blob: e3fde7cfc984c3dd080c08cf7e08c8cc0ea4fe08 [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:
107 if (Message.empty()) {
108 if (!UnknownObjCClass)
109 Diag(Loc, diag::err_unavailable) << D->getDeclName();
110 else
111 Diag(Loc, diag::warn_unavailable_fwdclass_message)
112 << D->getDeclName();
113 }
114 else
115 Diag(Loc, diag::err_unavailable_message)
116 << D->getDeclName() << Message;
John McCallf85e1932011-06-15 23:02:42 +0000117 Diag(D->getLocation(), diag::note_unavailable_here)
118 << isa<FunctionDecl>(D) << false;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000119 break;
120 }
121
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000122 // Warn if this is used but marked unused.
123 if (D->hasAttr<UnusedAttr>())
124 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
125
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000126 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000127}
128
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000129/// \brief Retrieve the message suffix that should be added to a
130/// diagnostic complaining about the given function being deleted or
131/// unavailable.
132std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
133 // FIXME: C++0x implicitly-deleted special member functions could be
134 // detected here so that we could improve diagnostics to say, e.g.,
135 // "base class 'A' had a deleted copy constructor".
136 if (FD->isDeleted())
137 return std::string();
138
139 std::string Message;
140 if (FD->getAvailability(&Message))
141 return ": " + Message;
142
143 return std::string();
144}
145
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000146/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +0000147/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000148/// attribute. It warns if call does not have the sentinel argument.
149///
150void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000151 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000152 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000153 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000154 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000155
156 // FIXME: In C++0x, if any of the arguments are parameter pack
157 // expansions, we can't check for the sentinel now.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000158 int sentinelPos = attr->getSentinel();
159 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +0000160
Mike Stump390b4cc2009-05-16 07:39:55 +0000161 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
162 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000163 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000164 bool warnNotEnoughArgs = false;
165 int isMethod = 0;
166 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
167 // skip over named parameters.
168 ObjCMethodDecl::param_iterator P, E = MD->param_end();
169 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
170 if (nullPos)
171 --nullPos;
172 else
173 ++i;
174 }
175 warnNotEnoughArgs = (P != E || i >= NumArgs);
176 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000177 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000178 // skip over named parameters.
179 ObjCMethodDecl::param_iterator P, E = FD->param_end();
180 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
181 if (nullPos)
182 --nullPos;
183 else
184 ++i;
185 }
186 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000187 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000188 // block or function pointer call.
189 QualType Ty = V->getType();
190 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000191 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000192 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
193 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000194 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
195 unsigned NumArgsInProto = Proto->getNumArgs();
196 unsigned k;
197 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
198 if (nullPos)
199 --nullPos;
200 else
201 ++i;
202 }
203 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
204 }
205 if (Ty->isBlockPointerType())
206 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000207 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000208 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000209 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000210 return;
211
212 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000213 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000214 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000215 return;
216 }
217 int sentinel = i;
218 while (sentinelPos > 0 && i < NumArgs-1) {
219 --sentinelPos;
220 ++i;
221 }
222 if (sentinelPos > 0) {
223 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000224 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000225 return;
226 }
227 while (i < NumArgs-1) {
228 ++i;
229 ++sentinel;
230 }
231 Expr *sentinelExpr = Args[sentinel];
John McCall8eb662e2010-05-06 23:53:00 +0000232 if (!sentinelExpr) return;
233 if (sentinelExpr->isTypeDependent()) return;
234 if (sentinelExpr->isValueDependent()) return;
Anders Carlsson343e6ff2010-11-05 15:21:33 +0000235
236 // nullptr_t is always treated as null.
237 if (sentinelExpr->getType()->isNullPtrType()) return;
238
Fariborz Jahanian9ccd7252010-07-14 16:37:51 +0000239 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall8eb662e2010-05-06 23:53:00 +0000240 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
241 Expr::NPC_ValueDependentIsNull))
242 return;
243
244 // Unfortunately, __null has type 'int'.
245 if (isa<GNUNullExpr>(sentinelExpr)) return;
246
247 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
248 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000249}
250
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000251SourceRange Sema::getExprRange(ExprTy *E) const {
252 Expr *Ex = (Expr *)E;
253 return Ex? Ex->getSourceRange() : SourceRange();
254}
255
Chris Lattnere7a2e912008-07-25 21:10:04 +0000256//===----------------------------------------------------------------------===//
257// Standard Promotions and Conversions
258//===----------------------------------------------------------------------===//
259
Chris Lattnere7a2e912008-07-25 21:10:04 +0000260/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000261ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000262 QualType Ty = E->getType();
263 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
264
Chris Lattnere7a2e912008-07-25 21:10:04 +0000265 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000266 E = ImpCastExprToType(E, Context.getPointerType(Ty),
267 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000268 else if (Ty->isArrayType()) {
269 // In C90 mode, arrays only promote to pointers if the array expression is
270 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
271 // type 'array of type' is converted to an expression that has type 'pointer
272 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
273 // that has type 'array of type' ...". The relevant change is "an lvalue"
274 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000275 //
276 // C++ 4.2p1:
277 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
278 // T" can be converted to an rvalue of type "pointer to T".
279 //
John McCall7eb0a9e2010-11-24 05:12:34 +0000280 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000281 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
282 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000283 }
John Wiegley429bb272011-04-08 18:41:53 +0000284 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000285}
286
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000287static void CheckForNullPointerDereference(Sema &S, Expr *E) {
288 // Check to see if we are dereferencing a null pointer. If so,
289 // and if not volatile-qualified, this is undefined behavior that the
290 // optimizer will delete, so warn about it. People sometimes try to use this
291 // to get a deterministic trap and are surprised by clang's behavior. This
292 // only handles the pattern "*null", which is a very syntactic check.
293 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
294 if (UO->getOpcode() == UO_Deref &&
295 UO->getSubExpr()->IgnoreParenCasts()->
296 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
297 !UO->getType().isVolatileQualified()) {
298 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
299 S.PDiag(diag::warn_indirection_through_null)
300 << UO->getSubExpr()->getSourceRange());
301 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
302 S.PDiag(diag::note_indirection_through_null));
303 }
304}
305
John Wiegley429bb272011-04-08 18:41:53 +0000306ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000307 // C++ [conv.lval]p1:
308 // A glvalue of a non-function, non-array type T can be
309 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000310 if (!E->isGLValue()) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +0000311
John McCall409fa9a2010-12-06 20:48:59 +0000312 QualType T = E->getType();
313 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000314
John McCall409fa9a2010-12-06 20:48:59 +0000315 // Create a load out of an ObjCProperty l-value, if necessary.
316 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley429bb272011-04-08 18:41:53 +0000317 ExprResult Res = ConvertPropertyForRValue(E);
318 if (Res.isInvalid())
319 return Owned(E);
320 E = Res.take();
John McCall409fa9a2010-12-06 20:48:59 +0000321 if (!E->isGLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000322 return Owned(E);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000323 }
John McCall409fa9a2010-12-06 20:48:59 +0000324
325 // We don't want to throw lvalue-to-rvalue casts on top of
326 // expressions of certain types in C++.
327 if (getLangOptions().CPlusPlus &&
328 (E->getType() == Context.OverloadTy ||
329 T->isDependentType() ||
330 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000331 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000332
333 // The C standard is actually really unclear on this point, and
334 // DR106 tells us what the result should be but not why. It's
335 // generally best to say that void types just doesn't undergo
336 // lvalue-to-rvalue at all. Note that expressions of unqualified
337 // 'void' type are never l-values, but qualified void can be.
338 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000339 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000340
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000341 CheckForNullPointerDereference(*this, E);
342
John McCall409fa9a2010-12-06 20:48:59 +0000343 // C++ [conv.lval]p1:
344 // [...] If T is a non-class type, the type of the prvalue is the
345 // cv-unqualified version of T. Otherwise, the type of the
346 // rvalue is T.
347 //
348 // C99 6.3.2.1p2:
349 // If the lvalue has qualified type, the value has the unqualified
350 // version of the type of the lvalue; otherwise, the value has the
351 // type of the lvalue.
352 if (T.hasQualifiers())
353 T = T.getUnqualifiedType();
354
Ted Kremenek3aea4da2011-03-01 18:41:00 +0000355 CheckArrayAccess(E);
Ted Kremeneka0125d82011-02-16 01:57:07 +0000356
John Wiegley429bb272011-04-08 18:41:53 +0000357 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
358 E, 0, VK_RValue));
John McCall409fa9a2010-12-06 20:48:59 +0000359}
360
John Wiegley429bb272011-04-08 18:41:53 +0000361ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
362 ExprResult Res = DefaultFunctionArrayConversion(E);
363 if (Res.isInvalid())
364 return ExprError();
365 Res = DefaultLvalueConversion(Res.take());
366 if (Res.isInvalid())
367 return ExprError();
368 return move(Res);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000369}
370
371
Chris Lattnere7a2e912008-07-25 21:10:04 +0000372/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000373/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000374/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000375/// apply if the array is an argument to the sizeof or address (&) operators.
376/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000377ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000378 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000379 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
380 if (Res.isInvalid())
381 return Owned(E);
382 E = Res.take();
John McCall0ae287a2010-12-01 04:43:34 +0000383
384 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000385 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCall0ae287a2010-12-01 04:43:34 +0000386
387 // Try to perform integral promotions if the object has a theoretically
388 // promotable type.
389 if (Ty->isIntegralOrUnscopedEnumerationType()) {
390 // C99 6.3.1.1p2:
391 //
392 // The following may be used in an expression wherever an int or
393 // unsigned int may be used:
394 // - an object or expression with an integer type whose integer
395 // conversion rank is less than or equal to the rank of int
396 // and unsigned int.
397 // - A bit-field of type _Bool, int, signed int, or unsigned int.
398 //
399 // If an int can represent all values of the original type, the
400 // value is converted to an int; otherwise, it is converted to an
401 // unsigned int. These are called the integer promotions. All
402 // other types are unchanged by the integer promotions.
403
404 QualType PTy = Context.isPromotableBitField(E);
405 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000406 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
407 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000408 }
409 if (Ty->isPromotableIntegerType()) {
410 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000411 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
412 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000413 }
Eli Friedman04e83572009-08-20 04:21:42 +0000414 }
John Wiegley429bb272011-04-08 18:41:53 +0000415 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000416}
417
Chris Lattner05faf172008-07-25 22:25:12 +0000418/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000419/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000420/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000421ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
422 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000423 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000424
John Wiegley429bb272011-04-08 18:41:53 +0000425 ExprResult Res = UsualUnaryConversions(E);
426 if (Res.isInvalid())
427 return Owned(E);
428 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000429
Chris Lattner05faf172008-07-25 22:25:12 +0000430 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000431 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000432 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
433
434 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000435}
436
Chris Lattner312531a2009-04-12 08:11:20 +0000437/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
438/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley429bb272011-04-08 18:41:53 +0000439/// interfaces passed by value.
440ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000441 FunctionDecl *FDecl) {
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000442 ExprResult ExprRes = CheckPlaceholderExpr(E);
443 if (ExprRes.isInvalid())
444 return ExprError();
445
446 ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000447 if (ExprRes.isInvalid())
448 return ExprError();
449 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000450
Chris Lattner40378332010-05-16 04:01:30 +0000451 // __builtin_va_start takes the second argument as a "varargs" argument, but
452 // it doesn't actually do anything with it. It doesn't need to be non-pod
453 // etc.
454 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
John Wiegley429bb272011-04-08 18:41:53 +0000455 return Owned(E);
Chris Lattner40378332010-05-16 04:01:30 +0000456
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000457 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley429bb272011-04-08 18:41:53 +0000458 if (E->getType()->isObjCObjectType() &&
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000459 DiagRuntimeBehavior(E->getLocStart(), 0,
460 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
461 << E->getType() << CT))
John Wiegley429bb272011-04-08 18:41:53 +0000462 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000463
John McCallf85e1932011-06-15 23:02:42 +0000464 if (!E->getType().isPODType(Context)) {
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000465 // C++0x [expr.call]p7:
466 // Passing a potentially-evaluated argument of class type (Clause 9)
467 // having a non-trivial copy constructor, a non-trivial move constructor,
468 // or a non-trivial destructor, with no corresponding parameter,
469 // is conditionally-supported with implementation-defined semantics.
470 bool TrivialEnough = false;
471 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
472 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
473 if (Record->hasTrivialCopyConstructor() &&
474 Record->hasTrivialMoveConstructor() &&
475 Record->hasTrivialDestructor())
476 TrivialEnough = true;
477 }
478 }
John McCallf85e1932011-06-15 23:02:42 +0000479
480 if (!TrivialEnough &&
481 getLangOptions().ObjCAutoRefCount &&
482 E->getType()->isObjCLifetimeType())
483 TrivialEnough = true;
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000484
485 if (TrivialEnough) {
486 // Nothing to diagnose. This is okay.
487 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000488 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000489 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000490 << CT)) {
491 // Turn this into a trap.
492 CXXScopeSpec SS;
493 UnqualifiedId Name;
494 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
495 E->getLocStart());
496 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
497 if (TrapFn.isInvalid())
498 return ExprError();
499
500 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
501 MultiExprArg(), E->getLocEnd());
502 if (Call.isInvalid())
503 return ExprError();
504
505 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
506 Call.get(), E);
507 if (Comma.isInvalid())
508 return ExprError();
509
510 E = Comma.get();
511 }
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000512 }
513
John Wiegley429bb272011-04-08 18:41:53 +0000514 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000515}
516
Chris Lattnere7a2e912008-07-25 21:10:04 +0000517/// UsualArithmeticConversions - Performs various conversions that are common to
518/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000519/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000520/// responsible for emitting appropriate error diagnostics.
521/// FIXME: verify the conversion rules for "complex int" are consistent with
522/// GCC.
John Wiegley429bb272011-04-08 18:41:53 +0000523QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr, ExprResult &rhsExpr,
Chris Lattnere7a2e912008-07-25 21:10:04 +0000524 bool isCompAssign) {
John Wiegley429bb272011-04-08 18:41:53 +0000525 if (!isCompAssign) {
526 lhsExpr = UsualUnaryConversions(lhsExpr.take());
527 if (lhsExpr.isInvalid())
528 return QualType();
529 }
Eli Friedmanab3a8522009-03-28 01:22:36 +0000530
John Wiegley429bb272011-04-08 18:41:53 +0000531 rhsExpr = UsualUnaryConversions(rhsExpr.take());
532 if (rhsExpr.isInvalid())
533 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000534
Mike Stump1eb44332009-09-09 15:08:12 +0000535 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000536 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000537 QualType lhs =
John Wiegley429bb272011-04-08 18:41:53 +0000538 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000539 QualType rhs =
John Wiegley429bb272011-04-08 18:41:53 +0000540 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000541
542 // If both types are identical, no conversion is needed.
543 if (lhs == rhs)
544 return lhs;
545
546 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
547 // The caller can deal with this (e.g. pointer + int).
548 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
549 return lhs;
550
John McCallcf33b242010-11-13 08:17:45 +0000551 // Apply unary and bitfield promotions to the LHS's type.
552 QualType lhs_unpromoted = lhs;
553 if (lhs->isPromotableIntegerType())
554 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley429bb272011-04-08 18:41:53 +0000555 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +0000556 if (!LHSBitfieldPromoteTy.isNull())
557 lhs = LHSBitfieldPromoteTy;
John McCallcf33b242010-11-13 08:17:45 +0000558 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000559 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000560
John McCallcf33b242010-11-13 08:17:45 +0000561 // If both types are identical, no conversion is needed.
562 if (lhs == rhs)
563 return lhs;
564
565 // At this point, we have two different arithmetic types.
566
567 // Handle complex types first (C99 6.3.1.8p1).
568 bool LHSComplexFloat = lhs->isComplexType();
569 bool RHSComplexFloat = rhs->isComplexType();
570 if (LHSComplexFloat || RHSComplexFloat) {
571 // if we have an integer operand, the result is the complex type.
572
John McCall2bb5d002010-11-13 09:02:35 +0000573 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
574 if (rhs->isIntegerType()) {
575 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000576 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
577 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000578 } else {
579 assert(rhs->isComplexIntegerType());
John Wiegley429bb272011-04-08 18:41:53 +0000580 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000581 }
John McCallcf33b242010-11-13 08:17:45 +0000582 return lhs;
583 }
584
John McCall2bb5d002010-11-13 09:02:35 +0000585 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
586 if (!isCompAssign) {
587 // int -> float -> _Complex float
588 if (lhs->isIntegerType()) {
589 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000590 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_IntegralToFloating);
591 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000592 } else {
593 assert(lhs->isComplexIntegerType());
John Wiegley429bb272011-04-08 18:41:53 +0000594 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000595 }
596 }
John McCallcf33b242010-11-13 08:17:45 +0000597 return rhs;
598 }
599
600 // This handles complex/complex, complex/float, or float/complex.
601 // When both operands are complex, the shorter operand is converted to the
602 // type of the longer, and that is the type of the result. This corresponds
603 // to what is done when combining two real floating-point operands.
604 // The fun begins when size promotion occur across type domains.
605 // From H&S 6.3.4: When one operand is complex and the other is a real
606 // floating-point type, the less precise type is converted, within it's
607 // real or complex domain, to the precision of the other type. For example,
608 // when combining a "long double" with a "double _Complex", the
609 // "double _Complex" is promoted to "long double _Complex".
610 int order = Context.getFloatingTypeOrder(lhs, rhs);
611
612 // If both are complex, just cast to the more precise type.
613 if (LHSComplexFloat && RHSComplexFloat) {
614 if (order > 0) {
615 // _Complex float -> _Complex double
John Wiegley429bb272011-04-08 18:41:53 +0000616 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000617 return lhs;
618
619 } else if (order < 0) {
620 // _Complex float -> _Complex double
621 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000622 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000623 return rhs;
624 }
625 return lhs;
626 }
627
628 // If just the LHS is complex, the RHS needs to be converted,
629 // and the LHS might need to be promoted.
630 if (LHSComplexFloat) {
631 if (order > 0) { // LHS is wider
632 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000633 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000634 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
635 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000636 return lhs;
637 }
638
639 // RHS is at least as wide. Find its corresponding complex type.
640 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
641
642 // double -> _Complex double
John Wiegley429bb272011-04-08 18:41:53 +0000643 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000644
645 // _Complex float -> _Complex double
646 if (!isCompAssign && order < 0)
John Wiegley429bb272011-04-08 18:41:53 +0000647 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000648
649 return result;
650 }
651
652 // Just the RHS is complex, so the LHS needs to be converted
653 // and the RHS might need to be promoted.
654 assert(RHSComplexFloat);
655
656 if (order < 0) { // RHS is wider
657 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000658 if (!isCompAssign) {
Argyrios Kyrtzidise1889332011-01-18 18:49:33 +0000659 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000660 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
661 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000662 }
John McCallcf33b242010-11-13 08:17:45 +0000663 return rhs;
664 }
665
666 // LHS is at least as wide. Find its corresponding complex type.
667 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
668
669 // double -> _Complex double
670 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000671 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000672
673 // _Complex float -> _Complex double
674 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +0000675 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000676
677 return result;
678 }
679
680 // Now handle "real" floating types (i.e. float, double, long double).
681 bool LHSFloat = lhs->isRealFloatingType();
682 bool RHSFloat = rhs->isRealFloatingType();
683 if (LHSFloat || RHSFloat) {
684 // If we have two real floating types, convert the smaller operand
685 // to the bigger result.
686 if (LHSFloat && RHSFloat) {
687 int order = Context.getFloatingTypeOrder(lhs, rhs);
688 if (order > 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000689 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCallcf33b242010-11-13 08:17:45 +0000690 return lhs;
691 }
692
693 assert(order < 0 && "illegal float comparison");
694 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000695 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCallcf33b242010-11-13 08:17:45 +0000696 return rhs;
697 }
698
699 // If we have an integer operand, the result is the real floating type.
700 if (LHSFloat) {
701 if (rhs->isIntegerType()) {
702 // Convert rhs to the lhs floating point type.
John Wiegley429bb272011-04-08 18:41:53 +0000703 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCallcf33b242010-11-13 08:17:45 +0000704 return lhs;
705 }
706
707 // Convert both sides to the appropriate complex float.
708 assert(rhs->isComplexIntegerType());
709 QualType result = Context.getComplexType(lhs);
710
711 // _Complex int -> _Complex float
John Wiegley429bb272011-04-08 18:41:53 +0000712 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000713
714 // float -> _Complex float
715 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000716 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000717
718 return result;
719 }
720
721 assert(RHSFloat);
722 if (lhs->isIntegerType()) {
723 // Convert lhs to the rhs floating point type.
724 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000725 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCallcf33b242010-11-13 08:17:45 +0000726 return rhs;
727 }
728
729 // Convert both sides to the appropriate complex float.
730 assert(lhs->isComplexIntegerType());
731 QualType result = Context.getComplexType(rhs);
732
733 // _Complex int -> _Complex float
734 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000735 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000736
737 // float -> _Complex float
John Wiegley429bb272011-04-08 18:41:53 +0000738 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000739
740 return result;
741 }
742
743 // Handle GCC complex int extension.
744 // FIXME: if the operands are (int, _Complex long), we currently
745 // don't promote the complex. Also, signedness?
746 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
747 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
748 if (lhsComplexInt && rhsComplexInt) {
749 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
750 rhsComplexInt->getElementType());
751 assert(order && "inequal types with equal element ordering");
752 if (order > 0) {
753 // _Complex int -> _Complex long
John Wiegley429bb272011-04-08 18:41:53 +0000754 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000755 return lhs;
756 }
757
758 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000759 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000760 return rhs;
761 } else if (lhsComplexInt) {
762 // int -> _Complex int
John Wiegley429bb272011-04-08 18:41:53 +0000763 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000764 return lhs;
765 } else if (rhsComplexInt) {
766 // int -> _Complex int
767 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000768 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000769 return rhs;
770 }
771
772 // Finally, we have two differing integer types.
773 // The rules for this case are in C99 6.3.1.8
774 int compare = Context.getIntegerTypeOrder(lhs, rhs);
775 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
776 rhsSigned = rhs->hasSignedIntegerRepresentation();
777 if (lhsSigned == rhsSigned) {
778 // Same signedness; use the higher-ranked type
779 if (compare >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000780 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000781 return lhs;
782 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000783 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000784 return rhs;
785 } else if (compare != (lhsSigned ? 1 : -1)) {
786 // The unsigned type has greater than or equal rank to the
787 // signed type, so use the unsigned type
788 if (rhsSigned) {
John Wiegley429bb272011-04-08 18:41:53 +0000789 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000790 return lhs;
791 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000792 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000793 return rhs;
794 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
795 // The two types are different widths; if we are here, that
796 // means the signed type is larger than the unsigned type, so
797 // use the signed type.
798 if (lhsSigned) {
John Wiegley429bb272011-04-08 18:41:53 +0000799 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000800 return lhs;
801 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000802 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000803 return rhs;
804 } else {
805 // The signed type is higher-ranked than the unsigned type,
806 // but isn't actually any bigger (like unsigned int and long
807 // on most 32-bit systems). Use the unsigned type corresponding
808 // to the signed type.
809 QualType result =
810 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley429bb272011-04-08 18:41:53 +0000811 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000812 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000813 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000814 return result;
815 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000816}
817
Chris Lattnere7a2e912008-07-25 21:10:04 +0000818//===----------------------------------------------------------------------===//
819// Semantic Analysis for various Expression Types
820//===----------------------------------------------------------------------===//
821
822
Peter Collingbournef111d932011-04-15 00:35:48 +0000823ExprResult
824Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
825 SourceLocation DefaultLoc,
826 SourceLocation RParenLoc,
827 Expr *ControllingExpr,
828 MultiTypeArg types,
829 MultiExprArg exprs) {
830 unsigned NumAssocs = types.size();
831 assert(NumAssocs == exprs.size());
832
833 ParsedType *ParsedTypes = types.release();
834 Expr **Exprs = exprs.release();
835
836 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
837 for (unsigned i = 0; i < NumAssocs; ++i) {
838 if (ParsedTypes[i])
839 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
840 else
841 Types[i] = 0;
842 }
843
844 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
845 ControllingExpr, Types, Exprs,
846 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +0000847 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +0000848 return ER;
849}
850
851ExprResult
852Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
853 SourceLocation DefaultLoc,
854 SourceLocation RParenLoc,
855 Expr *ControllingExpr,
856 TypeSourceInfo **Types,
857 Expr **Exprs,
858 unsigned NumAssocs) {
859 bool TypeErrorFound = false,
860 IsResultDependent = ControllingExpr->isTypeDependent(),
861 ContainsUnexpandedParameterPack
862 = ControllingExpr->containsUnexpandedParameterPack();
863
864 for (unsigned i = 0; i < NumAssocs; ++i) {
865 if (Exprs[i]->containsUnexpandedParameterPack())
866 ContainsUnexpandedParameterPack = true;
867
868 if (Types[i]) {
869 if (Types[i]->getType()->containsUnexpandedParameterPack())
870 ContainsUnexpandedParameterPack = true;
871
872 if (Types[i]->getType()->isDependentType()) {
873 IsResultDependent = true;
874 } else {
875 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
876 // complete object type other than a variably modified type."
877 unsigned D = 0;
878 if (Types[i]->getType()->isIncompleteType())
879 D = diag::err_assoc_type_incomplete;
880 else if (!Types[i]->getType()->isObjectType())
881 D = diag::err_assoc_type_nonobject;
882 else if (Types[i]->getType()->isVariablyModifiedType())
883 D = diag::err_assoc_type_variably_modified;
884
885 if (D != 0) {
886 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
887 << Types[i]->getTypeLoc().getSourceRange()
888 << Types[i]->getType();
889 TypeErrorFound = true;
890 }
891
892 // C1X 6.5.1.1p2 "No two generic associations in the same generic
893 // selection shall specify compatible types."
894 for (unsigned j = i+1; j < NumAssocs; ++j)
895 if (Types[j] && !Types[j]->getType()->isDependentType() &&
896 Context.typesAreCompatible(Types[i]->getType(),
897 Types[j]->getType())) {
898 Diag(Types[j]->getTypeLoc().getBeginLoc(),
899 diag::err_assoc_compatible_types)
900 << Types[j]->getTypeLoc().getSourceRange()
901 << Types[j]->getType()
902 << Types[i]->getType();
903 Diag(Types[i]->getTypeLoc().getBeginLoc(),
904 diag::note_compat_assoc)
905 << Types[i]->getTypeLoc().getSourceRange()
906 << Types[i]->getType();
907 TypeErrorFound = true;
908 }
909 }
910 }
911 }
912 if (TypeErrorFound)
913 return ExprError();
914
915 // If we determined that the generic selection is result-dependent, don't
916 // try to compute the result expression.
917 if (IsResultDependent)
918 return Owned(new (Context) GenericSelectionExpr(
919 Context, KeyLoc, ControllingExpr,
920 Types, Exprs, NumAssocs, DefaultLoc,
921 RParenLoc, ContainsUnexpandedParameterPack));
922
923 llvm::SmallVector<unsigned, 1> CompatIndices;
924 unsigned DefaultIndex = -1U;
925 for (unsigned i = 0; i < NumAssocs; ++i) {
926 if (!Types[i])
927 DefaultIndex = i;
928 else if (Context.typesAreCompatible(ControllingExpr->getType(),
929 Types[i]->getType()))
930 CompatIndices.push_back(i);
931 }
932
933 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
934 // type compatible with at most one of the types named in its generic
935 // association list."
936 if (CompatIndices.size() > 1) {
937 // We strip parens here because the controlling expression is typically
938 // parenthesized in macro definitions.
939 ControllingExpr = ControllingExpr->IgnoreParens();
940 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
941 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
942 << (unsigned) CompatIndices.size();
943 for (llvm::SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
944 E = CompatIndices.end(); I != E; ++I) {
945 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
946 diag::note_compat_assoc)
947 << Types[*I]->getTypeLoc().getSourceRange()
948 << Types[*I]->getType();
949 }
950 return ExprError();
951 }
952
953 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
954 // its controlling expression shall have type compatible with exactly one of
955 // the types named in its generic association list."
956 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
957 // We strip parens here because the controlling expression is typically
958 // parenthesized in macro definitions.
959 ControllingExpr = ControllingExpr->IgnoreParens();
960 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
961 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
962 return ExprError();
963 }
964
965 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
966 // type name that is compatible with the type of the controlling expression,
967 // then the result expression of the generic selection is the expression
968 // in that generic association. Otherwise, the result expression of the
969 // generic selection is the expression in the default generic association."
970 unsigned ResultIndex =
971 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
972
973 return Owned(new (Context) GenericSelectionExpr(
974 Context, KeyLoc, ControllingExpr,
975 Types, Exprs, NumAssocs, DefaultLoc,
976 RParenLoc, ContainsUnexpandedParameterPack,
977 ResultIndex));
978}
979
Steve Narofff69936d2007-09-16 03:34:24 +0000980/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000981/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
982/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
983/// multiple tokens. However, the common case is that StringToks points to one
984/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000985///
John McCall60d7b3a2010-08-24 06:29:42 +0000986ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +0000987Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000988 assert(NumStringToks && "Must have at least one string!");
989
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000990 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000991 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000992 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000993
994 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
995 for (unsigned i = 0; i != NumStringToks; ++i)
996 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000997
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000998 QualType StrTy = Context.CharTy;
Anders Carlsson96b4adc2011-04-06 18:42:48 +0000999 if (Literal.AnyWide)
1000 StrTy = Context.getWCharType();
1001 else if (Literal.Pascal)
1002 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001003
1004 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +00001005 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001006 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001007
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001008 // Get an array type for the string, according to C99 6.4.5. This includes
1009 // the nul terminator character as well as the string length for pascal
1010 // strings.
1011 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001012 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001013 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001014
Reid Spencer5f016e22007-07-11 17:01:13 +00001015 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +00001016 return Owned(StringLiteral::Create(Context, Literal.GetString(),
1017 Literal.GetStringLength(),
Anders Carlsson3e2193c2011-04-14 00:40:03 +00001018 Literal.AnyWide, Literal.Pascal, StrTy,
Sean Hunt6cf75022010-08-30 17:47:05 +00001019 &StringTokLocs[0],
1020 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001021}
1022
John McCall469a1eb2011-02-02 13:00:07 +00001023enum CaptureResult {
1024 /// No capture is required.
1025 CR_NoCapture,
1026
1027 /// A capture is required.
1028 CR_Capture,
1029
John McCall6b5a61b2011-02-07 10:33:21 +00001030 /// A by-ref capture is required.
1031 CR_CaptureByRef,
1032
John McCall469a1eb2011-02-02 13:00:07 +00001033 /// An error occurred when trying to capture the given variable.
1034 CR_Error
1035};
1036
1037/// Diagnose an uncapturable value reference.
Chris Lattner639e2d32008-10-20 05:16:36 +00001038///
John McCall469a1eb2011-02-02 13:00:07 +00001039/// \param var - the variable referenced
1040/// \param DC - the context which we couldn't capture through
1041static CaptureResult
John McCall6b5a61b2011-02-07 10:33:21 +00001042diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001043 VarDecl *var, DeclContext *DC) {
1044 switch (S.ExprEvalContexts.back().Context) {
1045 case Sema::Unevaluated:
1046 // The argument will never be evaluated, so don't complain.
1047 return CR_NoCapture;
Mike Stump1eb44332009-09-09 15:08:12 +00001048
John McCall469a1eb2011-02-02 13:00:07 +00001049 case Sema::PotentiallyEvaluated:
1050 case Sema::PotentiallyEvaluatedIfUsed:
1051 break;
Chris Lattner639e2d32008-10-20 05:16:36 +00001052
John McCall469a1eb2011-02-02 13:00:07 +00001053 case Sema::PotentiallyPotentiallyEvaluated:
1054 // FIXME: delay these!
1055 break;
Chris Lattner17f3a6d2009-04-21 22:26:47 +00001056 }
Mike Stump1eb44332009-09-09 15:08:12 +00001057
John McCall469a1eb2011-02-02 13:00:07 +00001058 // Don't diagnose about capture if we're not actually in code right
1059 // now; in general, there are more appropriate places that will
1060 // diagnose this.
1061 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1062
John McCall4f38f412011-03-22 23:15:50 +00001063 // Certain madnesses can happen with parameter declarations, which
1064 // we want to ignore.
1065 if (isa<ParmVarDecl>(var)) {
1066 // - If the parameter still belongs to the translation unit, then
1067 // we're actually just using one parameter in the declaration of
1068 // the next. This is useful in e.g. VLAs.
1069 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1070 return CR_NoCapture;
1071
1072 // - This particular madness can happen in ill-formed default
1073 // arguments; claim it's okay and let downstream code handle it.
1074 if (S.CurContext == var->getDeclContext()->getParent())
1075 return CR_NoCapture;
1076 }
John McCall469a1eb2011-02-02 13:00:07 +00001077
1078 DeclarationName functionName;
1079 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1080 functionName = fn->getDeclName();
1081 // FIXME: variable from enclosing block that we couldn't capture from!
1082
1083 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1084 << var->getIdentifier() << functionName;
1085 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1086 << var->getIdentifier();
1087
1088 return CR_Error;
Mike Stump1eb44332009-09-09 15:08:12 +00001089}
1090
John McCall6b5a61b2011-02-07 10:33:21 +00001091/// There is a well-formed capture at a particular scope level;
1092/// propagate it through all the nested blocks.
1093static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1094 const BlockDecl::Capture &capture) {
1095 VarDecl *var = capture.getVariable();
1096
1097 // Update all the inner blocks with the capture information.
1098 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1099 i != e; ++i) {
1100 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1101 innerBlock->Captures.push_back(
1102 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1103 /*nested*/ true, capture.getCopyExpr()));
1104 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1105 }
1106
1107 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1108}
1109
1110/// shouldCaptureValueReference - Determine if a reference to the
John McCall469a1eb2011-02-02 13:00:07 +00001111/// given value in the current context requires a variable capture.
1112///
1113/// This also keeps the captures set in the BlockScopeInfo records
1114/// up-to-date.
John McCall6b5a61b2011-02-07 10:33:21 +00001115static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001116 ValueDecl *value) {
1117 // Only variables ever require capture.
1118 VarDecl *var = dyn_cast<VarDecl>(value);
John McCall76a40212011-02-09 01:13:10 +00001119 if (!var) return CR_NoCapture;
John McCall469a1eb2011-02-02 13:00:07 +00001120
1121 // Fast path: variables from the current context never require capture.
1122 DeclContext *DC = S.CurContext;
1123 if (var->getDeclContext() == DC) return CR_NoCapture;
1124
1125 // Only variables with local storage require capture.
1126 // FIXME: What about 'const' variables in C++?
1127 if (!var->hasLocalStorage()) return CR_NoCapture;
1128
1129 // Otherwise, we need to capture.
1130
1131 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCall469a1eb2011-02-02 13:00:07 +00001132 do {
1133 // Only blocks (and eventually C++0x closures) can capture; other
1134 // scopes don't work.
1135 if (!isa<BlockDecl>(DC))
John McCall6b5a61b2011-02-07 10:33:21 +00001136 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCall469a1eb2011-02-02 13:00:07 +00001137
1138 BlockScopeInfo *blockScope =
1139 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1140 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1141
John McCall6b5a61b2011-02-07 10:33:21 +00001142 // Check whether we've already captured it in this block. If so,
1143 // we're done.
1144 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1145 return propagateCapture(S, functionScopesIndex,
1146 blockScope->Captures[indexPlus1 - 1]);
John McCall469a1eb2011-02-02 13:00:07 +00001147
1148 functionScopesIndex--;
1149 DC = cast<BlockDecl>(DC)->getDeclContext();
1150 } while (var->getDeclContext() != DC);
1151
John McCall6b5a61b2011-02-07 10:33:21 +00001152 // Okay, we descended all the way to the block that defines the variable.
1153 // Actually try to capture it.
1154 QualType type = var->getType();
1155
1156 // Prohibit variably-modified types.
1157 if (type->isVariablyModifiedType()) {
1158 S.Diag(loc, diag::err_ref_vm_type);
1159 S.Diag(var->getLocation(), diag::note_declared_at);
1160 return CR_Error;
1161 }
1162
1163 // Prohibit arrays, even in __block variables, but not references to
1164 // them.
1165 if (type->isArrayType()) {
1166 S.Diag(loc, diag::err_ref_array_type);
1167 S.Diag(var->getLocation(), diag::note_declared_at);
1168 return CR_Error;
1169 }
1170
1171 S.MarkDeclarationReferenced(loc, var);
1172
1173 // The BlocksAttr indicates the variable is bound by-reference.
1174 bool byRef = var->hasAttr<BlocksAttr>();
1175
1176 // Build a copy expression.
1177 Expr *copyExpr = 0;
John McCall642a75f2011-04-28 02:15:35 +00001178 const RecordType *rtype;
1179 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1180 (rtype = type->getAs<RecordType>())) {
1181
1182 // The capture logic needs the destructor, so make sure we mark it.
1183 // Usually this is unnecessary because most local variables have
1184 // their destructors marked at declaration time, but parameters are
1185 // an exception because it's technically only the call site that
1186 // actually requires the destructor.
1187 if (isa<ParmVarDecl>(var))
1188 S.FinalizeVarWithDestructor(var, rtype);
1189
John McCall6b5a61b2011-02-07 10:33:21 +00001190 // According to the blocks spec, the capture of a variable from
1191 // the stack requires a const copy constructor. This is not true
1192 // of the copy/move done to move a __block variable to the heap.
1193 type.addConst();
1194
1195 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1196 ExprResult result =
1197 S.PerformCopyInitialization(
1198 InitializedEntity::InitializeBlock(var->getLocation(),
1199 type, false),
1200 loc, S.Owned(declRef));
1201
1202 // Build a full-expression copy expression if initialization
1203 // succeeded and used a non-trivial constructor. Recover from
1204 // errors by pretending that the copy isn't necessary.
1205 if (!result.isInvalid() &&
1206 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1207 result = S.MaybeCreateExprWithCleanups(result);
1208 copyExpr = result.take();
1209 }
1210 }
1211
1212 // We're currently at the declarer; go back to the closure.
1213 functionScopesIndex++;
1214 BlockScopeInfo *blockScope =
1215 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1216
1217 // Build a valid capture in this scope.
1218 blockScope->Captures.push_back(
1219 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1220 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1221
1222 // Propagate that to inner captures if necessary.
1223 return propagateCapture(S, functionScopesIndex,
1224 blockScope->Captures.back());
1225}
1226
1227static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1228 const DeclarationNameInfo &NameInfo,
1229 bool byRef) {
1230 assert(isa<VarDecl>(vd) && "capturing non-variable");
1231
1232 VarDecl *var = cast<VarDecl>(vd);
1233 assert(var->hasLocalStorage() && "capturing non-local");
1234 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1235
1236 QualType exprType = var->getType().getNonReferenceType();
1237
1238 BlockDeclRefExpr *BDRE;
1239 if (!byRef) {
1240 // The variable will be bound by copy; make it const within the
1241 // closure, but record that this was done in the expression.
1242 bool constAdded = !exprType.isConstQualified();
1243 exprType.addConst();
1244
1245 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1246 NameInfo.getLoc(), false,
1247 constAdded);
1248 } else {
1249 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1250 NameInfo.getLoc(), true);
1251 }
1252
1253 return S.Owned(BDRE);
John McCall469a1eb2011-02-02 13:00:07 +00001254}
Chris Lattner639e2d32008-10-20 05:16:36 +00001255
John McCall60d7b3a2010-08-24 06:29:42 +00001256ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001257Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001258 SourceLocation Loc,
1259 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001260 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001261 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001262}
1263
John McCall76a40212011-02-09 01:13:10 +00001264/// BuildDeclRefExpr - Build an expression that references a
1265/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001266ExprResult
John McCall76a40212011-02-09 01:13:10 +00001267Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001268 const DeclarationNameInfo &NameInfo,
1269 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001270 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +00001271
John McCall7eb0a9e2010-11-24 05:12:34 +00001272 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +00001273 SS? SS->getWithLocInContext(Context)
1274 : NestedNameSpecifierLoc(),
John McCall7eb0a9e2010-11-24 05:12:34 +00001275 D, NameInfo, Ty, VK);
1276
1277 // Just in case we're building an illegal pointer-to-member.
1278 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1279 E->setObjectKind(OK_BitField);
1280
1281 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001282}
1283
John McCalldfa1edb2010-11-23 20:48:44 +00001284static ExprResult
1285BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1286 const CXXScopeSpec &SS, FieldDecl *Field,
1287 DeclAccessPair FoundDecl,
1288 const DeclarationNameInfo &MemberNameInfo);
1289
John McCall60d7b3a2010-08-24 06:29:42 +00001290ExprResult
John McCall5808ce42011-02-03 08:15:49 +00001291Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
1292 SourceLocation loc,
1293 IndirectFieldDecl *indirectField,
1294 Expr *baseObjectExpr,
1295 SourceLocation opLoc) {
1296 // First, build the expression that refers to the base object.
1297
1298 bool baseObjectIsPointer = false;
1299 Qualifiers baseQuals;
1300
1301 // Case 1: the base of the indirect field is not a field.
1302 VarDecl *baseVariable = indirectField->getVarDecl();
Douglas Gregorf5848322011-02-18 02:44:58 +00001303 CXXScopeSpec EmptySS;
John McCall5808ce42011-02-03 08:15:49 +00001304 if (baseVariable) {
1305 assert(baseVariable->getType()->isRecordType());
1306
1307 // In principle we could have a member access expression that
1308 // accesses an anonymous struct/union that's a static member of
1309 // the base object's class. However, under the current standard,
1310 // static data members cannot be anonymous structs or unions.
1311 // Supporting this is as easy as building a MemberExpr here.
1312 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1313
1314 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1315
1316 ExprResult result =
Douglas Gregorf5848322011-02-18 02:44:58 +00001317 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
John McCall5808ce42011-02-03 08:15:49 +00001318 if (result.isInvalid()) return ExprError();
1319
1320 baseObjectExpr = result.take();
1321 baseObjectIsPointer = false;
1322 baseQuals = baseObjectExpr->getType().getQualifiers();
1323
1324 // Case 2: the base of the indirect field is a field and the user
1325 // wrote a member expression.
1326 } else if (baseObjectExpr) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001327 // The caller provided the base object expression. Determine
1328 // whether its a pointer and whether it adds any qualifiers to the
1329 // anonymous struct/union fields we're looking into.
John McCall5808ce42011-02-03 08:15:49 +00001330 QualType objectType = baseObjectExpr->getType();
1331
1332 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1333 baseObjectIsPointer = true;
1334 objectType = ptr->getPointeeType();
1335 } else {
1336 baseObjectIsPointer = false;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001337 }
John McCall5808ce42011-02-03 08:15:49 +00001338 baseQuals = objectType.getQualifiers();
1339
1340 // Case 3: the base of the indirect field is a field and we should
1341 // build an implicit member access.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001342 } else {
1343 // We've found a member of an anonymous struct/union that is
1344 // inside a non-anonymous struct/union, so in a well-formed
1345 // program our base object expression is "this".
Richard Smith7a614d82011-06-11 17:19:42 +00001346 QualType ThisTy = getAndCaptureCurrentThisType();
1347 if (ThisTy.isNull()) {
John McCall5808ce42011-02-03 08:15:49 +00001348 Diag(loc, diag::err_invalid_member_use_in_static_method)
1349 << indirectField->getDeclName();
1350 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001351 }
1352
John McCall5808ce42011-02-03 08:15:49 +00001353 // Our base object expression is "this".
1354 baseObjectExpr =
Richard Smith7a614d82011-06-11 17:19:42 +00001355 new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
John McCall5808ce42011-02-03 08:15:49 +00001356 baseObjectIsPointer = true;
Richard Smith7a614d82011-06-11 17:19:42 +00001357 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001358 }
1359
1360 // Build the implicit member references to the field of the
1361 // anonymous struct/union.
John McCall5808ce42011-02-03 08:15:49 +00001362 Expr *result = baseObjectExpr;
1363 IndirectFieldDecl::chain_iterator
1364 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCalldfa1edb2010-11-23 20:48:44 +00001365
John McCall5808ce42011-02-03 08:15:49 +00001366 // Build the first member access in the chain with full information.
1367 if (!baseVariable) {
1368 FieldDecl *field = cast<FieldDecl>(*FI);
John McCalldfa1edb2010-11-23 20:48:44 +00001369
John McCall5808ce42011-02-03 08:15:49 +00001370 // FIXME: use the real found-decl info!
1371 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall0953e762009-09-24 19:53:00 +00001372
John McCall5808ce42011-02-03 08:15:49 +00001373 // Make a nameInfo that properly uses the anonymous name.
1374 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall0953e762009-09-24 19:53:00 +00001375
John McCall5808ce42011-02-03 08:15:49 +00001376 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Douglas Gregorf5848322011-02-18 02:44:58 +00001377 EmptySS, field, foundDecl,
John McCall5808ce42011-02-03 08:15:49 +00001378 memberNameInfo).take();
1379 baseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +00001380
John McCall5808ce42011-02-03 08:15:49 +00001381 // FIXME: check qualified member access
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001382 }
1383
John McCall5808ce42011-02-03 08:15:49 +00001384 // In all cases, we should now skip the first declaration in the chain.
1385 ++FI;
1386
Douglas Gregorf5848322011-02-18 02:44:58 +00001387 while (FI != FEnd) {
1388 FieldDecl *field = cast<FieldDecl>(*FI++);
John McCall5808ce42011-02-03 08:15:49 +00001389
1390 // FIXME: these are somewhat meaningless
1391 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1392 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall5808ce42011-02-03 08:15:49 +00001393
1394 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Douglas Gregorf5848322011-02-18 02:44:58 +00001395 (FI == FEnd? SS : EmptySS), field,
1396 foundDecl, memberNameInfo)
John McCall5808ce42011-02-03 08:15:49 +00001397 .take();
1398 }
1399
1400 return Owned(result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001401}
1402
Abramo Bagnara25777432010-08-11 22:01:17 +00001403/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001404/// possibly a list of template arguments.
1405///
1406/// If this produces template arguments, it is permitted to call
1407/// DecomposeTemplateName.
1408///
1409/// This actually loses a lot of source location information for
1410/// non-standard name kinds; we should consider preserving that in
1411/// some way.
1412static void DecomposeUnqualifiedId(Sema &SemaRef,
1413 const UnqualifiedId &Id,
1414 TemplateArgumentListInfo &Buffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00001415 DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00001416 const TemplateArgumentListInfo *&TemplateArgs) {
1417 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1418 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1419 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1420
1421 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1422 Id.TemplateId->getTemplateArgs(),
1423 Id.TemplateId->NumArgs);
1424 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1425 TemplateArgsPtr.release();
1426
John McCall2b5289b2010-08-23 07:28:44 +00001427 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001428 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1429 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001430 TemplateArgs = &Buffer;
1431 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001432 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001433 TemplateArgs = 0;
1434 }
1435}
1436
John McCallaa81e162009-12-01 22:10:20 +00001437/// Determines if the given class is provably not derived from all of
1438/// the prospective base classes.
1439static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1440 CXXRecordDecl *Record,
1441 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +00001442 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +00001443 return false;
1444
Douglas Gregor952b0172010-02-11 01:04:33 +00001445 RecordDecl *RD = Record->getDefinition();
John McCallb1b42562009-12-01 22:28:41 +00001446 if (!RD) return false;
1447 Record = cast<CXXRecordDecl>(RD);
1448
John McCallaa81e162009-12-01 22:10:20 +00001449 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1450 E = Record->bases_end(); I != E; ++I) {
1451 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1452 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1453 if (!BaseRT) return false;
1454
1455 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +00001456 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1457 return false;
1458 }
1459
1460 return true;
1461}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001462
John McCallaa81e162009-12-01 22:10:20 +00001463enum IMAKind {
1464 /// The reference is definitely not an instance member access.
1465 IMA_Static,
1466
1467 /// The reference may be an implicit instance member access.
1468 IMA_Mixed,
1469
1470 /// The reference may be to an instance member, but it is invalid if
1471 /// so, because the context is not an instance method.
1472 IMA_Mixed_StaticContext,
1473
1474 /// The reference may be to an instance member, but it is invalid if
1475 /// so, because the context is from an unrelated class.
1476 IMA_Mixed_Unrelated,
1477
1478 /// The reference is definitely an implicit instance member access.
1479 IMA_Instance,
1480
1481 /// The reference may be to an unresolved using declaration.
1482 IMA_Unresolved,
1483
1484 /// The reference may be to an unresolved using declaration and the
1485 /// context is not an instance method.
1486 IMA_Unresolved_StaticContext,
1487
John McCallaa81e162009-12-01 22:10:20 +00001488 /// All possible referrents are instance members and the current
1489 /// context is not an instance method.
1490 IMA_Error_StaticContext,
1491
1492 /// All possible referrents are instance members of an unrelated
1493 /// class.
1494 IMA_Error_Unrelated
1495};
1496
1497/// The given lookup names class member(s) and is not being used for
1498/// an address-of-member expression. Classify the type of access
1499/// according to whether it's possible that this reference names an
1500/// instance member. This is best-effort; it is okay to
1501/// conservatively answer "yes", in which case some errors will simply
1502/// not be caught until template-instantiation.
1503static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
Richard Smith7a614d82011-06-11 17:19:42 +00001504 Scope *CurScope,
John McCallaa81e162009-12-01 22:10:20 +00001505 const LookupResult &R) {
John McCall3b4294e2009-12-16 12:17:52 +00001506 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCallaa81e162009-12-01 22:10:20 +00001507
John McCallea1471e2010-05-20 01:18:31 +00001508 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
Richard Smith7a614d82011-06-11 17:19:42 +00001509
John McCallaa81e162009-12-01 22:10:20 +00001510 bool isStaticContext =
John McCallea1471e2010-05-20 01:18:31 +00001511 (!isa<CXXMethodDecl>(DC) ||
1512 cast<CXXMethodDecl>(DC)->isStatic());
John McCallaa81e162009-12-01 22:10:20 +00001513
Richard Smith7a614d82011-06-11 17:19:42 +00001514 // C++0x [expr.prim]p4:
1515 // Otherwise, if a member-declarator declares a non-static data member
1516 // of a class X, the expression this is a prvalue of type "pointer to X"
1517 // within the optional brace-or-equal-initializer.
1518 if (CurScope->getFlags() & Scope::ThisScope)
1519 isStaticContext = false;
1520
John McCallaa81e162009-12-01 22:10:20 +00001521 if (R.isUnresolvableResult())
1522 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1523
1524 // Collect all the declaring classes of instance members we find.
1525 bool hasNonInstance = false;
Sebastian Redlf9780002010-11-26 16:28:07 +00001526 bool hasField = false;
John McCallaa81e162009-12-01 22:10:20 +00001527 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1528 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall161755a2010-04-06 21:38:20 +00001529 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00001530
John McCall161755a2010-04-06 21:38:20 +00001531 if (D->isCXXInstanceMember()) {
Sebastian Redlf9780002010-11-26 16:28:07 +00001532 if (dyn_cast<FieldDecl>(D))
1533 hasField = true;
1534
John McCallaa81e162009-12-01 22:10:20 +00001535 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCallaa81e162009-12-01 22:10:20 +00001536 Classes.insert(R->getCanonicalDecl());
1537 }
1538 else
1539 hasNonInstance = true;
1540 }
1541
1542 // If we didn't find any instance members, it can't be an implicit
1543 // member reference.
1544 if (Classes.empty())
1545 return IMA_Static;
1546
1547 // If the current context is not an instance method, it can't be
1548 // an implicit member reference.
Sebastian Redlf9780002010-11-26 16:28:07 +00001549 if (isStaticContext) {
1550 if (hasNonInstance)
1551 return IMA_Mixed_StaticContext;
1552
1553 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1554 // C++0x [expr.prim.general]p10:
1555 // An id-expression that denotes a non-static data member or non-static
1556 // member function of a class can only be used:
1557 // (...)
John McCallf85e1932011-06-15 23:02:42 +00001558 // - if that id-expression denotes a non-static data member and it
1559 // appears in an unevaluated operand.
1560 const Sema::ExpressionEvaluationContextRecord& record
1561 = SemaRef.ExprEvalContexts.back();
1562 bool isUnevaluatedExpression = (record.Context == Sema::Unevaluated);
Sebastian Redlf9780002010-11-26 16:28:07 +00001563 if (isUnevaluatedExpression)
1564 return IMA_Mixed_StaticContext;
1565 }
1566
1567 return IMA_Error_StaticContext;
1568 }
John McCallaa81e162009-12-01 22:10:20 +00001569
Richard Smith7a614d82011-06-11 17:19:42 +00001570 CXXRecordDecl *contextClass;
1571 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
1572 contextClass = MD->getParent()->getCanonicalDecl();
1573 else
1574 contextClass = cast<CXXRecordDecl>(DC);
Argyrios Kyrtzidis0d8dc462011-04-14 00:46:47 +00001575
1576 // [class.mfct.non-static]p3:
1577 // ...is used in the body of a non-static member function of class X,
1578 // if name lookup (3.4.1) resolves the name in the id-expression to a
1579 // non-static non-type member of some class C [...]
1580 // ...if C is not X or a base class of X, the class member access expression
1581 // is ill-formed.
1582 if (R.getNamingClass() &&
1583 contextClass != R.getNamingClass()->getCanonicalDecl() &&
1584 contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
1585 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1586
John McCallaa81e162009-12-01 22:10:20 +00001587 // If we can prove that the current context is unrelated to all the
1588 // declaring classes, it can't be an implicit member reference (in
1589 // which case it's an error if any of those members are selected).
Argyrios Kyrtzidis0d8dc462011-04-14 00:46:47 +00001590 if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
John McCallaa81e162009-12-01 22:10:20 +00001591 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1592
1593 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1594}
1595
1596/// Diagnose a reference to a field with no object available.
1597static void DiagnoseInstanceReference(Sema &SemaRef,
1598 const CXXScopeSpec &SS,
John McCall5808ce42011-02-03 08:15:49 +00001599 NamedDecl *rep,
1600 const DeclarationNameInfo &nameInfo) {
1601 SourceLocation Loc = nameInfo.getLoc();
John McCallaa81e162009-12-01 22:10:20 +00001602 SourceRange Range(Loc);
1603 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1604
John McCall5808ce42011-02-03 08:15:49 +00001605 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCallaa81e162009-12-01 22:10:20 +00001606 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1607 if (MD->isStatic()) {
1608 // "invalid use of member 'x' in static member function"
1609 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCall5808ce42011-02-03 08:15:49 +00001610 << Range << nameInfo.getName();
John McCallaa81e162009-12-01 22:10:20 +00001611 return;
1612 }
1613 }
1614
1615 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCall5808ce42011-02-03 08:15:49 +00001616 << nameInfo.getName() << Range;
John McCallaa81e162009-12-01 22:10:20 +00001617 return;
1618 }
1619
1620 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +00001621}
1622
John McCall578b69b2009-12-16 08:11:27 +00001623/// Diagnose an empty lookup.
1624///
1625/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001626bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1627 CorrectTypoContext CTC) {
John McCall578b69b2009-12-16 08:11:27 +00001628 DeclarationName Name = R.getLookupName();
1629
John McCall578b69b2009-12-16 08:11:27 +00001630 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001631 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001632 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1633 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001634 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001635 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001636 diagnostic_suggest = diag::err_undeclared_use_suggest;
1637 }
John McCall578b69b2009-12-16 08:11:27 +00001638
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001639 // If the original lookup was an unqualified lookup, fake an
1640 // unqualified lookup. This is useful when (for example) the
1641 // original lookup would not have found something because it was a
1642 // dependent name.
Nick Lewycky03d98c52010-07-06 19:51:49 +00001643 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001644 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +00001645 if (isa<CXXRecordDecl>(DC)) {
1646 LookupQualifiedName(R, DC);
1647
1648 if (!R.empty()) {
1649 // Don't give errors about ambiguities in this lookup.
1650 R.suppressDiagnostics();
1651
1652 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1653 bool isInstance = CurMethod &&
1654 CurMethod->isInstance() &&
1655 DC == CurMethod->getParent();
1656
1657 // Give a code modification hint to insert 'this->'.
1658 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1659 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +00001660 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001661 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1662 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001663 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001664 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001665 if (DepMethod) {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001666 Diag(R.getNameLoc(), diagnostic) << Name
1667 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1668 QualType DepThisType = DepMethod->getThisType(Context);
1669 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1670 R.getNameLoc(), DepThisType, false);
1671 TemplateArgumentListInfo TList;
1672 if (ULE->hasExplicitTemplateArgs())
1673 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001674
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001675 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00001676 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001677 CXXDependentScopeMemberExpr *DepExpr =
1678 CXXDependentScopeMemberExpr::Create(
1679 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001680 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001681 R.getLookupNameInfo(), &TList);
1682 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001683 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001684 // FIXME: we should be able to handle this case too. It is correct
1685 // to add this-> here. This is a workaround for PR7947.
1686 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001687 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001688 } else {
John McCall578b69b2009-12-16 08:11:27 +00001689 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001690 }
John McCall578b69b2009-12-16 08:11:27 +00001691
1692 // Do we really want to note all of these?
1693 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1694 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1695
1696 // Tell the callee to try to recover.
1697 return false;
1698 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001699
1700 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001701 }
1702 }
1703
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001704 // We didn't find anything, so try to correct for a typo.
Douglas Gregoraaf87162010-04-14 20:04:41 +00001705 DeclarationName Corrected;
Daniel Dunbardc32cdf2010-06-02 15:46:52 +00001706 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001707 if (!R.empty()) {
1708 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1709 if (SS.isEmpty())
1710 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1711 << FixItHint::CreateReplacement(R.getNameLoc(),
1712 R.getLookupName().getAsString());
1713 else
1714 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1715 << Name << computeDeclContext(SS, false) << R.getLookupName()
1716 << SS.getRange()
1717 << FixItHint::CreateReplacement(R.getNameLoc(),
1718 R.getLookupName().getAsString());
1719 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1720 Diag(ND->getLocation(), diag::note_previous_decl)
1721 << ND->getDeclName();
1722
1723 // Tell the callee to try to recover.
1724 return false;
1725 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001726
Douglas Gregoraaf87162010-04-14 20:04:41 +00001727 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1728 // FIXME: If we ended up with a typo for a type name or
1729 // Objective-C class name, we're in trouble because the parser
1730 // is in the wrong place to recover. Suggest the typo
1731 // correction, but don't make it a fix-it since we're not going
1732 // to recover well anyway.
1733 if (SS.isEmpty())
1734 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1735 else
1736 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1737 << Name << computeDeclContext(SS, false) << R.getLookupName()
1738 << SS.getRange();
1739
1740 // Don't try to recover; it won't work.
1741 return true;
1742 }
1743 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001744 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001745 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001746 if (SS.isEmpty())
Douglas Gregoraaf87162010-04-14 20:04:41 +00001747 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001748 else
Douglas Gregord203a162010-01-01 00:15:04 +00001749 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001750 << Name << computeDeclContext(SS, false) << Corrected
1751 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001752 return true;
1753 }
Douglas Gregord203a162010-01-01 00:15:04 +00001754 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001755 }
1756
1757 // Emit a special diagnostic for failed member lookups.
1758 // FIXME: computing the declaration context might fail here (?)
1759 if (!SS.isEmpty()) {
1760 Diag(R.getNameLoc(), diag::err_no_member)
1761 << Name << computeDeclContext(SS, false)
1762 << SS.getRange();
1763 return true;
1764 }
1765
John McCall578b69b2009-12-16 08:11:27 +00001766 // Give up, we can't recover.
1767 Diag(R.getNameLoc(), diagnostic) << Name;
1768 return true;
1769}
1770
Douglas Gregorca45da02010-11-02 20:36:02 +00001771ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1772 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001773 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1774 if (!IDecl)
1775 return 0;
1776 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1777 if (!ClassImpDecl)
1778 return 0;
Douglas Gregorca45da02010-11-02 20:36:02 +00001779 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001780 if (!property)
1781 return 0;
1782 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregorca45da02010-11-02 20:36:02 +00001783 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1784 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001785 return 0;
1786 return property;
1787}
1788
Douglas Gregorca45da02010-11-02 20:36:02 +00001789bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1790 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1791 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1792 if (!IDecl)
1793 return false;
1794 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1795 if (!ClassImpDecl)
1796 return false;
1797 if (ObjCPropertyImplDecl *PIDecl
1798 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1799 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1800 PIDecl->getPropertyIvarDecl())
1801 return false;
1802
1803 return true;
1804}
1805
Douglas Gregor312eadb2011-04-24 05:37:28 +00001806ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1807 IdentifierInfo *II,
1808 SourceLocation NameLoc) {
1809 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001810 bool LookForIvars;
1811 if (Lookup.empty())
1812 LookForIvars = true;
1813 else if (CurMeth->isClassMethod())
1814 LookForIvars = false;
1815 else
1816 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahaniand0fbadd2011-01-26 00:57:01 +00001817 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1818 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001819 if (!LookForIvars)
1820 return 0;
1821
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001822 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1823 if (!IDecl)
1824 return 0;
1825 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001826 if (!ClassImpDecl)
1827 return 0;
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001828 bool DynamicImplSeen = false;
Douglas Gregor312eadb2011-04-24 05:37:28 +00001829 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001830 if (!property)
1831 return 0;
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001832 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001833 DynamicImplSeen =
1834 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001835 // property implementation has a designated ivar. No need to assume a new
1836 // one.
1837 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1838 return 0;
1839 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001840 if (!DynamicImplSeen) {
Douglas Gregor312eadb2011-04-24 05:37:28 +00001841 QualType PropType = Context.getCanonicalType(property->getType());
1842 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001843 NameLoc, NameLoc,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001844 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian75049662010-12-15 23:29:04 +00001845 ObjCIvarDecl::Private,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001846 (Expr *)0, true);
1847 ClassImpDecl->addDecl(Ivar);
1848 IDecl->makeDeclVisibleInContext(Ivar, false);
1849 property->setPropertyIvarDecl(Ivar);
1850 return Ivar;
1851 }
1852 return 0;
1853}
1854
John McCall60d7b3a2010-08-24 06:29:42 +00001855ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001856 CXXScopeSpec &SS,
1857 UnqualifiedId &Id,
1858 bool HasTrailingLParen,
1859 bool isAddressOfOperand) {
John McCallf7a1a742009-11-24 19:00:30 +00001860 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1861 "cannot be direct & operand and have a trailing lparen");
1862
1863 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001864 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001865
John McCall129e2df2009-11-30 22:42:35 +00001866 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001867
1868 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001869 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001870 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnara25777432010-08-11 22:01:17 +00001871 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001872
Abramo Bagnara25777432010-08-11 22:01:17 +00001873 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001874 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001875 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001876
John McCallf7a1a742009-11-24 19:00:30 +00001877 // C++ [temp.dep.expr]p3:
1878 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001879 // -- an identifier that was declared with a dependent type,
1880 // (note: handled after lookup)
1881 // -- a template-id that is dependent,
1882 // (note: handled in BuildTemplateIdExpr)
1883 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001884 // -- a nested-name-specifier that contains a class-name that
1885 // names a dependent type.
1886 // Determine whether this is a member of an unknown specialization;
1887 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001888 bool DependentID = false;
1889 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1890 Name.getCXXNameType()->isDependentType()) {
1891 DependentID = true;
1892 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001893 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001894 if (RequireCompleteDeclContext(SS, DC))
1895 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001896 } else {
1897 DependentID = true;
1898 }
1899 }
1900
Chris Lattner337e5502011-02-18 01:27:55 +00001901 if (DependentID)
Abramo Bagnara25777432010-08-11 22:01:17 +00001902 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001903 TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001904
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001905 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001906 // Perform the required lookup.
Abramo Bagnara25777432010-08-11 22:01:17 +00001907 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001908 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001909 // Lookup the template name again to correctly establish the context in
1910 // which it was found. This is really unfortunate as we already did the
1911 // lookup to determine that it was a template name in the first place. If
1912 // this becomes a performance hit, we can work harder to preserve those
1913 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001914 bool MemberOfUnknownSpecialization;
1915 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1916 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001917
1918 if (MemberOfUnknownSpecialization ||
1919 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1920 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1921 TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001922 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001923 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001924 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001925
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001926 // If the result might be in a dependent base class, this is a dependent
1927 // id-expression.
1928 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1929 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1930 TemplateArgs);
1931
John McCallf7a1a742009-11-24 19:00:30 +00001932 // If this reference is in an Objective-C method, then we need to do
1933 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001934 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001935 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001936 if (E.isInvalid())
1937 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001938
Chris Lattner337e5502011-02-18 01:27:55 +00001939 if (Expr *Ex = E.takeAs<Expr>())
1940 return Owned(Ex);
1941
1942 // Synthesize ivars lazily.
Fariborz Jahaniane776f882011-01-03 18:08:02 +00001943 if (getLangOptions().ObjCDefaultSynthProperties &&
1944 getLangOptions().ObjCNonFragileABI2) {
Douglas Gregor312eadb2011-04-24 05:37:28 +00001945 if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
Fariborz Jahaniande267602010-11-17 19:41:23 +00001946 if (const ObjCPropertyDecl *Property =
1947 canSynthesizeProvisionalIvar(II)) {
1948 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1949 Diag(Property->getLocation(), diag::note_property_declare);
1950 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001951 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1952 isAddressOfOperand);
Fariborz Jahaniande267602010-11-17 19:41:23 +00001953 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001954 }
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001955 // for further use, this must be set to false if in class method.
1956 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001957 }
Chris Lattner8a934232008-03-31 00:36:02 +00001958 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001959
John McCallf7a1a742009-11-24 19:00:30 +00001960 if (R.isAmbiguous())
1961 return ExprError();
1962
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001963 // Determine whether this name might be a candidate for
1964 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001965 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001966
John McCallf7a1a742009-11-24 19:00:30 +00001967 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001968 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001969 // in C90, extension in C99, forbidden in C++).
1970 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1971 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1972 if (D) R.addDecl(D);
1973 }
1974
1975 // If this name wasn't predeclared and if this is not a function
1976 // call, diagnose the problem.
1977 if (R.empty()) {
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001978 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001979 return ExprError();
1980
1981 assert(!R.empty() &&
1982 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001983
1984 // If we found an Objective-C instance variable, let
1985 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001986 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001987 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1988 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001989 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001990 assert(E.isInvalid() || E.get());
1991 return move(E);
1992 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001993 }
1994 }
Mike Stump1eb44332009-09-09 15:08:12 +00001995
John McCallf7a1a742009-11-24 19:00:30 +00001996 // This is guaranteed from this point on.
1997 assert(!R.empty() || ADL);
1998
John McCallaa81e162009-12-01 22:10:20 +00001999 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00002000 // C++ [class.mfct.non-static]p3:
2001 // When an id-expression that is not part of a class member access
2002 // syntax and not used to form a pointer to member is used in the
2003 // body of a non-static member function of class X, if name lookup
2004 // resolves the name in the id-expression to a non-static non-type
2005 // member of some class C, the id-expression is transformed into a
2006 // class member access expression using (*this) as the
2007 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00002008 //
2009 // But we don't actually need to do this for '&' operands if R
2010 // resolved to a function or overloaded function set, because the
2011 // expression is ill-formed if it actually works out to be a
2012 // non-static member function:
2013 //
2014 // C++ [expr.ref]p4:
2015 // Otherwise, if E1.E2 refers to a non-static member function. . .
2016 // [t]he expression can be used only as the left-hand operand of a
2017 // member function call.
2018 //
2019 // There are other safeguards against such uses, but it's important
2020 // to get this right here so that we don't end up making a
2021 // spuriously dependent expression if we're inside a dependent
2022 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00002023 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00002024 bool MightBeImplicitMember;
2025 if (!isAddressOfOperand)
2026 MightBeImplicitMember = true;
2027 else if (!SS.isEmpty())
2028 MightBeImplicitMember = false;
2029 else if (R.isOverloadedResult())
2030 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00002031 else if (R.isUnresolvableResult())
2032 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00002033 else
Francois Pichet87c2e122010-11-21 06:08:52 +00002034 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2035 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00002036
2037 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00002038 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00002039 }
2040
John McCallf7a1a742009-11-24 19:00:30 +00002041 if (TemplateArgs)
2042 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00002043
John McCallf7a1a742009-11-24 19:00:30 +00002044 return BuildDeclarationNameExpr(SS, R, ADL);
2045}
2046
John McCall3b4294e2009-12-16 12:17:52 +00002047/// Builds an expression which might be an implicit member expression.
John McCall60d7b3a2010-08-24 06:29:42 +00002048ExprResult
John McCall3b4294e2009-12-16 12:17:52 +00002049Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
2050 LookupResult &R,
2051 const TemplateArgumentListInfo *TemplateArgs) {
Richard Smith7a614d82011-06-11 17:19:42 +00002052 switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
John McCall3b4294e2009-12-16 12:17:52 +00002053 case IMA_Instance:
2054 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
2055
John McCall3b4294e2009-12-16 12:17:52 +00002056 case IMA_Mixed:
2057 case IMA_Mixed_Unrelated:
2058 case IMA_Unresolved:
2059 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
2060
2061 case IMA_Static:
2062 case IMA_Mixed_StaticContext:
2063 case IMA_Unresolved_StaticContext:
2064 if (TemplateArgs)
2065 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
2066 return BuildDeclarationNameExpr(SS, R, false);
2067
2068 case IMA_Error_StaticContext:
2069 case IMA_Error_Unrelated:
John McCall5808ce42011-02-03 08:15:49 +00002070 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
2071 R.getLookupNameInfo());
John McCall3b4294e2009-12-16 12:17:52 +00002072 return ExprError();
2073 }
2074
2075 llvm_unreachable("unexpected instance member access kind");
2076 return ExprError();
2077}
2078
John McCall129e2df2009-11-30 22:42:35 +00002079/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2080/// declaration name, generally during template instantiation.
2081/// There's a large number of things which don't need to be done along
2082/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00002083ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002084Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002085 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00002086 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00002087 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00002088 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00002089
John McCall77bb1aa2010-05-01 00:40:08 +00002090 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00002091 return ExprError();
2092
Abramo Bagnara25777432010-08-11 22:01:17 +00002093 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00002094 LookupQualifiedName(R, DC);
2095
2096 if (R.isAmbiguous())
2097 return ExprError();
2098
2099 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002100 Diag(NameInfo.getLoc(), diag::err_no_member)
2101 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00002102 return ExprError();
2103 }
2104
2105 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
2106}
2107
2108/// LookupInObjCMethod - The parser has read a name in, and Sema has
2109/// detected that we're currently inside an ObjC method. Perform some
2110/// additional lookup.
2111///
2112/// Ideally, most of this would be done by lookup, but there's
2113/// actually quite a lot of extra work involved.
2114///
2115/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00002116ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002117Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00002118 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00002119 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00002120 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002121
John McCallf7a1a742009-11-24 19:00:30 +00002122 // There are two cases to handle here. 1) scoped lookup could have failed,
2123 // in which case we should look for an ivar. 2) scoped lookup could have
2124 // found a decl, but that decl is outside the current instance method (i.e.
2125 // a global variable). In these two cases, we do a lookup for an ivar with
2126 // this name, if the lookup sucedes, we replace it our current decl.
2127
2128 // If we're in a class method, we don't normally want to look for
2129 // ivars. But if we don't find anything else, and there's an
2130 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00002131 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00002132
2133 bool LookForIvars;
2134 if (Lookup.empty())
2135 LookForIvars = true;
2136 else if (IsClassMethod)
2137 LookForIvars = false;
2138 else
2139 LookForIvars = (Lookup.isSingleResult() &&
2140 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00002141 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00002142 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00002143 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00002144 ObjCInterfaceDecl *ClassDeclared;
2145 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2146 // Diagnose using an ivar in a class method.
2147 if (IsClassMethod)
2148 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2149 << IV->getDeclName());
2150
2151 // If we're referencing an invalid decl, just return this as a silent
2152 // error node. The error diagnostic was already emitted on the decl.
2153 if (IV->isInvalidDecl())
2154 return ExprError();
2155
2156 // Check if referencing a field with __attribute__((deprecated)).
2157 if (DiagnoseUseOfDecl(IV, Loc))
2158 return ExprError();
2159
2160 // Diagnose the use of an ivar outside of the declaring class.
2161 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2162 ClassDeclared != IFace)
2163 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2164
2165 // FIXME: This should use a new expr for a direct reference, don't
2166 // turn this into Self->ivar, just return a BareIVarExpr or something.
2167 IdentifierInfo &II = Context.Idents.get("self");
2168 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002169 SelfName.setIdentifier(&II, SourceLocation());
John McCallf7a1a742009-11-24 19:00:30 +00002170 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00002171 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00002172 SelfName, false, false);
2173 if (SelfExpr.isInvalid())
2174 return ExprError();
2175
John Wiegley429bb272011-04-08 18:41:53 +00002176 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2177 if (SelfExpr.isInvalid())
2178 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00002179
John McCallf7a1a742009-11-24 19:00:30 +00002180 MarkDeclarationReferenced(Loc, IV);
Fariborz Jahanianb8f17ab2011-04-12 23:39:33 +00002181 Expr *base = SelfExpr.take();
2182 base = base->IgnoreParenImpCasts();
2183 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(base)) {
2184 const NamedDecl *ND = DE->getDecl();
2185 if (!isa<ImplicitParamDecl>(ND)) {
Fariborz Jahanianeefa76e2011-04-15 17:04:42 +00002186 // relax the rule such that it is allowed to have a shadow 'self'
2187 // where stand-alone ivar can be found in this 'self' object.
2188 // This is to match gcc's behavior.
2189 ObjCInterfaceDecl *selfIFace = 0;
2190 if (const ObjCObjectPointerType *OPT =
2191 base->getType()->getAsObjCInterfacePointerType())
2192 selfIFace = OPT->getInterfaceDecl();
2193 if (!selfIFace ||
2194 !selfIFace->lookupInstanceVariable(IV->getIdentifier())) {
Fariborz Jahanianb8f17ab2011-04-12 23:39:33 +00002195 Diag(Loc, diag::error_implicit_ivar_access)
2196 << IV->getDeclName();
2197 Diag(ND->getLocation(), diag::note_declared_at);
2198 return ExprError();
2199 }
Fariborz Jahanianeefa76e2011-04-15 17:04:42 +00002200 }
Fariborz Jahanianb8f17ab2011-04-12 23:39:33 +00002201 }
John McCallf7a1a742009-11-24 19:00:30 +00002202 return Owned(new (Context)
2203 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley429bb272011-04-08 18:41:53 +00002204 SelfExpr.take(), true, true));
John McCallf7a1a742009-11-24 19:00:30 +00002205 }
Chris Lattneraec43db2010-04-12 05:10:17 +00002206 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00002207 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00002208 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00002209 ObjCInterfaceDecl *ClassDeclared;
2210 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2211 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2212 IFace == ClassDeclared)
2213 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2214 }
2215 }
2216
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002217 if (Lookup.empty() && II && AllowBuiltinCreation) {
2218 // FIXME. Consolidate this with similar code in LookupName.
2219 if (unsigned BuiltinID = II->getBuiltinID()) {
2220 if (!(getLangOptions().CPlusPlus &&
2221 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2222 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2223 S, Lookup.isForRedeclaration(),
2224 Lookup.getNameLoc());
2225 if (D) Lookup.addDecl(D);
2226 }
2227 }
2228 }
John McCallf7a1a742009-11-24 19:00:30 +00002229 // Sentinel value saying that we didn't do anything special.
2230 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00002231}
John McCallba135432009-11-21 08:51:07 +00002232
John McCall6bb80172010-03-30 21:47:33 +00002233/// \brief Cast a base object to a member's actual type.
2234///
2235/// Logically this happens in three phases:
2236///
2237/// * First we cast from the base type to the naming class.
2238/// The naming class is the class into which we were looking
2239/// when we found the member; it's the qualifier type if a
2240/// qualifier was provided, and otherwise it's the base type.
2241///
2242/// * Next we cast from the naming class to the declaring class.
2243/// If the member we found was brought into a class's scope by
2244/// a using declaration, this is that class; otherwise it's
2245/// the class declaring the member.
2246///
2247/// * Finally we cast from the declaring class to the "true"
2248/// declaring class of the member. This conversion does not
2249/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00002250ExprResult
2251Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002252 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002253 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002254 NamedDecl *Member) {
2255 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2256 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00002257 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002258
Douglas Gregor5fccd362010-03-03 23:55:11 +00002259 QualType DestRecordType;
2260 QualType DestType;
2261 QualType FromRecordType;
2262 QualType FromType = From->getType();
2263 bool PointerConversions = false;
2264 if (isa<FieldDecl>(Member)) {
2265 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002266
Douglas Gregor5fccd362010-03-03 23:55:11 +00002267 if (FromType->getAs<PointerType>()) {
2268 DestType = Context.getPointerType(DestRecordType);
2269 FromRecordType = FromType->getPointeeType();
2270 PointerConversions = true;
2271 } else {
2272 DestType = DestRecordType;
2273 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002274 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002275 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2276 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00002277 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002278
Douglas Gregor5fccd362010-03-03 23:55:11 +00002279 DestType = Method->getThisType(Context);
2280 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002281
Douglas Gregor5fccd362010-03-03 23:55:11 +00002282 if (FromType->getAs<PointerType>()) {
2283 FromRecordType = FromType->getPointeeType();
2284 PointerConversions = true;
2285 } else {
2286 FromRecordType = FromType;
2287 DestType = DestRecordType;
2288 }
2289 } else {
2290 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002291 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002292 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002293
Douglas Gregor5fccd362010-03-03 23:55:11 +00002294 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002295 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002296
Douglas Gregor5fccd362010-03-03 23:55:11 +00002297 // If the unqualified types are the same, no conversion is necessary.
2298 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002299 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002300
John McCall6bb80172010-03-30 21:47:33 +00002301 SourceRange FromRange = From->getSourceRange();
2302 SourceLocation FromLoc = FromRange.getBegin();
2303
John McCall5baba9d2010-08-25 10:28:54 +00002304 ExprValueKind VK = CastCategory(From);
Sebastian Redl906082e2010-07-20 04:20:21 +00002305
Douglas Gregor5fccd362010-03-03 23:55:11 +00002306 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002307 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002308 // class name.
2309 //
2310 // If the member was a qualified name and the qualified referred to a
2311 // specific base subobject type, we'll cast to that intermediate type
2312 // first and then to the object in which the member is declared. That allows
2313 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2314 //
2315 // class Base { public: int x; };
2316 // class Derived1 : public Base { };
2317 // class Derived2 : public Base { };
2318 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2319 //
2320 // void VeryDerived::f() {
2321 // x = 17; // error: ambiguous base subobjects
2322 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2323 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002324 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002325 QualType QType = QualType(Qualifier->getAsType(), 0);
2326 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2327 assert(QType->isRecordType() && "lookup done with non-record type");
2328
2329 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2330
2331 // In C++98, the qualifier type doesn't actually have to be a base
2332 // type of the object type, in which case we just ignore it.
2333 // Otherwise build the appropriate casts.
2334 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002335 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002336 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002337 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002338 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002339
Douglas Gregor5fccd362010-03-03 23:55:11 +00002340 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002341 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002342 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2343 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002344
2345 FromType = QType;
2346 FromRecordType = QRecordType;
2347
2348 // If the qualifier type was the same as the destination type,
2349 // we're done.
2350 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002351 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002352 }
2353 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002354
John McCall6bb80172010-03-30 21:47:33 +00002355 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002356
John McCall6bb80172010-03-30 21:47:33 +00002357 // If we actually found the member through a using declaration, cast
2358 // down to the using declaration's type.
2359 //
2360 // Pointer equality is fine here because only one declaration of a
2361 // class ever has member declarations.
2362 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2363 assert(isa<UsingShadowDecl>(FoundDecl));
2364 QualType URecordType = Context.getTypeDeclType(
2365 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2366
2367 // We only need to do this if the naming-class to declaring-class
2368 // conversion is non-trivial.
2369 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2370 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002371 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002372 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002373 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002374 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002375
John McCall6bb80172010-03-30 21:47:33 +00002376 QualType UType = URecordType;
2377 if (PointerConversions)
2378 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002379 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2380 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002381 FromType = UType;
2382 FromRecordType = URecordType;
2383 }
2384
2385 // We don't do access control for the conversion from the
2386 // declaring class to the true declaring class.
2387 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002388 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002389
John McCallf871d0c2010-08-07 06:22:56 +00002390 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002391 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2392 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002393 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002394 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002395
John Wiegley429bb272011-04-08 18:41:53 +00002396 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2397 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002398}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002399
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002400/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00002401static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00002402 const CXXScopeSpec &SS, ValueDecl *Member,
John McCall161755a2010-04-06 21:38:20 +00002403 DeclAccessPair FoundDecl,
Abramo Bagnara25777432010-08-11 22:01:17 +00002404 const DeclarationNameInfo &MemberNameInfo,
2405 QualType Ty,
John McCallf89e55a2010-11-18 06:31:45 +00002406 ExprValueKind VK, ExprObjectKind OK,
John McCallf7a1a742009-11-24 19:00:30 +00002407 const TemplateArgumentListInfo *TemplateArgs = 0) {
Douglas Gregor40d96a62011-02-28 21:54:11 +00002408 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
Abramo Bagnara25777432010-08-11 22:01:17 +00002409 Member, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002410 TemplateArgs, Ty, VK, OK);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002411}
2412
John McCalldfa1edb2010-11-23 20:48:44 +00002413static ExprResult
2414BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2415 const CXXScopeSpec &SS, FieldDecl *Field,
2416 DeclAccessPair FoundDecl,
2417 const DeclarationNameInfo &MemberNameInfo) {
2418 // x.a is an l-value if 'a' has a reference type. Otherwise:
2419 // x.a is an l-value/x-value/pr-value if the base is (and note
2420 // that *x is always an l-value), except that if the base isn't
2421 // an ordinary object then we must have an rvalue.
2422 ExprValueKind VK = VK_LValue;
2423 ExprObjectKind OK = OK_Ordinary;
2424 if (!IsArrow) {
2425 if (BaseExpr->getObjectKind() == OK_Ordinary)
2426 VK = BaseExpr->getValueKind();
2427 else
2428 VK = VK_RValue;
2429 }
2430 if (VK != VK_RValue && Field->isBitField())
2431 OK = OK_BitField;
2432
2433 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2434 QualType MemberType = Field->getType();
2435 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2436 MemberType = Ref->getPointeeType();
2437 VK = VK_LValue;
2438 } else {
2439 QualType BaseType = BaseExpr->getType();
2440 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2441
2442 Qualifiers BaseQuals = BaseType.getQualifiers();
2443
2444 // GC attributes are never picked up by members.
2445 BaseQuals.removeObjCGCAttr();
2446
2447 // CVR attributes from the base are picked up by members,
2448 // except that 'mutable' members don't pick up 'const'.
2449 if (Field->isMutable()) BaseQuals.removeConst();
2450
2451 Qualifiers MemberQuals
2452 = S.Context.getCanonicalType(MemberType).getQualifiers();
2453
2454 // TR 18037 does not allow fields to be declared with address spaces.
2455 assert(!MemberQuals.hasAddressSpace());
2456
2457 Qualifiers Combined = BaseQuals + MemberQuals;
2458 if (Combined != MemberQuals)
2459 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2460 }
2461
2462 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
John Wiegley429bb272011-04-08 18:41:53 +00002463 ExprResult Base =
2464 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2465 FoundDecl, Field);
2466 if (Base.isInvalid())
John McCalldfa1edb2010-11-23 20:48:44 +00002467 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00002468 return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
John McCalldfa1edb2010-11-23 20:48:44 +00002469 Field, FoundDecl, MemberNameInfo,
2470 MemberType, VK, OK));
2471}
2472
John McCallaa81e162009-12-01 22:10:20 +00002473/// Builds an implicit member access expression. The current context
2474/// is known to be an instance method, and the given unqualified lookup
2475/// set is known to contain only instance members, at least one of which
2476/// is from an appropriate type.
John McCall60d7b3a2010-08-24 06:29:42 +00002477ExprResult
John McCallaa81e162009-12-01 22:10:20 +00002478Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2479 LookupResult &R,
2480 const TemplateArgumentListInfo *TemplateArgs,
2481 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00002482 assert(!R.empty() && !R.isAmbiguous());
2483
John McCall5808ce42011-02-03 08:15:49 +00002484 SourceLocation loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00002485
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002486 // We may have found a field within an anonymous union or struct
2487 // (C++ [class.union]).
John McCallf7a1a742009-11-24 19:00:30 +00002488 // FIXME: template-ids inside anonymous structs?
Francois Pichet87c2e122010-11-21 06:08:52 +00002489 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCall5808ce42011-02-03 08:15:49 +00002490 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet87c2e122010-11-21 06:08:52 +00002491
John McCall5808ce42011-02-03 08:15:49 +00002492 // If this is known to be an instance access, go ahead and build an
2493 // implicit 'this' expression now.
John McCallaa81e162009-12-01 22:10:20 +00002494 // 'this' expression now.
Richard Smith7a614d82011-06-11 17:19:42 +00002495 QualType ThisTy = getAndCaptureCurrentThisType();
2496 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
John McCall5808ce42011-02-03 08:15:49 +00002497
John McCall5808ce42011-02-03 08:15:49 +00002498 Expr *baseExpr = 0; // null signifies implicit access
John McCallaa81e162009-12-01 22:10:20 +00002499 if (IsKnownInstance) {
Douglas Gregor828a1972010-01-07 23:12:05 +00002500 SourceLocation Loc = R.getNameLoc();
2501 if (SS.getRange().isValid())
2502 Loc = SS.getRange().getBegin();
Richard Smith7a614d82011-06-11 17:19:42 +00002503 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
Douglas Gregor88a35142008-12-22 05:46:06 +00002504 }
2505
Richard Smith7a614d82011-06-11 17:19:42 +00002506 return BuildMemberReferenceExpr(baseExpr, ThisTy,
John McCallaa81e162009-12-01 22:10:20 +00002507 /*OpLoc*/ SourceLocation(),
2508 /*IsArrow*/ true,
John McCallc2233c52010-01-15 08:34:02 +00002509 SS,
2510 /*FirstQualifierInScope*/ 0,
2511 R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00002512}
2513
John McCallf7a1a742009-11-24 19:00:30 +00002514bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002515 const LookupResult &R,
2516 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002517 // Only when used directly as the postfix-expression of a call.
2518 if (!HasTrailingLParen)
2519 return false;
2520
2521 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002522 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002523 return false;
2524
2525 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002526 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002527 return false;
2528
2529 // Turn off ADL when we find certain kinds of declarations during
2530 // normal lookup:
2531 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2532 NamedDecl *D = *I;
2533
2534 // C++0x [basic.lookup.argdep]p3:
2535 // -- a declaration of a class member
2536 // Since using decls preserve this property, we check this on the
2537 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002538 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002539 return false;
2540
2541 // C++0x [basic.lookup.argdep]p3:
2542 // -- a block-scope function declaration that is not a
2543 // using-declaration
2544 // NOTE: we also trigger this for function templates (in fact, we
2545 // don't check the decl type at all, since all other decl types
2546 // turn off ADL anyway).
2547 if (isa<UsingShadowDecl>(D))
2548 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2549 else if (D->getDeclContext()->isFunctionOrMethod())
2550 return false;
2551
2552 // C++0x [basic.lookup.argdep]p3:
2553 // -- a declaration that is neither a function or a function
2554 // template
2555 // And also for builtin functions.
2556 if (isa<FunctionDecl>(D)) {
2557 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2558
2559 // But also builtin functions.
2560 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2561 return false;
2562 } else if (!isa<FunctionTemplateDecl>(D))
2563 return false;
2564 }
2565
2566 return true;
2567}
2568
2569
John McCallba135432009-11-21 08:51:07 +00002570/// Diagnoses obvious problems with the use of the given declaration
2571/// as an expression. This is only actually called for lookups that
2572/// were not overloaded, and it doesn't promise that the declaration
2573/// will in fact be used.
2574static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002575 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002576 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2577 return true;
2578 }
2579
2580 if (isa<ObjCInterfaceDecl>(D)) {
2581 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2582 return true;
2583 }
2584
2585 if (isa<NamespaceDecl>(D)) {
2586 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2587 return true;
2588 }
2589
2590 return false;
2591}
2592
John McCall60d7b3a2010-08-24 06:29:42 +00002593ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002594Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002595 LookupResult &R,
2596 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002597 // If this is a single, fully-resolved result and we don't need ADL,
2598 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002599 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002600 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2601 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002602
2603 // We only need to check the declaration if there's exactly one
2604 // result, because in the overloaded case the results can only be
2605 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002606 if (R.isSingleResult() &&
2607 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002608 return ExprError();
2609
John McCallc373d482010-01-27 01:50:18 +00002610 // Otherwise, just build an unresolved lookup expression. Suppress
2611 // any lookup-related diagnostics; we'll hash these out later, when
2612 // we've picked a target.
2613 R.suppressDiagnostics();
2614
John McCallba135432009-11-21 08:51:07 +00002615 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002616 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002617 SS.getWithLocInContext(Context),
2618 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002619 NeedsADL, R.isOverloadedResult(),
2620 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002621
2622 return Owned(ULE);
2623}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002624
John McCallba135432009-11-21 08:51:07 +00002625/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002626ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002627Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002628 const DeclarationNameInfo &NameInfo,
2629 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002630 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002631 assert(!isa<FunctionTemplateDecl>(D) &&
2632 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002633
Abramo Bagnara25777432010-08-11 22:01:17 +00002634 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002635 if (CheckDeclInExpr(*this, Loc, D))
2636 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002637
Douglas Gregor9af2f522009-12-01 16:58:18 +00002638 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2639 // Specifically diagnose references to class templates that are missing
2640 // a template argument list.
2641 Diag(Loc, diag::err_template_decl_ref)
2642 << Template << SS.getRange();
2643 Diag(Template->getLocation(), diag::note_template_decl_here);
2644 return ExprError();
2645 }
2646
2647 // Make sure that we're referring to a value.
2648 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2649 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002650 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002651 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002652 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002653 return ExprError();
2654 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002655
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002656 // Check whether this declaration can be used. Note that we suppress
2657 // this check when we're going to perform argument-dependent lookup
2658 // on this function name, because this might not be the function
2659 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002660 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002661 return ExprError();
2662
Steve Naroffdd972f22008-09-05 22:11:13 +00002663 // Only create DeclRefExpr's for valid Decl's.
2664 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002665 return ExprError();
2666
John McCall5808ce42011-02-03 08:15:49 +00002667 // Handle members of anonymous structs and unions. If we got here,
2668 // and the reference is to a class member indirect field, then this
2669 // must be the subject of a pointer-to-member expression.
2670 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2671 if (!indirectField->isCXXClassMember())
2672 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2673 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002674
Chris Lattner639e2d32008-10-20 05:16:36 +00002675 // If the identifier reference is inside a block, and it refers to a value
2676 // that is outside the block, create a BlockDeclRefExpr instead of a
2677 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2678 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002679 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002680 // We do not do this for things like enum constants, global variables, etc,
2681 // as they do not get snapshotted.
2682 //
John McCall6b5a61b2011-02-07 10:33:21 +00002683 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCall469a1eb2011-02-02 13:00:07 +00002684 case CR_Error:
2685 return ExprError();
Mike Stump0d6fd572010-01-05 02:56:35 +00002686
John McCall469a1eb2011-02-02 13:00:07 +00002687 case CR_Capture:
John McCall6b5a61b2011-02-07 10:33:21 +00002688 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2689 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2690
2691 case CR_CaptureByRef:
2692 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2693 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCall76a40212011-02-09 01:13:10 +00002694
2695 case CR_NoCapture: {
2696 // If this reference is not in a block or if the referenced
2697 // variable is within the block, create a normal DeclRefExpr.
2698
2699 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002700 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002701
2702 switch (D->getKind()) {
2703 // Ignore all the non-ValueDecl kinds.
2704#define ABSTRACT_DECL(kind)
2705#define VALUE(type, base)
2706#define DECL(type, base) \
2707 case Decl::type:
2708#include "clang/AST/DeclNodes.inc"
2709 llvm_unreachable("invalid value decl kind");
2710 return ExprError();
2711
2712 // These shouldn't make it here.
2713 case Decl::ObjCAtDefsField:
2714 case Decl::ObjCIvar:
2715 llvm_unreachable("forming non-member reference to ivar?");
2716 return ExprError();
2717
2718 // Enum constants are always r-values and never references.
2719 // Unresolved using declarations are dependent.
2720 case Decl::EnumConstant:
2721 case Decl::UnresolvedUsingValue:
2722 valueKind = VK_RValue;
2723 break;
2724
2725 // Fields and indirect fields that got here must be for
2726 // pointer-to-member expressions; we just call them l-values for
2727 // internal consistency, because this subexpression doesn't really
2728 // exist in the high-level semantics.
2729 case Decl::Field:
2730 case Decl::IndirectField:
2731 assert(getLangOptions().CPlusPlus &&
2732 "building reference to field in C?");
2733
2734 // These can't have reference type in well-formed programs, but
2735 // for internal consistency we do this anyway.
2736 type = type.getNonReferenceType();
2737 valueKind = VK_LValue;
2738 break;
2739
2740 // Non-type template parameters are either l-values or r-values
2741 // depending on the type.
2742 case Decl::NonTypeTemplateParm: {
2743 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2744 type = reftype->getPointeeType();
2745 valueKind = VK_LValue; // even if the parameter is an r-value reference
2746 break;
2747 }
2748
2749 // For non-references, we need to strip qualifiers just in case
2750 // the template parameter was declared as 'const int' or whatever.
2751 valueKind = VK_RValue;
2752 type = type.getUnqualifiedType();
2753 break;
2754 }
2755
2756 case Decl::Var:
2757 // In C, "extern void blah;" is valid and is an r-value.
2758 if (!getLangOptions().CPlusPlus &&
2759 !type.hasQualifiers() &&
2760 type->isVoidType()) {
2761 valueKind = VK_RValue;
2762 break;
2763 }
2764 // fallthrough
2765
2766 case Decl::ImplicitParam:
2767 case Decl::ParmVar:
2768 // These are always l-values.
2769 valueKind = VK_LValue;
2770 type = type.getNonReferenceType();
2771 break;
2772
2773 case Decl::Function: {
John McCall755d8492011-04-12 00:42:48 +00002774 const FunctionType *fty = type->castAs<FunctionType>();
2775
2776 // If we're referring to a function with an __unknown_anytype
2777 // result type, make the entire expression __unknown_anytype.
2778 if (fty->getResultType() == Context.UnknownAnyTy) {
2779 type = Context.UnknownAnyTy;
2780 valueKind = VK_RValue;
2781 break;
2782 }
2783
John McCall76a40212011-02-09 01:13:10 +00002784 // Functions are l-values in C++.
2785 if (getLangOptions().CPlusPlus) {
2786 valueKind = VK_LValue;
2787 break;
2788 }
2789
2790 // C99 DR 316 says that, if a function type comes from a
2791 // function definition (without a prototype), that type is only
2792 // used for checking compatibility. Therefore, when referencing
2793 // the function, we pretend that we don't have the full function
2794 // type.
John McCall755d8492011-04-12 00:42:48 +00002795 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2796 isa<FunctionProtoType>(fty))
2797 type = Context.getFunctionNoProtoType(fty->getResultType(),
2798 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002799
2800 // Functions are r-values in C.
2801 valueKind = VK_RValue;
2802 break;
2803 }
2804
2805 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002806 // If we're referring to a method with an __unknown_anytype
2807 // result type, make the entire expression __unknown_anytype.
2808 // This should only be possible with a type written directly.
2809 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(VD->getType()))
2810 if (proto->getResultType() == Context.UnknownAnyTy) {
2811 type = Context.UnknownAnyTy;
2812 valueKind = VK_RValue;
2813 break;
2814 }
2815
John McCall76a40212011-02-09 01:13:10 +00002816 // C++ methods are l-values if static, r-values if non-static.
2817 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2818 valueKind = VK_LValue;
2819 break;
2820 }
2821 // fallthrough
2822
2823 case Decl::CXXConversion:
2824 case Decl::CXXDestructor:
2825 case Decl::CXXConstructor:
2826 valueKind = VK_RValue;
2827 break;
2828 }
2829
2830 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2831 }
2832
John McCall469a1eb2011-02-02 13:00:07 +00002833 }
John McCallf89e55a2010-11-18 06:31:45 +00002834
John McCall6b5a61b2011-02-07 10:33:21 +00002835 llvm_unreachable("unknown capture result");
2836 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002837}
2838
John McCall755d8492011-04-12 00:42:48 +00002839ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002840 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002841
Reid Spencer5f016e22007-07-11 17:01:13 +00002842 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00002843 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002844 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2845 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2846 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002847 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002848
Chris Lattnerfa28b302008-01-12 08:14:25 +00002849 // Pre-defined identifiers are of type char[x], where x is the length of the
2850 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002851
Anders Carlsson3a082d82009-09-08 18:24:21 +00002852 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002853 if (!currentDecl && getCurBlock())
2854 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002855 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002856 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002857 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002858 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002859
Anders Carlsson773f3972009-09-11 01:22:35 +00002860 QualType ResTy;
2861 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2862 ResTy = Context.DependentTy;
2863 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002864 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002865
Anders Carlsson773f3972009-09-11 01:22:35 +00002866 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002867 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002868 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2869 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002870 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002871}
2872
John McCall60d7b3a2010-08-24 06:29:42 +00002873ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002874 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002875 bool Invalid = false;
2876 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2877 if (Invalid)
2878 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002879
Benjamin Kramerddeea562010-02-27 13:44:12 +00002880 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2881 PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00002882 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002883 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002884
Chris Lattnere8337df2009-12-30 21:19:39 +00002885 QualType Ty;
2886 if (!getLangOptions().CPlusPlus)
2887 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2888 else if (Literal.isWide())
2889 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002890 else if (Literal.isMultiChar())
2891 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002892 else
2893 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002894
Sebastian Redle91b3bc2009-01-20 22:23:13 +00002895 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2896 Literal.isWide(),
Chris Lattnere8337df2009-12-30 21:19:39 +00002897 Ty, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002898}
2899
John McCall60d7b3a2010-08-24 06:29:42 +00002900ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002901 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002902 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2903 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002904 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00002905 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002906 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002907 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002908 }
Ted Kremenek28396602009-01-13 23:19:12 +00002909
Reid Spencer5f016e22007-07-11 17:01:13 +00002910 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002911 // Add padding so that NumericLiteralParser can overread by one character.
2912 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002913 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002914
Reid Spencer5f016e22007-07-11 17:01:13 +00002915 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002916 bool Invalid = false;
2917 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2918 if (Invalid)
2919 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002920
Mike Stump1eb44332009-09-09 15:08:12 +00002921 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002922 Tok.getLocation(), PP);
2923 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002924 return ExprError();
2925
Chris Lattner5d661452007-08-26 03:42:43 +00002926 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002927
Chris Lattner5d661452007-08-26 03:42:43 +00002928 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002929 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002930 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002931 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002932 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002933 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002934 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002935 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002936
2937 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2938
John McCall94c939d2009-12-24 09:08:04 +00002939 using llvm::APFloat;
2940 APFloat Val(Format);
2941
2942 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002943
2944 // Overflow is always an error, but underflow is only an error if
2945 // we underflowed to zero (APFloat reports denormals as underflow).
2946 if ((result & APFloat::opOverflow) ||
2947 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002948 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002949 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002950 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002951 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002952 APFloat::getLargest(Format).toString(buffer);
2953 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002954 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002955 APFloat::getSmallest(Format).toString(buffer);
2956 }
2957
2958 Diag(Tok.getLocation(), diagnostic)
2959 << Ty
2960 << llvm::StringRef(buffer.data(), buffer.size());
2961 }
2962
2963 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002964 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002965
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002966 if (Ty == Context.DoubleTy) {
2967 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002968 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002969 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2970 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002971 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002972 }
2973 }
Chris Lattner5d661452007-08-26 03:42:43 +00002974 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002975 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002976 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002977 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002978
Neil Boothb9449512007-08-29 22:00:19 +00002979 // long long is a C99 feature.
2980 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00002981 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00002982 Diag(Tok.getLocation(), diag::ext_longlong);
2983
Reid Spencer5f016e22007-07-11 17:01:13 +00002984 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00002985 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002986
Reid Spencer5f016e22007-07-11 17:01:13 +00002987 if (Literal.GetIntegerValue(ResultVal)) {
2988 // If this value didn't fit into uintmax_t, warn and force to ull.
2989 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002990 Ty = Context.UnsignedLongLongTy;
2991 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002992 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002993 } else {
2994 // If this value fits into a ULL, try to figure out what else it fits into
2995 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002996
Reid Spencer5f016e22007-07-11 17:01:13 +00002997 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2998 // be an unsigned int.
2999 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3000
3001 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003002 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00003003 if (!Literal.isLong && !Literal.isLongLong) {
3004 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003005 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00003006
Reid Spencer5f016e22007-07-11 17:01:13 +00003007 // Does it fit in a unsigned int?
3008 if (ResultVal.isIntN(IntSize)) {
3009 // Does it fit in a signed int?
3010 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00003011 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003012 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00003013 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003014 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00003015 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003016 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003017
Reid Spencer5f016e22007-07-11 17:01:13 +00003018 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00003019 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003020 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00003021
Reid Spencer5f016e22007-07-11 17:01:13 +00003022 // Does it fit in a unsigned long?
3023 if (ResultVal.isIntN(LongSize)) {
3024 // Does it fit in a signed long?
3025 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00003026 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003027 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00003028 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003029 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00003030 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003031 }
3032
Reid Spencer5f016e22007-07-11 17:01:13 +00003033 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003034 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003035 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00003036
Reid Spencer5f016e22007-07-11 17:01:13 +00003037 // Does it fit in a unsigned long long?
3038 if (ResultVal.isIntN(LongLongSize)) {
3039 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00003040 // To be compatible with MSVC, hex integer literals ending with the
3041 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00003042 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3043 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00003044 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003045 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00003046 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003047 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00003048 }
3049 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003050
Reid Spencer5f016e22007-07-11 17:01:13 +00003051 // If we still couldn't decide a type, we probably have something that
3052 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003053 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003054 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003055 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003056 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00003057 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003058
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00003059 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003060 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00003061 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003062 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00003063 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003064
Chris Lattner5d661452007-08-26 03:42:43 +00003065 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3066 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00003067 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003068 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00003069
3070 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00003071}
3072
John McCall60d7b3a2010-08-24 06:29:42 +00003073ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCall9ae2f072010-08-23 23:25:46 +00003074 SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00003075 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00003076 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00003077}
3078
Chandler Carruthdf1f3772011-05-26 08:53:12 +00003079static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3080 SourceLocation Loc,
3081 SourceRange ArgRange) {
3082 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3083 // scalar or vector data type argument..."
3084 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3085 // type (C99 6.2.5p18) or void.
3086 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3087 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3088 << T << ArgRange;
3089 return true;
3090 }
3091
3092 assert((T->isVoidType() || !T->isIncompleteType()) &&
3093 "Scalar types should always be complete");
3094 return false;
3095}
3096
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003097static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3098 SourceLocation Loc,
3099 SourceRange ArgRange,
3100 UnaryExprOrTypeTrait TraitKind) {
3101 // C99 6.5.3.4p1:
3102 if (T->isFunctionType()) {
3103 // alignof(function) is allowed as an extension.
3104 if (TraitKind == UETT_SizeOf)
3105 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
3106 return false;
3107 }
3108
3109 // Allow sizeof(void)/alignof(void) as an extension.
3110 if (T->isVoidType()) {
3111 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
3112 return false;
3113 }
3114
3115 return true;
3116}
3117
3118static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3119 SourceLocation Loc,
3120 SourceRange ArgRange,
3121 UnaryExprOrTypeTrait TraitKind) {
3122 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
3123 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
3124 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3125 << T << (TraitKind == UETT_SizeOf)
3126 << ArgRange;
3127 return true;
3128 }
3129
3130 return false;
3131}
3132
Chandler Carruth9d342d02011-05-26 08:53:10 +00003133/// \brief Check the constrains on expression operands to unary type expression
3134/// and type traits.
3135///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003136/// Completes any types necessary and validates the constraints on the operand
3137/// expression. The logic mostly mirrors the type-based overload, but may modify
3138/// the expression as it completes the type for that expression through template
3139/// instantiation, etc.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003140bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op,
3141 UnaryExprOrTypeTrait ExprKind) {
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003142 QualType ExprTy = Op->getType();
3143
3144 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3145 // the result is the size of the referenced type."
3146 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3147 // result shall be the alignment of the referenced type."
3148 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3149 ExprTy = Ref->getPointeeType();
3150
3151 if (ExprKind == UETT_VecStep)
3152 return CheckVecStepTraitOperandType(*this, ExprTy, Op->getExprLoc(),
3153 Op->getSourceRange());
3154
3155 // Whitelist some types as extensions
3156 if (!CheckExtensionTraitOperandType(*this, ExprTy, Op->getExprLoc(),
3157 Op->getSourceRange(), ExprKind))
3158 return false;
3159
3160 if (RequireCompleteExprType(Op,
3161 PDiag(diag::err_sizeof_alignof_incomplete_type)
3162 << ExprKind << Op->getSourceRange(),
3163 std::make_pair(SourceLocation(), PDiag(0))))
3164 return true;
3165
3166 // Completeing the expression's type may have changed it.
3167 ExprTy = Op->getType();
3168 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3169 ExprTy = Ref->getPointeeType();
3170
3171 if (CheckObjCTraitOperandConstraints(*this, ExprTy, Op->getExprLoc(),
3172 Op->getSourceRange(), ExprKind))
3173 return true;
3174
Nico Webercf739922011-06-15 02:47:03 +00003175 if (ExprKind == UETT_SizeOf) {
3176 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Op->IgnoreParens())) {
3177 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3178 QualType OType = PVD->getOriginalType();
3179 QualType Type = PVD->getType();
3180 if (Type->isPointerType() && OType->isArrayType()) {
3181 Diag(Op->getExprLoc(), diag::warn_sizeof_array_param)
3182 << Type << OType;
3183 Diag(PVD->getLocation(), diag::note_declared_at);
3184 }
3185 }
3186 }
3187 }
3188
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003189 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00003190}
3191
3192/// \brief Check the constraints on operands to unary expression and type
3193/// traits.
3194///
3195/// This will complete any types necessary, and validate the various constraints
3196/// on those operands.
3197///
Reid Spencer5f016e22007-07-11 17:01:13 +00003198/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003199/// C99 6.3.2.1p[2-4] all state:
3200/// Except when it is the operand of the sizeof operator ...
3201///
3202/// C++ [expr.sizeof]p4
3203/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3204/// standard conversions are not applied to the operand of sizeof.
3205///
3206/// This policy is followed for all of the unary trait expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003207bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
3208 SourceLocation OpLoc,
3209 SourceRange ExprRange,
3210 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl28507842009-02-26 14:39:58 +00003211 if (exprType->isDependentType())
3212 return false;
3213
Sebastian Redl5d484e82009-11-23 17:18:46 +00003214 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3215 // the result is the size of the referenced type."
3216 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3217 // result shall be the alignment of the referenced type."
3218 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
3219 exprType = Ref->getPointeeType();
3220
Chandler Carruthdf1f3772011-05-26 08:53:12 +00003221 if (ExprKind == UETT_VecStep)
3222 return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003223
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003224 // Whitelist some types as extensions
3225 if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange,
3226 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00003227 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003228
Chris Lattner1efaa952009-04-24 00:30:45 +00003229 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00003230 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003231 << ExprKind << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00003232 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003233
Chandler Carruth42ec65d2011-05-26 08:53:16 +00003234 if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange,
3235 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00003236 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003237
Chris Lattner1efaa952009-04-24 00:30:45 +00003238 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00003239}
3240
Chandler Carruth9d342d02011-05-26 08:53:10 +00003241static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00003242 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00003243
Mike Stump1eb44332009-09-09 15:08:12 +00003244 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00003245 if (isa<DeclRefExpr>(E))
3246 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00003247
3248 // Cannot know anything else if the expression is dependent.
3249 if (E->isTypeDependent())
3250 return false;
3251
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003252 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003253 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3254 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003255 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00003256 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003257
3258 // Alignment of a field access is always okay, so long as it isn't a
3259 // bit-field.
3260 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00003261 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003262 return false;
3263
Chandler Carruth9d342d02011-05-26 08:53:10 +00003264 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003265}
3266
Chandler Carruth9d342d02011-05-26 08:53:10 +00003267bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003268 E = E->IgnoreParens();
3269
3270 // Cannot know anything else if the expression is dependent.
3271 if (E->isTypeDependent())
3272 return false;
3273
Chandler Carruth9d342d02011-05-26 08:53:10 +00003274 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00003275}
3276
Douglas Gregorba498172009-03-13 21:01:28 +00003277/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003278ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003279Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3280 SourceLocation OpLoc,
3281 UnaryExprOrTypeTrait ExprKind,
3282 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00003283 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00003284 return ExprError();
3285
John McCalla93c9342009-12-07 02:54:59 +00003286 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00003287
Douglas Gregorba498172009-03-13 21:01:28 +00003288 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003289 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00003290 return ExprError();
3291
3292 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003293 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3294 Context.getSizeType(),
3295 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003296}
3297
3298/// \brief Build a sizeof or alignof expression given an expression
3299/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003300ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003301Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3302 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregorba498172009-03-13 21:01:28 +00003303 // Verify that the operand is valid.
3304 bool isInvalid = false;
3305 if (E->isTypeDependent()) {
3306 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003307 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003308 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003309 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003310 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003311 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003312 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00003313 isInvalid = true;
John McCall2cd11fe2010-10-12 02:09:17 +00003314 } else if (E->getType()->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00003315 ExprResult PE = CheckPlaceholderExpr(E);
John McCall2cd11fe2010-10-12 02:09:17 +00003316 if (PE.isInvalid()) return ExprError();
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003317 return CreateUnaryExprOrTypeTraitExpr(PE.take(), OpLoc, ExprKind);
Douglas Gregorba498172009-03-13 21:01:28 +00003318 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00003319 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00003320 }
3321
3322 if (isInvalid)
3323 return ExprError();
3324
3325 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00003326 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003327 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00003328 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003329}
3330
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003331/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3332/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00003333/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00003334ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003335Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3336 UnaryExprOrTypeTrait ExprKind, bool isType,
3337 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003338 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003339 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003340
Sebastian Redl05189992008-11-11 17:56:53 +00003341 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00003342 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00003343 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003344 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00003345 }
Sebastian Redl05189992008-11-11 17:56:53 +00003346
Douglas Gregorba498172009-03-13 21:01:28 +00003347 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00003348 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregorba498172009-03-13 21:01:28 +00003349 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00003350}
3351
John Wiegley429bb272011-04-08 18:41:53 +00003352static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall09431682010-11-18 19:01:18 +00003353 bool isReal) {
John Wiegley429bb272011-04-08 18:41:53 +00003354 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00003355 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003356
John McCallf6a16482010-12-04 03:47:34 +00003357 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00003358 if (V.get()->getObjectKind() != OK_Ordinary) {
3359 V = S.DefaultLvalueConversion(V.take());
3360 if (V.isInvalid())
3361 return QualType();
3362 }
John McCallf6a16482010-12-04 03:47:34 +00003363
Chris Lattnercc26ed72007-08-26 05:39:26 +00003364 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003365 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003366 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003367
Chris Lattnercc26ed72007-08-26 05:39:26 +00003368 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003369 if (V.get()->getType()->isArithmeticType())
3370 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003371
John McCall2cd11fe2010-10-12 02:09:17 +00003372 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003373 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003374 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003375 if (PR.get() != V.get()) {
3376 V = move(PR);
John McCall09431682010-11-18 19:01:18 +00003377 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003378 }
3379
Chris Lattnercc26ed72007-08-26 05:39:26 +00003380 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003381 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattnerba27e2a2009-02-17 08:12:06 +00003382 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003383 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003384}
3385
3386
Reid Spencer5f016e22007-07-11 17:01:13 +00003387
John McCall60d7b3a2010-08-24 06:29:42 +00003388ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003389Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003390 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003391 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003392 switch (Kind) {
3393 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003394 case tok::plusplus: Opc = UO_PostInc; break;
3395 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003396 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003397
John McCall9ae2f072010-08-23 23:25:46 +00003398 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003399}
3400
John McCall09431682010-11-18 19:01:18 +00003401/// Expressions of certain arbitrary types are forbidden by C from
3402/// having l-value type. These are:
3403/// - 'void', but not qualified void
3404/// - function types
3405///
3406/// The exact rule here is C99 6.3.2.1:
3407/// An lvalue is an expression with an object type or an incomplete
3408/// type other than void.
3409static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
3410 return ((T->isVoidType() && !T.hasQualifiers()) ||
3411 T->isFunctionType());
3412}
3413
John McCall60d7b3a2010-08-24 06:29:42 +00003414ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003415Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3416 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003417 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003418 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003419 if (Result.isInvalid()) return ExprError();
3420 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003421
John McCall9ae2f072010-08-23 23:25:46 +00003422 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003423
Douglas Gregor337c6b92008-11-19 17:17:41 +00003424 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003425 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003426 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003427 Context.DependentTy,
3428 VK_LValue, OK_Ordinary,
3429 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003430 }
3431
Mike Stump1eb44332009-09-09 15:08:12 +00003432 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003433 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003434 LHSExp->getType()->isEnumeralType() ||
3435 RHSExp->getType()->isRecordType() ||
3436 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00003437 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003438 }
3439
John McCall9ae2f072010-08-23 23:25:46 +00003440 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003441}
3442
3443
John McCall60d7b3a2010-08-24 06:29:42 +00003444ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003445Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3446 Expr *Idx, SourceLocation RLoc) {
3447 Expr *LHSExp = Base;
3448 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003449
Chris Lattner12d9ff62007-07-16 00:14:47 +00003450 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003451 if (!LHSExp->getType()->getAs<VectorType>()) {
3452 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3453 if (Result.isInvalid())
3454 return ExprError();
3455 LHSExp = Result.take();
3456 }
3457 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3458 if (Result.isInvalid())
3459 return ExprError();
3460 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003461
Chris Lattner12d9ff62007-07-16 00:14:47 +00003462 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003463 ExprValueKind VK = VK_LValue;
3464 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003465
Reid Spencer5f016e22007-07-11 17:01:13 +00003466 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003467 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003468 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003469 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003470 Expr *BaseExpr, *IndexExpr;
3471 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003472 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3473 BaseExpr = LHSExp;
3474 IndexExpr = RHSExp;
3475 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003476 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003477 BaseExpr = LHSExp;
3478 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003479 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003480 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00003481 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00003482 BaseExpr = RHSExp;
3483 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003484 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003485 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003486 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003487 BaseExpr = LHSExp;
3488 IndexExpr = RHSExp;
3489 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003490 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003491 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003492 // Handle the uncommon case of "123[Ptr]".
3493 BaseExpr = RHSExp;
3494 IndexExpr = LHSExp;
3495 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003496 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003497 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003498 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003499 VK = LHSExp->getValueKind();
3500 if (VK != VK_RValue)
3501 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003502
Chris Lattner12d9ff62007-07-16 00:14:47 +00003503 // FIXME: need to deal with const...
3504 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003505 } else if (LHSTy->isArrayType()) {
3506 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003507 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003508 // wasn't promoted because of the C90 rule that doesn't
3509 // allow promoting non-lvalue arrays. Warn, then
3510 // force the promotion here.
3511 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3512 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003513 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3514 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003515 LHSTy = LHSExp->getType();
3516
3517 BaseExpr = LHSExp;
3518 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003519 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003520 } else if (RHSTy->isArrayType()) {
3521 // Same as previous, except for 123[f().a] case
3522 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3523 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003524 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3525 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003526 RHSTy = RHSExp->getType();
3527
3528 BaseExpr = RHSExp;
3529 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003530 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003531 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003532 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3533 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003534 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003535 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003536 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003537 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3538 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003539
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003540 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003541 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3542 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003543 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3544
Douglas Gregore7450f52009-03-24 19:52:54 +00003545 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003546 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3547 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003548 // incomplete types are not object types.
3549 if (ResultType->isFunctionType()) {
3550 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3551 << ResultType << BaseExpr->getSourceRange();
3552 return ExprError();
3553 }
Mike Stump1eb44332009-09-09 15:08:12 +00003554
Abramo Bagnara46358452010-09-13 06:50:07 +00003555 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3556 // GNU extension: subscripting on pointer to void
3557 Diag(LLoc, diag::ext_gnu_void_ptr)
3558 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003559
3560 // C forbids expressions of unqualified void type from being l-values.
3561 // See IsCForbiddenLValueType.
3562 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003563 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003564 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003565 PDiag(diag::err_subscript_incomplete_type)
3566 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003567 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003568
Chris Lattner1efaa952009-04-24 00:30:45 +00003569 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003570 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003571 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3572 << ResultType << BaseExpr->getSourceRange();
3573 return ExprError();
3574 }
Mike Stump1eb44332009-09-09 15:08:12 +00003575
John McCall09431682010-11-18 19:01:18 +00003576 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3577 !IsCForbiddenLValueType(Context, ResultType));
3578
Mike Stumpeed9cac2009-02-19 03:04:26 +00003579 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003580 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003581}
3582
John McCall09431682010-11-18 19:01:18 +00003583/// Check an ext-vector component access expression.
3584///
3585/// VK should be set in advance to the value kind of the base
3586/// expression.
3587static QualType
3588CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3589 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003590 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00003591 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3592 // see FIXME there.
3593 //
3594 // FIXME: This logic can be greatly simplified by splitting it along
3595 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00003596 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00003597
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003598 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00003599 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003600
Mike Stumpeed9cac2009-02-19 03:04:26 +00003601 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00003602 // special names that indicate a subset of exactly half the elements are
3603 // to be selected.
3604 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003605
Nate Begeman353417a2009-01-18 01:47:54 +00003606 // This flag determines whether or not CompName has an 's' char prefix,
3607 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00003608 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00003609
John McCall09431682010-11-18 19:01:18 +00003610 bool HasRepeated = false;
3611 bool HasIndex[16] = {};
3612
3613 int Idx;
3614
Nate Begeman8a997642008-05-09 06:41:27 +00003615 // Check that we've found one of the special components, or that the component
3616 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003617 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00003618 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3619 HalvingSwizzle = true;
John McCall09431682010-11-18 19:01:18 +00003620 } else if (!HexSwizzle &&
3621 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3622 do {
3623 if (HasIndex[Idx]) HasRepeated = true;
3624 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003625 compStr++;
John McCall09431682010-11-18 19:01:18 +00003626 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3627 } else {
3628 if (HexSwizzle) compStr++;
3629 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3630 if (HasIndex[Idx]) HasRepeated = true;
3631 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003632 compStr++;
John McCall09431682010-11-18 19:01:18 +00003633 }
Chris Lattner88dca042007-08-02 22:33:49 +00003634 }
Nate Begeman353417a2009-01-18 01:47:54 +00003635
Mike Stumpeed9cac2009-02-19 03:04:26 +00003636 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003637 // We didn't get to the end of the string. This means the component names
3638 // didn't come from the same set *or* we encountered an illegal name.
John McCall09431682010-11-18 19:01:18 +00003639 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00003640 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003641 return QualType();
3642 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003643
Nate Begeman353417a2009-01-18 01:47:54 +00003644 // Ensure no component accessor exceeds the width of the vector type it
3645 // operates on.
3646 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00003647 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003648
3649 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003650 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00003651
3652 while (*compStr) {
3653 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall09431682010-11-18 19:01:18 +00003654 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begeman353417a2009-01-18 01:47:54 +00003655 << baseType << SourceRange(CompLoc);
3656 return QualType();
3657 }
3658 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003659 }
Nate Begeman8a997642008-05-09 06:41:27 +00003660
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003661 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003662 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003663 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00003664 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00003665 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00003666 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00003667 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00003668 if (HexSwizzle)
3669 CompSize--;
3670
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003671 if (CompSize == 1)
3672 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003673
John McCall09431682010-11-18 19:01:18 +00003674 if (HasRepeated) VK = VK_RValue;
3675
3676 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003677 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00003678 // diagostics look bad. We want extended vector types to appear built-in.
John McCall09431682010-11-18 19:01:18 +00003679 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3680 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3681 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00003682 }
3683 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003684}
3685
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003686static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003687 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003688 const Selector &Sel,
3689 ASTContext &Context) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003690 if (Member)
3691 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3692 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003693 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003694 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00003695
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003696 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3697 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003698 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3699 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003700 return D;
3701 }
3702 return 0;
3703}
3704
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003705static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3706 IdentifierInfo *Member,
3707 const Selector &Sel,
3708 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003709 // Check protocols on qualified interfaces.
3710 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003711 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003712 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003713 if (Member)
3714 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3715 GDecl = PD;
3716 break;
3717 }
3718 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003719 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003720 GDecl = OMD;
3721 break;
3722 }
3723 }
3724 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003725 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003726 E = QIdTy->qual_end(); I != E; ++I) {
3727 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003728 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3729 Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003730 if (GDecl)
3731 return GDecl;
3732 }
3733 }
3734 return GDecl;
3735}
Chris Lattner76a642f2009-02-15 22:43:40 +00003736
John McCall60d7b3a2010-08-24 06:29:42 +00003737ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003738Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCallaa81e162009-12-01 22:10:20 +00003739 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00003740 const CXXScopeSpec &SS,
3741 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003742 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003743 const TemplateArgumentListInfo *TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00003744 // Even in dependent contexts, try to diagnose base expressions with
3745 // obviously wrong types, e.g.:
3746 //
3747 // T* t;
3748 // t.f;
3749 //
3750 // In Obj-C++, however, the above expression is valid, since it could be
3751 // accessing the 'f' property if T is an Obj-C interface. The extra check
3752 // allows this, while still reporting an error if T is a struct pointer.
3753 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00003754 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00003755 if (PT && (!getLangOptions().ObjC1 ||
3756 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00003757 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnara25777432010-08-11 22:01:17 +00003758 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00003759 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00003760 return ExprError();
3761 }
3762 }
3763
Abramo Bagnara25777432010-08-11 22:01:17 +00003764 assert(BaseType->isDependentType() ||
3765 NameInfo.getName().isDependentName() ||
Douglas Gregor01e56ae2010-04-12 20:54:26 +00003766 isDependentScopeSpecifier(SS));
John McCall129e2df2009-11-30 22:42:35 +00003767
3768 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3769 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00003770 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003771 IsArrow, OpLoc,
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003772 SS.getWithLocInContext(Context),
John McCall129e2df2009-11-30 22:42:35 +00003773 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003774 NameInfo, TemplateArgs));
John McCall129e2df2009-11-30 22:42:35 +00003775}
3776
3777/// We know that the given qualified member reference points only to
3778/// declarations which do not belong to the static type of the base
3779/// expression. Diagnose the problem.
3780static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3781 Expr *BaseExpr,
3782 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003783 const CXXScopeSpec &SS,
John McCall5808ce42011-02-03 08:15:49 +00003784 NamedDecl *rep,
3785 const DeclarationNameInfo &nameInfo) {
John McCall2f841ba2009-12-02 03:53:29 +00003786 // If this is an implicit member access, use a different set of
3787 // diagnostics.
3788 if (!BaseExpr)
John McCall5808ce42011-02-03 08:15:49 +00003789 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall129e2df2009-11-30 22:42:35 +00003790
John McCall5808ce42011-02-03 08:15:49 +00003791 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3792 << SS.getRange() << rep << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00003793}
3794
3795// Check whether the declarations we found through a nested-name
3796// specifier in a member expression are actually members of the base
3797// type. The restriction here is:
3798//
3799// C++ [expr.ref]p2:
3800// ... In these cases, the id-expression shall name a
3801// member of the class or of one of its base classes.
3802//
3803// So it's perfectly legitimate for the nested-name specifier to name
3804// an unrelated class, and for us to find an overload set including
3805// decls from classes which are not superclasses, as long as the decl
3806// we actually pick through overload resolution is from a superclass.
3807bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3808 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003809 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003810 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00003811 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3812 if (!BaseRT) {
3813 // We can't check this yet because the base type is still
3814 // dependent.
3815 assert(BaseType->isDependentType());
3816 return false;
3817 }
3818 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00003819
3820 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00003821 // If this is an implicit member reference and we find a
3822 // non-instance member, it's not an error.
John McCall161755a2010-04-06 21:38:20 +00003823 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCallaa81e162009-12-01 22:10:20 +00003824 return false;
John McCall129e2df2009-11-30 22:42:35 +00003825
John McCallaa81e162009-12-01 22:10:20 +00003826 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman02463762010-07-27 20:51:02 +00003827 DeclContext *DC = (*I)->getDeclContext();
3828 while (DC->isTransparentContext())
3829 DC = DC->getParent();
John McCallaa81e162009-12-01 22:10:20 +00003830
Douglas Gregor9d4bb942010-07-28 22:27:52 +00003831 if (!DC->isRecord())
3832 continue;
3833
John McCallaa81e162009-12-01 22:10:20 +00003834 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman02463762010-07-27 20:51:02 +00003835 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCallaa81e162009-12-01 22:10:20 +00003836
3837 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3838 return false;
3839 }
3840
John McCall5808ce42011-02-03 08:15:49 +00003841 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3842 R.getRepresentativeDecl(),
3843 R.getLookupNameInfo());
John McCallaa81e162009-12-01 22:10:20 +00003844 return true;
3845}
3846
3847static bool
3848LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3849 SourceRange BaseRange, const RecordType *RTy,
John McCallad00b772010-06-16 08:42:20 +00003850 SourceLocation OpLoc, CXXScopeSpec &SS,
3851 bool HasTemplateArgs) {
John McCallaa81e162009-12-01 22:10:20 +00003852 RecordDecl *RDecl = RTy->getDecl();
3853 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003854 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCallaa81e162009-12-01 22:10:20 +00003855 << BaseRange))
3856 return true;
3857
John McCallad00b772010-06-16 08:42:20 +00003858 if (HasTemplateArgs) {
3859 // LookupTemplateName doesn't expect these both to exist simultaneously.
3860 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3861
3862 bool MOUS;
3863 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3864 return false;
3865 }
3866
John McCallaa81e162009-12-01 22:10:20 +00003867 DeclContext *DC = RDecl;
3868 if (SS.isSet()) {
3869 // If the member name was a qualified-id, look into the
3870 // nested-name-specifier.
3871 DC = SemaRef.computeDeclContext(SS, false);
3872
John McCall77bb1aa2010-05-01 00:40:08 +00003873 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCall2f841ba2009-12-02 03:53:29 +00003874 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3875 << SS.getRange() << DC;
3876 return true;
3877 }
3878
John McCallaa81e162009-12-01 22:10:20 +00003879 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003880
John McCallaa81e162009-12-01 22:10:20 +00003881 if (!isa<TypeDecl>(DC)) {
3882 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3883 << DC << SS.getRange();
3884 return true;
John McCall129e2df2009-11-30 22:42:35 +00003885 }
3886 }
3887
John McCallaa81e162009-12-01 22:10:20 +00003888 // The record definition is complete, now look up the member.
3889 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00003890
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003891 if (!R.empty())
3892 return false;
3893
3894 // We didn't find anything with the given name, so try to correct
3895 // for typos.
3896 DeclarationName Name = R.getLookupName();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003897 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00003898 !R.empty() &&
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003899 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3900 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3901 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00003902 << FixItHint::CreateReplacement(R.getNameLoc(),
3903 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003904 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3905 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3906 << ND->getDeclName();
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003907 return false;
3908 } else {
3909 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003910 R.setLookupName(Name);
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003911 }
3912
John McCall129e2df2009-11-30 22:42:35 +00003913 return false;
3914}
3915
John McCall60d7b3a2010-08-24 06:29:42 +00003916ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003917Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003918 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003919 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003920 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003921 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003922 const TemplateArgumentListInfo *TemplateArgs) {
John McCall2f841ba2009-12-02 03:53:29 +00003923 if (BaseType->isDependentType() ||
3924 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall9ae2f072010-08-23 23:25:46 +00003925 return ActOnDependentMemberExpr(Base, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003926 IsArrow, OpLoc,
3927 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003928 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003929
Abramo Bagnara25777432010-08-11 22:01:17 +00003930 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00003931
John McCallaa81e162009-12-01 22:10:20 +00003932 // Implicit member accesses.
3933 if (!Base) {
3934 QualType RecordTy = BaseType;
3935 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3936 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3937 RecordTy->getAs<RecordType>(),
John McCallad00b772010-06-16 08:42:20 +00003938 OpLoc, SS, TemplateArgs != 0))
John McCallaa81e162009-12-01 22:10:20 +00003939 return ExprError();
3940
3941 // Explicit member accesses.
3942 } else {
John Wiegley429bb272011-04-08 18:41:53 +00003943 ExprResult BaseResult = Owned(Base);
John McCall60d7b3a2010-08-24 06:29:42 +00003944 ExprResult Result =
John Wiegley429bb272011-04-08 18:41:53 +00003945 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCalld226f652010-08-21 09:40:31 +00003946 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCallaa81e162009-12-01 22:10:20 +00003947
John Wiegley429bb272011-04-08 18:41:53 +00003948 if (BaseResult.isInvalid())
3949 return ExprError();
3950 Base = BaseResult.take();
3951
John McCallaa81e162009-12-01 22:10:20 +00003952 if (Result.isInvalid()) {
3953 Owned(Base);
3954 return ExprError();
3955 }
3956
3957 if (Result.get())
3958 return move(Result);
Sebastian Redlf3e63372010-05-07 09:25:11 +00003959
3960 // LookupMemberExpr can modify Base, and thus change BaseType
3961 BaseType = Base->getType();
John McCall129e2df2009-11-30 22:42:35 +00003962 }
3963
John McCall9ae2f072010-08-23 23:25:46 +00003964 return BuildMemberReferenceExpr(Base, BaseType,
John McCallc2233c52010-01-15 08:34:02 +00003965 OpLoc, IsArrow, SS, FirstQualifierInScope,
3966 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003967}
3968
John McCall60d7b3a2010-08-24 06:29:42 +00003969ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003970Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCallaa81e162009-12-01 22:10:20 +00003971 SourceLocation OpLoc, bool IsArrow,
3972 const CXXScopeSpec &SS,
John McCallc2233c52010-01-15 08:34:02 +00003973 NamedDecl *FirstQualifierInScope,
John McCall129e2df2009-11-30 22:42:35 +00003974 LookupResult &R,
Douglas Gregor06a9f362010-05-01 20:49:11 +00003975 const TemplateArgumentListInfo *TemplateArgs,
3976 bool SuppressQualifierCheck) {
John McCallaa81e162009-12-01 22:10:20 +00003977 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00003978 if (IsArrow) {
3979 assert(BaseType->isPointerType());
3980 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3981 }
John McCall161755a2010-04-06 21:38:20 +00003982 R.setBaseObjectType(BaseType);
John McCall129e2df2009-11-30 22:42:35 +00003983
Abramo Bagnara25777432010-08-11 22:01:17 +00003984 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3985 DeclarationName MemberName = MemberNameInfo.getName();
3986 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall129e2df2009-11-30 22:42:35 +00003987
3988 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00003989 return ExprError();
3990
John McCall129e2df2009-11-30 22:42:35 +00003991 if (R.empty()) {
3992 // Rederive where we looked up.
3993 DeclContext *DC = (SS.isSet()
3994 ? computeDeclContext(SS, false)
3995 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00003996
John McCall129e2df2009-11-30 22:42:35 +00003997 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00003998 << MemberName << DC
3999 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00004000 return ExprError();
4001 }
4002
John McCallc2233c52010-01-15 08:34:02 +00004003 // Diagnose lookups that find only declarations from a non-base
4004 // type. This is possible for either qualified lookups (which may
4005 // have been qualified with an unrelated type) or implicit member
4006 // expressions (which were found with unqualified lookup and thus
4007 // may have come from an enclosing scope). Note that it's okay for
4008 // lookup to find declarations from a non-base type as long as those
4009 // aren't the ones picked by overload resolution.
4010 if ((SS.isSet() || !BaseExpr ||
4011 (isa<CXXThisExpr>(BaseExpr) &&
4012 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00004013 !SuppressQualifierCheck &&
John McCallc2233c52010-01-15 08:34:02 +00004014 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00004015 return ExprError();
4016
4017 // Construct an unresolved result if we in fact got an unresolved
4018 // result.
4019 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallc373d482010-01-27 01:50:18 +00004020 // Suppress any lookup-related diagnostics; we'll do these when we
4021 // pick a member.
4022 R.suppressDiagnostics();
4023
John McCall129e2df2009-11-30 22:42:35 +00004024 UnresolvedMemberExpr *MemExpr
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00004025 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00004026 BaseExpr, BaseExprType,
4027 IsArrow, OpLoc,
Douglas Gregor4c9be892011-02-28 20:01:57 +00004028 SS.getWithLocInContext(Context),
Abramo Bagnara25777432010-08-11 22:01:17 +00004029 MemberNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00004030 TemplateArgs, R.begin(), R.end());
John McCall129e2df2009-11-30 22:42:35 +00004031
4032 return Owned(MemExpr);
4033 }
4034
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004035 assert(R.isSingleResult());
John McCall161755a2010-04-06 21:38:20 +00004036 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall129e2df2009-11-30 22:42:35 +00004037 NamedDecl *MemberDecl = R.getFoundDecl();
4038
4039 // FIXME: diagnose the presence of template arguments now.
4040
4041 // If the decl being referenced had an error, return an error for this
4042 // sub-expr without emitting another error, in order to avoid cascading
4043 // error cases.
4044 if (MemberDecl->isInvalidDecl())
4045 return ExprError();
4046
John McCallaa81e162009-12-01 22:10:20 +00004047 // Handle the implicit-member-access case.
4048 if (!BaseExpr) {
4049 // If this is not an instance member, convert to a non-member access.
John McCall161755a2010-04-06 21:38:20 +00004050 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnara25777432010-08-11 22:01:17 +00004051 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCallaa81e162009-12-01 22:10:20 +00004052
Douglas Gregor828a1972010-01-07 23:12:05 +00004053 SourceLocation Loc = R.getNameLoc();
4054 if (SS.getRange().isValid())
4055 Loc = SS.getRange().getBegin();
4056 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCallaa81e162009-12-01 22:10:20 +00004057 }
4058
John McCall129e2df2009-11-30 22:42:35 +00004059 bool ShouldCheckUse = true;
4060 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
4061 // Don't diagnose the use of a virtual member function unless it's
4062 // explicitly qualified.
4063 if (MD->isVirtual() && !SS.isSet())
4064 ShouldCheckUse = false;
4065 }
4066
4067 // Check the use of this member.
4068 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
4069 Owned(BaseExpr);
4070 return ExprError();
4071 }
4072
John McCallf6a16482010-12-04 03:47:34 +00004073 // Perform a property load on the base regardless of whether we
4074 // actually need it for the declaration.
John Wiegley429bb272011-04-08 18:41:53 +00004075 if (BaseExpr->getObjectKind() == OK_ObjCProperty) {
4076 ExprResult Result = ConvertPropertyForRValue(BaseExpr);
4077 if (Result.isInvalid())
4078 return ExprError();
4079 BaseExpr = Result.take();
4080 }
John McCallf6a16482010-12-04 03:47:34 +00004081
John McCalldfa1edb2010-11-23 20:48:44 +00004082 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
4083 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
4084 SS, FD, FoundDecl, MemberNameInfo);
John McCall129e2df2009-11-30 22:42:35 +00004085
Francois Pichet87c2e122010-11-21 06:08:52 +00004086 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
4087 // We may have found a field within an anonymous union or struct
4088 // (C++ [class.union]).
John McCall5808ce42011-02-03 08:15:49 +00004089 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCallf6a16482010-12-04 03:47:34 +00004090 BaseExpr, OpLoc);
Francois Pichet87c2e122010-11-21 06:08:52 +00004091
John McCall129e2df2009-11-30 22:42:35 +00004092 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
4093 MarkDeclarationReferenced(MemberLoc, Var);
4094 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00004095 Var, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00004096 Var->getType().getNonReferenceType(),
John McCall09431682010-11-18 19:01:18 +00004097 VK_LValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00004098 }
4099
John McCallf89e55a2010-11-18 06:31:45 +00004100 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall864c0412011-04-26 20:42:42 +00004101 ExprValueKind valueKind;
4102 QualType type;
4103 if (MemberFn->isInstance()) {
4104 valueKind = VK_RValue;
4105 type = Context.BoundMemberTy;
4106 } else {
4107 valueKind = VK_LValue;
4108 type = MemberFn->getType();
4109 }
4110
John McCall129e2df2009-11-30 22:42:35 +00004111 MarkDeclarationReferenced(MemberLoc, MemberDecl);
4112 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00004113 MemberFn, FoundDecl, MemberNameInfo,
John McCall864c0412011-04-26 20:42:42 +00004114 type, valueKind, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00004115 }
John McCallf89e55a2010-11-18 06:31:45 +00004116 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall129e2df2009-11-30 22:42:35 +00004117
4118 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
4119 MarkDeclarationReferenced(MemberLoc, MemberDecl);
4120 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00004121 Enum, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00004122 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00004123 }
4124
4125 Owned(BaseExpr);
4126
Douglas Gregorb0fd4832010-04-25 20:55:08 +00004127 // We found something that we didn't expect. Complain.
John McCall129e2df2009-11-30 22:42:35 +00004128 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnara25777432010-08-11 22:01:17 +00004129 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregorb0fd4832010-04-25 20:55:08 +00004130 << MemberName << BaseType << int(IsArrow);
4131 else
4132 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
4133 << MemberName << BaseType << int(IsArrow);
John McCall129e2df2009-11-30 22:42:35 +00004134
Douglas Gregorb0fd4832010-04-25 20:55:08 +00004135 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
4136 << MemberName;
Douglas Gregor2b147f02010-04-25 21:15:30 +00004137 R.suppressDiagnostics();
Douglas Gregorb0fd4832010-04-25 20:55:08 +00004138 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00004139}
4140
John McCall028d3972010-12-15 16:46:44 +00004141/// Given that normal member access failed on the given expression,
4142/// and given that the expression's type involves builtin-id or
4143/// builtin-Class, decide whether substituting in the redefinition
4144/// types would be profitable. The redefinition type is whatever
4145/// this translation unit tried to typedef to id/Class; we store
4146/// it to the side and then re-use it in places like this.
John Wiegley429bb272011-04-08 18:41:53 +00004147static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
John McCall028d3972010-12-15 16:46:44 +00004148 const ObjCObjectPointerType *opty
John Wiegley429bb272011-04-08 18:41:53 +00004149 = base.get()->getType()->getAs<ObjCObjectPointerType>();
John McCall028d3972010-12-15 16:46:44 +00004150 if (!opty) return false;
4151
4152 const ObjCObjectType *ty = opty->getObjectType();
4153
4154 QualType redef;
4155 if (ty->isObjCId()) {
4156 redef = S.Context.ObjCIdRedefinitionType;
4157 } else if (ty->isObjCClass()) {
4158 redef = S.Context.ObjCClassRedefinitionType;
4159 } else {
4160 return false;
4161 }
4162
4163 // Do the substitution as long as the redefinition type isn't just a
4164 // possibly-qualified pointer to builtin-id or builtin-Class again.
4165 opty = redef->getAs<ObjCObjectPointerType>();
4166 if (opty && !opty->getObjectType()->getInterface() != 0)
4167 return false;
4168
John Wiegley429bb272011-04-08 18:41:53 +00004169 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
John McCall028d3972010-12-15 16:46:44 +00004170 return true;
4171}
4172
John McCall129e2df2009-11-30 22:42:35 +00004173/// Look up the given member of the given non-type-dependent
4174/// expression. This can return in one of two ways:
4175/// * If it returns a sentinel null-but-valid result, the caller will
4176/// assume that lookup was performed and the results written into
4177/// the provided structure. It will take over from there.
4178/// * Otherwise, the returned expression will be produced in place of
4179/// an ordinary member expression.
4180///
4181/// The ObjCImpDecl bit is a gross hack that will need to be properly
4182/// fixed for ObjC++.
John McCall60d7b3a2010-08-24 06:29:42 +00004183ExprResult
John Wiegley429bb272011-04-08 18:41:53 +00004184Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00004185 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004186 CXXScopeSpec &SS,
John McCalld226f652010-08-21 09:40:31 +00004187 Decl *ObjCImpDecl, bool HasTemplateArgs) {
John Wiegley429bb272011-04-08 18:41:53 +00004188 assert(BaseExpr.get() && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00004189
Steve Naroff3cc4af82007-12-16 21:42:28 +00004190 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00004191 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
Sebastian Redl0eb23302009-01-19 00:08:26 +00004192
John Wiegley429bb272011-04-08 18:41:53 +00004193 if (IsArrow) {
4194 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4195 if (BaseExpr.isInvalid())
4196 return ExprError();
4197 }
4198
4199 QualType BaseType = BaseExpr.get()->getType();
John McCall129e2df2009-11-30 22:42:35 +00004200 assert(!BaseType->isDependentType());
4201
4202 DeclarationName MemberName = R.getLookupName();
4203 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00004204
John McCall028d3972010-12-15 16:46:44 +00004205 // For later type-checking purposes, turn arrow accesses into dot
4206 // accesses. The only access type we support that doesn't follow
4207 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
4208 // and those never use arrows, so this is unaffected.
4209 if (IsArrow) {
4210 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4211 BaseType = Ptr->getPointeeType();
4212 else if (const ObjCObjectPointerType *Ptr
4213 = BaseType->getAs<ObjCObjectPointerType>())
4214 BaseType = Ptr->getPointeeType();
4215 else if (BaseType->isRecordType()) {
4216 // Recover from arrow accesses to records, e.g.:
4217 // struct MyRecord foo;
4218 // foo->bar
4219 // This is actually well-formed in C++ if MyRecord has an
4220 // overloaded operator->, but that should have been dealt with
4221 // by now.
4222 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley429bb272011-04-08 18:41:53 +00004223 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
John McCall028d3972010-12-15 16:46:44 +00004224 << FixItHint::CreateReplacement(OpLoc, ".");
4225 IsArrow = false;
John McCall864c0412011-04-26 20:42:42 +00004226 } else if (BaseType == Context.BoundMemberTy) {
4227 goto fail;
John McCall028d3972010-12-15 16:46:44 +00004228 } else {
4229 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
John Wiegley429bb272011-04-08 18:41:53 +00004230 << BaseType << BaseExpr.get()->getSourceRange();
John McCall028d3972010-12-15 16:46:44 +00004231 return ExprError();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00004232 }
4233 }
4234
John McCall028d3972010-12-15 16:46:44 +00004235 // Handle field access to simple records.
4236 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John Wiegley429bb272011-04-08 18:41:53 +00004237 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
John McCall028d3972010-12-15 16:46:44 +00004238 RTy, OpLoc, SS, HasTemplateArgs))
4239 return ExprError();
4240
4241 // Returning valid-but-null is how we indicate to the caller that
4242 // the lookup result was filled in.
4243 return Owned((Expr*) 0);
David Chisnall0f436562009-08-17 16:35:33 +00004244 }
John McCall129e2df2009-11-30 22:42:35 +00004245
John McCall028d3972010-12-15 16:46:44 +00004246 // Handle ivar access to Objective-C objects.
4247 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004248 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall028d3972010-12-15 16:46:44 +00004249
4250 // There are three cases for the base type:
4251 // - builtin id (qualified or unqualified)
4252 // - builtin Class (qualified or unqualified)
4253 // - an interface
4254 ObjCInterfaceDecl *IDecl = OTy->getInterface();
4255 if (!IDecl) {
John McCallf85e1932011-06-15 23:02:42 +00004256 if (getLangOptions().ObjCAutoRefCount &&
4257 (OTy->isObjCId() || OTy->isObjCClass()))
4258 goto fail;
John McCall028d3972010-12-15 16:46:44 +00004259 // There's an implicit 'isa' ivar on all objects.
4260 // But we only actually find it this way on objects of type 'id',
4261 // apparently.
4262 if (OTy->isObjCId() && Member->isStr("isa"))
John Wiegley429bb272011-04-08 18:41:53 +00004263 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
John McCall028d3972010-12-15 16:46:44 +00004264 Context.getObjCClassType()));
4265
4266 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4267 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4268 ObjCImpDecl, HasTemplateArgs);
4269 goto fail;
4270 }
4271
4272 ObjCInterfaceDecl *ClassDeclared;
4273 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
4274
4275 if (!IV) {
4276 // Attempt to correct for typos in ivar names.
4277 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
4278 LookupMemberName);
4279 if (CorrectTypo(Res, 0, 0, IDecl, false,
4280 IsArrow ? CTC_ObjCIvarLookup
4281 : CTC_ObjCPropertyLookup) &&
4282 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
4283 Diag(R.getNameLoc(),
4284 diag::err_typecheck_member_reference_ivar_suggest)
4285 << IDecl->getDeclName() << MemberName << IV->getDeclName()
4286 << FixItHint::CreateReplacement(R.getNameLoc(),
4287 IV->getNameAsString());
4288 Diag(IV->getLocation(), diag::note_previous_decl)
4289 << IV->getDeclName();
4290 } else {
4291 Res.clear();
4292 Res.setLookupName(Member);
4293
4294 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
4295 << IDecl->getDeclName() << MemberName
John Wiegley429bb272011-04-08 18:41:53 +00004296 << BaseExpr.get()->getSourceRange();
John McCall028d3972010-12-15 16:46:44 +00004297 return ExprError();
4298 }
4299 }
4300
4301 // If the decl being referenced had an error, return an error for this
4302 // sub-expr without emitting another error, in order to avoid cascading
4303 // error cases.
4304 if (IV->isInvalidDecl())
4305 return ExprError();
4306
4307 // Check whether we can reference this field.
4308 if (DiagnoseUseOfDecl(IV, MemberLoc))
4309 return ExprError();
4310 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
4311 IV->getAccessControl() != ObjCIvarDecl::Package) {
4312 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
4313 if (ObjCMethodDecl *MD = getCurMethodDecl())
4314 ClassOfMethodDecl = MD->getClassInterface();
4315 else if (ObjCImpDecl && getCurFunctionDecl()) {
4316 // Case of a c-function declared inside an objc implementation.
4317 // FIXME: For a c-style function nested inside an objc implementation
4318 // class, there is no implementation context available, so we pass
4319 // down the context as argument to this routine. Ideally, this context
4320 // need be passed down in the AST node and somehow calculated from the
4321 // AST for a function decl.
4322 if (ObjCImplementationDecl *IMPD =
4323 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
4324 ClassOfMethodDecl = IMPD->getClassInterface();
4325 else if (ObjCCategoryImplDecl* CatImplClass =
4326 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
4327 ClassOfMethodDecl = CatImplClass->getClassInterface();
4328 }
4329
4330 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
4331 if (ClassDeclared != IDecl ||
4332 ClassOfMethodDecl != ClassDeclared)
4333 Diag(MemberLoc, diag::error_private_ivar_access)
4334 << IV->getDeclName();
4335 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
4336 // @protected
4337 Diag(MemberLoc, diag::error_protected_ivar_access)
4338 << IV->getDeclName();
4339 }
Fariborz Jahanianb1f7d242011-06-16 17:29:56 +00004340 if (getLangOptions().ObjCAutoRefCount) {
4341 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
4342 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
4343 if (UO->getOpcode() == UO_Deref)
4344 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
4345
4346 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
4347 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4348 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
4349 }
John McCall028d3972010-12-15 16:46:44 +00004350
4351 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
John Wiegley429bb272011-04-08 18:41:53 +00004352 MemberLoc, BaseExpr.take(),
John McCall028d3972010-12-15 16:46:44 +00004353 IsArrow));
4354 }
4355
4356 // Objective-C property access.
4357 const ObjCObjectPointerType *OPT;
4358 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
4359 // This actually uses the base as an r-value.
John Wiegley429bb272011-04-08 18:41:53 +00004360 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4361 if (BaseExpr.isInvalid())
4362 return ExprError();
4363
4364 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
John McCall028d3972010-12-15 16:46:44 +00004365
4366 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
4367
4368 const ObjCObjectType *OT = OPT->getObjectType();
4369
4370 // id, with and without qualifiers.
4371 if (OT->isObjCId()) {
4372 // Check protocols on qualified interfaces.
4373 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
4374 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
4375 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
4376 // Check the use of this declaration
4377 if (DiagnoseUseOfDecl(PD, MemberLoc))
4378 return ExprError();
4379
Douglas Gregor926df6c2011-06-11 01:09:30 +00004380 QualType T = PD->getType();
4381 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
4382 T = getMessageSendResultType(BaseType, Getter, false, false);
4383
4384 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCall028d3972010-12-15 16:46:44 +00004385 VK_LValue,
4386 OK_ObjCProperty,
4387 MemberLoc,
John Wiegley429bb272011-04-08 18:41:53 +00004388 BaseExpr.take()));
John McCall028d3972010-12-15 16:46:44 +00004389 }
4390
4391 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
4392 // Check the use of this method.
4393 if (DiagnoseUseOfDecl(OMD, MemberLoc))
4394 return ExprError();
4395 Selector SetterSel =
4396 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4397 PP.getSelectorTable(), Member);
4398 ObjCMethodDecl *SMD = 0;
4399 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
4400 SetterSel, Context))
4401 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Douglas Gregor926df6c2011-06-11 01:09:30 +00004402 QualType PType = getMessageSendResultType(BaseType, OMD, false,
4403 false);
John McCall028d3972010-12-15 16:46:44 +00004404
4405 ExprValueKind VK = VK_LValue;
4406 if (!getLangOptions().CPlusPlus &&
4407 IsCForbiddenLValueType(Context, PType))
4408 VK = VK_RValue;
4409 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4410
4411 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
4412 VK, OK,
John Wiegley429bb272011-04-08 18:41:53 +00004413 MemberLoc, BaseExpr.take()));
John McCall028d3972010-12-15 16:46:44 +00004414 }
4415 }
Fariborz Jahanian4eb7f692011-03-15 17:27:48 +00004416 // Use of id.member can only be for a property reference. Do not
4417 // use the 'id' redefinition in this case.
4418 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
John McCall028d3972010-12-15 16:46:44 +00004419 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4420 ObjCImpDecl, HasTemplateArgs);
4421
4422 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
4423 << MemberName << BaseType);
4424 }
4425
4426 // 'Class', unqualified only.
4427 if (OT->isObjCClass()) {
4428 // Only works in a method declaration (??!).
4429 ObjCMethodDecl *MD = getCurMethodDecl();
4430 if (!MD) {
4431 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4432 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4433 ObjCImpDecl, HasTemplateArgs);
4434
4435 goto fail;
4436 }
4437
4438 // Also must look for a getter name which uses property syntax.
4439 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004440 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4441 ObjCMethodDecl *Getter;
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004442 if ((Getter = IFace->lookupClassMethod(Sel))) {
4443 // Check the use of this method.
4444 if (DiagnoseUseOfDecl(Getter, MemberLoc))
4445 return ExprError();
John McCall028d3972010-12-15 16:46:44 +00004446 } else
Fariborz Jahanian74b27562010-12-03 23:37:08 +00004447 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004448 // If we found a getter then this may be a valid dot-reference, we
4449 // will look for the matching setter, in case it is needed.
4450 Selector SetterSel =
John McCall028d3972010-12-15 16:46:44 +00004451 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4452 PP.getSelectorTable(), Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004453 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
4454 if (!Setter) {
4455 // If this reference is in an @implementation, also check for 'private'
4456 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +00004457 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004458 }
4459 // Look through local category implementations associated with the class.
4460 if (!Setter)
4461 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004462
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004463 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
4464 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004465
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004466 if (Getter || Setter) {
4467 QualType PType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004468
John McCall09431682010-11-18 19:01:18 +00004469 ExprValueKind VK = VK_LValue;
4470 if (Getter) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00004471 PType = getMessageSendResultType(QualType(OT, 0), Getter, true,
4472 false);
John McCall09431682010-11-18 19:01:18 +00004473 if (!getLangOptions().CPlusPlus &&
4474 IsCForbiddenLValueType(Context, PType))
4475 VK = VK_RValue;
4476 } else {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004477 // Get the expression type from Setter's incoming parameter.
4478 PType = (*(Setter->param_end() -1))->getType();
John McCall09431682010-11-18 19:01:18 +00004479 }
4480 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4481
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004482 // FIXME: we must check that the setter has property type.
John McCall12f78a62010-12-02 01:19:52 +00004483 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
4484 PType, VK, OK,
John Wiegley429bb272011-04-08 18:41:53 +00004485 MemberLoc, BaseExpr.take()));
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004486 }
John McCall028d3972010-12-15 16:46:44 +00004487
4488 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4489 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4490 ObjCImpDecl, HasTemplateArgs);
4491
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004492 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall028d3972010-12-15 16:46:44 +00004493 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00004494 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004495
John McCall028d3972010-12-15 16:46:44 +00004496 // Normal property access.
John Wiegley429bb272011-04-08 18:41:53 +00004497 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), MemberName, MemberLoc,
John McCall028d3972010-12-15 16:46:44 +00004498 SourceLocation(), QualType(), false);
Steve Naroff14108da2009-07-10 23:34:53 +00004499 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004500
Chris Lattnerfb173ec2008-07-21 04:28:12 +00004501 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00004502 if (BaseType->isExtVectorType()) {
John McCall5e3c67b2010-12-15 04:42:30 +00004503 // FIXME: this expr should store IsArrow.
Anders Carlsson8f28f992009-08-26 18:25:21 +00004504 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John Wiegley429bb272011-04-08 18:41:53 +00004505 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
John McCall09431682010-11-18 19:01:18 +00004506 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
4507 Member, MemberLoc);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00004508 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004509 return ExprError();
John McCall09431682010-11-18 19:01:18 +00004510
John Wiegley429bb272011-04-08 18:41:53 +00004511 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
John McCall09431682010-11-18 19:01:18 +00004512 *Member, MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00004513 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004514
John McCall028d3972010-12-15 16:46:44 +00004515 // Adjust builtin-sel to the appropriate redefinition type if that's
4516 // not just a pointer to builtin-sel again.
4517 if (IsArrow &&
4518 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
4519 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004520 BaseExpr = ImpCastExprToType(BaseExpr.take(), Context.ObjCSelRedefinitionType,
4521 CK_BitCast);
John McCall028d3972010-12-15 16:46:44 +00004522 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4523 ObjCImpDecl, HasTemplateArgs);
4524 }
4525
4526 // Failure cases.
4527 fail:
4528
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004529 // Recover from dot accesses to pointers, e.g.:
4530 // type *foo;
4531 // foo.bar
4532 // This is actually well-formed in two cases:
4533 // - 'type' is an Objective C type
4534 // - 'bar' is a pseudo-destructor name which happens to refer to
4535 // the appropriate pointer type
John McCall028d3972010-12-15 16:46:44 +00004536 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004537 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
4538 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
John McCall028d3972010-12-15 16:46:44 +00004539 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley429bb272011-04-08 18:41:53 +00004540 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004541 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall028d3972010-12-15 16:46:44 +00004542
4543 // Recurse as an -> access.
4544 IsArrow = true;
4545 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4546 ObjCImpDecl, HasTemplateArgs);
4547 }
John McCall028d3972010-12-15 16:46:44 +00004548 }
4549
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004550 // If the user is trying to apply -> or . to a function name, it's probably
4551 // because they forgot parentheses to call that function.
Matt Beaumont-Gayc9366ba2011-05-04 22:10:40 +00004552 QualType ZeroArgCallTy;
4553 UnresolvedSet<4> Overloads;
4554 if (isExprCallable(*BaseExpr.get(), ZeroArgCallTy, Overloads)) {
4555 if (ZeroArgCallTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +00004556 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gayc9366ba2011-05-04 22:10:40 +00004557 << (Overloads.size() > 1) << 0 << BaseExpr.get()->getSourceRange();
4558 UnresolvedSet<2> PlausibleOverloads;
4559 for (OverloadExpr::decls_iterator It = Overloads.begin(),
4560 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
4561 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
4562 QualType OverloadResultTy = OverloadDecl->getResultType();
4563 if ((!IsArrow && OverloadResultTy->isRecordType()) ||
4564 (IsArrow && OverloadResultTy->isPointerType() &&
4565 OverloadResultTy->getPointeeType()->isRecordType()))
4566 PlausibleOverloads.addDecl(It.getDecl());
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004567 }
Matt Beaumont-Gayc9366ba2011-05-04 22:10:40 +00004568 NoteOverloads(PlausibleOverloads, BaseExpr.get()->getExprLoc());
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004569 return ExprError();
4570 }
Matt Beaumont-Gayc9366ba2011-05-04 22:10:40 +00004571 if ((!IsArrow && ZeroArgCallTy->isRecordType()) ||
4572 (IsArrow && ZeroArgCallTy->isPointerType() &&
4573 ZeroArgCallTy->getPointeeType()->isRecordType())) {
4574 // At this point, we know BaseExpr looks like it's potentially callable
4575 // with 0 arguments, and that it returns something of a reasonable type,
4576 // so we can emit a fixit and carry on pretending that BaseExpr was
4577 // actually a CallExpr.
4578 SourceLocation ParenInsertionLoc =
4579 PP.getLocForEndOfToken(BaseExpr.get()->getLocEnd());
4580 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
4581 << (Overloads.size() > 1) << 1 << BaseExpr.get()->getSourceRange()
4582 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4583 // FIXME: Try this before emitting the fixit, and suppress diagnostics
4584 // while doing so.
4585 ExprResult NewBase =
4586 ActOnCallExpr(0, BaseExpr.take(), ParenInsertionLoc,
4587 MultiExprArg(*this, 0, 0),
4588 ParenInsertionLoc.getFileLocWithOffset(1));
4589 if (NewBase.isInvalid())
4590 return ExprError();
4591 BaseExpr = NewBase;
4592 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
4593 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4594 ObjCImpDecl, HasTemplateArgs);
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004595 }
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004596 }
4597
Douglas Gregor214f31a2009-03-27 06:00:30 +00004598 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
John Wiegley429bb272011-04-08 18:41:53 +00004599 << BaseType << BaseExpr.get()->getSourceRange();
Douglas Gregor214f31a2009-03-27 06:00:30 +00004600
Douglas Gregor214f31a2009-03-27 06:00:30 +00004601 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00004602}
4603
John McCall129e2df2009-11-30 22:42:35 +00004604/// The main callback when the parser finds something like
4605/// expression . [nested-name-specifier] identifier
4606/// expression -> [nested-name-specifier] identifier
4607/// where 'identifier' encompasses a fairly broad spectrum of
4608/// possibilities, including destructor and operator references.
4609///
4610/// \param OpKind either tok::arrow or tok::period
4611/// \param HasTrailingLParen whether the next token is '(', which
4612/// is used to diagnose mis-uses of special members that can
4613/// only be called
4614/// \param ObjCImpDecl the current ObjC @implementation decl;
4615/// this is an ugly hack around the fact that ObjC @implementations
4616/// aren't properly put in the context chain
John McCall60d7b3a2010-08-24 06:29:42 +00004617ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall5e3c67b2010-12-15 04:42:30 +00004618 SourceLocation OpLoc,
4619 tok::TokenKind OpKind,
4620 CXXScopeSpec &SS,
4621 UnqualifiedId &Id,
4622 Decl *ObjCImpDecl,
4623 bool HasTrailingLParen) {
John McCall129e2df2009-11-30 22:42:35 +00004624 if (SS.isSet() && SS.isInvalid())
4625 return ExprError();
4626
Francois Pichetdbee3412011-01-18 05:04:39 +00004627 // Warn about the explicit constructor calls Microsoft extension.
4628 if (getLangOptions().Microsoft &&
4629 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4630 Diag(Id.getSourceRange().getBegin(),
4631 diag::ext_ms_explicit_constructor_call);
4632
John McCall129e2df2009-11-30 22:42:35 +00004633 TemplateArgumentListInfo TemplateArgsBuffer;
4634
4635 // Decompose the name into its component parts.
Abramo Bagnara25777432010-08-11 22:01:17 +00004636 DeclarationNameInfo NameInfo;
John McCall129e2df2009-11-30 22:42:35 +00004637 const TemplateArgumentListInfo *TemplateArgs;
4638 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00004639 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004640
Abramo Bagnara25777432010-08-11 22:01:17 +00004641 DeclarationName Name = NameInfo.getName();
John McCall129e2df2009-11-30 22:42:35 +00004642 bool IsArrow = (OpKind == tok::arrow);
4643
4644 NamedDecl *FirstQualifierInScope
4645 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4646 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4647
4648 // This is a postfix expression, so get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004649 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004650 if (Result.isInvalid()) return ExprError();
4651 Base = Result.take();
John McCall129e2df2009-11-30 22:42:35 +00004652
Douglas Gregor01e56ae2010-04-12 20:54:26 +00004653 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4654 isDependentScopeSpecifier(SS)) {
John McCall9ae2f072010-08-23 23:25:46 +00004655 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00004656 IsArrow, OpLoc,
4657 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00004658 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004659 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00004660 LookupResult R(*this, NameInfo, LookupMemberName);
John Wiegley429bb272011-04-08 18:41:53 +00004661 ExprResult BaseResult = Owned(Base);
4662 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCallad00b772010-06-16 08:42:20 +00004663 SS, ObjCImpDecl, TemplateArgs != 0);
John Wiegley429bb272011-04-08 18:41:53 +00004664 if (BaseResult.isInvalid())
4665 return ExprError();
4666 Base = BaseResult.take();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004667
John McCallad00b772010-06-16 08:42:20 +00004668 if (Result.isInvalid()) {
4669 Owned(Base);
4670 return ExprError();
4671 }
John McCall129e2df2009-11-30 22:42:35 +00004672
John McCallad00b772010-06-16 08:42:20 +00004673 if (Result.get()) {
4674 // The only way a reference to a destructor can be used is to
4675 // immediately call it, which falls into this case. If the
4676 // next token is not a '(', produce a diagnostic and build the
4677 // call now.
4678 if (!HasTrailingLParen &&
4679 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCall9ae2f072010-08-23 23:25:46 +00004680 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall129e2df2009-11-30 22:42:35 +00004681
John McCallad00b772010-06-16 08:42:20 +00004682 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00004683 }
4684
John McCall9ae2f072010-08-23 23:25:46 +00004685 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCallc2233c52010-01-15 08:34:02 +00004686 OpLoc, IsArrow, SS, FirstQualifierInScope,
4687 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004688 }
4689
4690 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00004691}
4692
John McCall60d7b3a2010-08-24 06:29:42 +00004693ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00004694 FunctionDecl *FD,
4695 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00004696 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004697 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00004698 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00004699 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00004700 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00004701 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004702 return ExprError();
4703 }
4704
4705 if (Param->hasUninstantiatedDefaultArg()) {
4706 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00004707
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004708 // Instantiate the expression.
4709 MultiLevelTemplateArgumentList ArgList
4710 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00004711
Nico Weber08e41a62010-11-29 18:19:25 +00004712 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004713 = ArgList.getInnermost();
4714 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4715 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004716
Nico Weber08e41a62010-11-29 18:19:25 +00004717 ExprResult Result;
4718 {
4719 // C++ [dcl.fct.default]p5:
4720 // The names in the [default argument] expression are bound, and
4721 // the semantic constraints are checked, at the point where the
4722 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00004723 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00004724 Result = SubstExpr(UninstExpr, ArgList);
4725 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004726 if (Result.isInvalid())
4727 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004728
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004729 // Check the expression as an initializer for the parameter.
4730 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004731 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004732 InitializationKind Kind
4733 = InitializationKind::CreateCopy(Param->getLocation(),
4734 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4735 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00004736
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004737 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4738 Result = InitSeq.Perform(*this, Entity, Kind,
4739 MultiExprArg(*this, &ResultE, 1));
4740 if (Result.isInvalid())
4741 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004742
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004743 // Build the default argument expression.
4744 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4745 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004746 }
4747
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004748 // If the default expression creates temporaries, we need to
4749 // push them to the current stack of expression temporaries so they'll
4750 // be properly destroyed.
4751 // FIXME: We should really be rebuilding the default argument with new
4752 // bound temporaries; see the comment in PR5810.
Douglas Gregor5833b0b2010-09-14 22:55:20 +00004753 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4754 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4755 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4756 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4757 ExprTemporaries.push_back(Temporary);
John McCallf85e1932011-06-15 23:02:42 +00004758 ExprNeedsCleanups = true;
Douglas Gregor5833b0b2010-09-14 22:55:20 +00004759 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004760
4761 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00004762 // Just mark all of the declarations in this potentially-evaluated expression
4763 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004764 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00004765 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004766}
4767
Douglas Gregor88a35142008-12-22 05:46:06 +00004768/// ConvertArgumentsForCall - Converts the arguments specified in
4769/// Args/NumArgs to the parameter types of the function FDecl with
4770/// function prototype Proto. Call is the call expression itself, and
4771/// Fn is the function expression. For a C++ member function, this
4772/// routine does not attempt to convert the object argument. Returns
4773/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004774bool
4775Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00004776 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00004777 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00004778 Expr **Args, unsigned NumArgs,
4779 SourceLocation RParenLoc) {
John McCall8e10f3b2011-02-26 05:39:39 +00004780 // Bail out early if calling a builtin with custom typechecking.
4781 // We don't need to do this in the
4782 if (FDecl)
4783 if (unsigned ID = FDecl->getBuiltinID())
4784 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4785 return false;
4786
Mike Stumpeed9cac2009-02-19 03:04:26 +00004787 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00004788 // assignment, to the types of the corresponding parameter, ...
4789 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004790 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004791
Douglas Gregor88a35142008-12-22 05:46:06 +00004792 // If too few arguments are available (and we don't have default
4793 // arguments for the remaining parameters), don't make the call.
4794 if (NumArgs < NumArgsInProto) {
4795 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4796 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004797 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00004798 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00004799 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00004800 }
4801
4802 // If too many are passed and not variadic, error on the extras and drop
4803 // them.
4804 if (NumArgs > NumArgsInProto) {
4805 if (!Proto->isVariadic()) {
4806 Diag(Args[NumArgsInProto]->getLocStart(),
4807 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004808 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00004809 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00004810 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4811 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00004812
4813 // Emit the location of the prototype.
4814 if (FDecl && !FDecl->getBuiltinID())
4815 Diag(FDecl->getLocStart(),
4816 diag::note_typecheck_call_too_many_args)
4817 << FDecl;
4818
Douglas Gregor88a35142008-12-22 05:46:06 +00004819 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004820 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004821 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004822 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004823 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004824 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004825 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004826 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4827 if (Fn->getType()->isBlockPointerType())
4828 CallType = VariadicBlock; // Block
4829 else if (isa<MemberExpr>(Fn))
4830 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004831 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004832 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004833 if (Invalid)
4834 return true;
4835 unsigned TotalNumArgs = AllArgs.size();
4836 for (unsigned i = 0; i < TotalNumArgs; ++i)
4837 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004838
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004839 return false;
4840}
Mike Stumpeed9cac2009-02-19 03:04:26 +00004841
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004842bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4843 FunctionDecl *FDecl,
4844 const FunctionProtoType *Proto,
4845 unsigned FirstProtoArg,
4846 Expr **Args, unsigned NumArgs,
4847 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004848 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004849 unsigned NumArgsInProto = Proto->getNumArgs();
4850 unsigned NumArgsToCheck = NumArgs;
4851 bool Invalid = false;
4852 if (NumArgs != NumArgsInProto)
4853 // Use default arguments for missing arguments
4854 NumArgsToCheck = NumArgsInProto;
4855 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00004856 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004857 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004858 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004859
Douglas Gregor88a35142008-12-22 05:46:06 +00004860 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004861 if (ArgIx < NumArgs) {
4862 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004863
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004864 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4865 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00004866 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004867 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004868 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004869
Douglas Gregora188ff22009-12-22 16:09:06 +00004870 // Pass the argument
4871 ParmVarDecl *Param = 0;
4872 if (FDecl && i < FDecl->getNumParams())
4873 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00004874
Douglas Gregora188ff22009-12-22 16:09:06 +00004875 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004876 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00004877 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
4878 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00004879 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00004880 SourceLocation(),
4881 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00004882 if (ArgE.isInvalid())
4883 return true;
4884
4885 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004886 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00004887 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004888
John McCall60d7b3a2010-08-24 06:29:42 +00004889 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004890 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004891 if (ArgExpr.isInvalid())
4892 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004893
Anders Carlsson56c5e332009-08-25 03:49:14 +00004894 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004895 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004896 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00004897 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004898
Douglas Gregor88a35142008-12-22 05:46:06 +00004899 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004900 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00004901
4902 // Assume that extern "C" functions with variadic arguments that
4903 // return __unknown_anytype aren't *really* variadic.
4904 if (Proto->getResultType() == Context.UnknownAnyTy &&
4905 FDecl && FDecl->isExternC()) {
4906 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4907 ExprResult arg;
4908 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
4909 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
4910 else
4911 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4912 Invalid |= arg.isInvalid();
4913 AllArgs.push_back(arg.take());
4914 }
4915
4916 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4917 } else {
4918 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4919 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4920 Invalid |= Arg.isInvalid();
4921 AllArgs.push_back(Arg.take());
4922 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004923 }
4924 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004925 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00004926}
4927
John McCall755d8492011-04-12 00:42:48 +00004928/// Given a function expression of unknown-any type, try to rebuild it
4929/// to have a function type.
4930static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4931
Steve Narofff69936d2007-09-16 03:34:24 +00004932/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00004933/// This provides the location of the left/right parens and a list of comma
4934/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00004935ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004936Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004937 MultiExprArg args, SourceLocation RParenLoc,
4938 Expr *ExecConfig) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00004939 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00004940
4941 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004942 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00004943 if (Result.isInvalid()) return ExprError();
4944 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00004945
John McCall9ae2f072010-08-23 23:25:46 +00004946 Expr **Args = args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004947
Douglas Gregor88a35142008-12-22 05:46:06 +00004948 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00004949 // If this is a pseudo-destructor expression, build the call immediately.
4950 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4951 if (NumArgs > 0) {
4952 // Pseudo-destructor calls should not have any arguments.
4953 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00004954 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00004955 SourceRange(Args[0]->getLocStart(),
4956 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00004957
Douglas Gregora71d8192009-09-04 17:36:40 +00004958 NumArgs = 0;
4959 }
Mike Stump1eb44332009-09-09 15:08:12 +00004960
Douglas Gregora71d8192009-09-04 17:36:40 +00004961 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00004962 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00004963 }
Mike Stump1eb44332009-09-09 15:08:12 +00004964
Douglas Gregor17330012009-02-04 15:01:18 +00004965 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00004966 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00004967 // FIXME: Will need to cache the results of name lookup (including ADL) in
4968 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00004969 bool Dependent = false;
4970 if (Fn->isTypeDependent())
4971 Dependent = true;
4972 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4973 Dependent = true;
4974
Peter Collingbournee08ce652011-02-09 21:07:24 +00004975 if (Dependent) {
4976 if (ExecConfig) {
4977 return Owned(new (Context) CUDAKernelCallExpr(
4978 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4979 Context.DependentTy, VK_RValue, RParenLoc));
4980 } else {
4981 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4982 Context.DependentTy, VK_RValue,
4983 RParenLoc));
4984 }
4985 }
Douglas Gregor17330012009-02-04 15:01:18 +00004986
4987 // Determine whether this is a call to an object (C++ [over.call.object]).
4988 if (Fn->getType()->isRecordType())
4989 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004990 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00004991
John McCall755d8492011-04-12 00:42:48 +00004992 if (Fn->getType() == Context.UnknownAnyTy) {
4993 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4994 if (result.isInvalid()) return ExprError();
4995 Fn = result.take();
4996 }
4997
John McCall864c0412011-04-26 20:42:42 +00004998 if (Fn->getType() == Context.BoundMemberTy) {
John McCallaa81e162009-12-01 22:10:20 +00004999 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00005000 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00005001 }
John McCall864c0412011-04-26 20:42:42 +00005002 }
John McCall129e2df2009-11-30 22:42:35 +00005003
John McCall864c0412011-04-26 20:42:42 +00005004 // Check for overloaded calls. This can happen even in C due to extensions.
5005 if (Fn->getType() == Context.OverloadTy) {
5006 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5007
5008 // We aren't supposed to apply this logic if there's an '&' involved.
5009 if (!find.IsAddressOfOperand) {
5010 OverloadExpr *ovl = find.Expression;
5011 if (isa<UnresolvedLookupExpr>(ovl)) {
5012 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
5013 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
5014 RParenLoc, ExecConfig);
5015 } else {
John McCallaa81e162009-12-01 22:10:20 +00005016 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00005017 RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00005018 }
5019 }
Douglas Gregor88a35142008-12-22 05:46:06 +00005020 }
5021
Douglas Gregorfa047642009-02-04 00:32:51 +00005022 // If we're directly calling a function, get the appropriate declaration.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005023
Eli Friedmanefa42f72009-12-26 03:35:45 +00005024 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00005025
John McCall3b4294e2009-12-16 12:17:52 +00005026 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00005027 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
5028 if (UnOp->getOpcode() == UO_AddrOf)
5029 NakedFn = UnOp->getSubExpr()->IgnoreParens();
5030
John McCall3b4294e2009-12-16 12:17:52 +00005031 if (isa<DeclRefExpr>(NakedFn))
5032 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00005033 else if (isa<MemberExpr>(NakedFn))
5034 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00005035
Peter Collingbournee08ce652011-02-09 21:07:24 +00005036 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
5037 ExecConfig);
5038}
5039
5040ExprResult
5041Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
5042 MultiExprArg execConfig, SourceLocation GGGLoc) {
5043 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
5044 if (!ConfigDecl)
5045 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
5046 << "cudaConfigureCall");
5047 QualType ConfigQTy = ConfigDecl->getType();
5048
5049 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
5050 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
5051
5052 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCallaa81e162009-12-01 22:10:20 +00005053}
5054
Tanya Lattner61eee0c2011-06-04 00:47:47 +00005055/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5056///
5057/// __builtin_astype( value, dst type )
5058///
5059ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty,
5060 SourceLocation BuiltinLoc,
5061 SourceLocation RParenLoc) {
5062 ExprValueKind VK = VK_RValue;
5063 ExprObjectKind OK = OK_Ordinary;
5064 QualType DstTy = GetTypeFromParser(destty);
5065 QualType SrcTy = expr->getType();
5066 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5067 return ExprError(Diag(BuiltinLoc,
5068 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00005069 << DstTy
5070 << SrcTy
Tanya Lattner61eee0c2011-06-04 00:47:47 +00005071 << expr->getSourceRange());
5072 return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc, RParenLoc));
5073}
5074
John McCall3b4294e2009-12-16 12:17:52 +00005075/// BuildResolvedCallExpr - Build a call to a resolved expression,
5076/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00005077/// unary-convert to an expression of function-pointer or
5078/// block-pointer type.
5079///
5080/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00005081ExprResult
John McCallaa81e162009-12-01 22:10:20 +00005082Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5083 SourceLocation LParenLoc,
5084 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00005085 SourceLocation RParenLoc,
5086 Expr *Config) {
John McCallaa81e162009-12-01 22:10:20 +00005087 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5088
Chris Lattner04421082008-04-08 04:40:51 +00005089 // Promote the function operand.
John Wiegley429bb272011-04-08 18:41:53 +00005090 ExprResult Result = UsualUnaryConversions(Fn);
5091 if (Result.isInvalid())
5092 return ExprError();
5093 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00005094
Chris Lattner925e60d2007-12-28 05:29:59 +00005095 // Make the call expr early, before semantic checks. This guarantees cleanup
5096 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00005097 CallExpr *TheCall;
5098 if (Config) {
5099 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5100 cast<CallExpr>(Config),
5101 Args, NumArgs,
5102 Context.BoolTy,
5103 VK_RValue,
5104 RParenLoc);
5105 } else {
5106 TheCall = new (Context) CallExpr(Context, Fn,
5107 Args, NumArgs,
5108 Context.BoolTy,
5109 VK_RValue,
5110 RParenLoc);
5111 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00005112
John McCall8e10f3b2011-02-26 05:39:39 +00005113 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5114
5115 // Bail out early if calling a builtin with custom typechecking.
5116 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5117 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
5118
John McCall1de4d4e2011-04-07 08:22:57 +00005119 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00005120 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00005121 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00005122 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5123 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00005124 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00005125 if (FuncT == 0)
5126 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5127 << Fn->getType() << Fn->getSourceRange());
5128 } else if (const BlockPointerType *BPT =
5129 Fn->getType()->getAs<BlockPointerType>()) {
5130 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5131 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00005132 // Handle calls to expressions of unknown-any type.
5133 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00005134 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00005135 if (rewrite.isInvalid()) return ExprError();
5136 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00005137 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00005138 goto retry;
5139 }
5140
Sebastian Redl0eb23302009-01-19 00:08:26 +00005141 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5142 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00005143 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00005144
Peter Collingbourne0423fc62011-02-23 01:53:29 +00005145 if (getLangOptions().CUDA) {
5146 if (Config) {
5147 // CUDA: Kernel calls must be to global functions
5148 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5149 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5150 << FDecl->getName() << Fn->getSourceRange());
5151
5152 // CUDA: Kernel function must have 'void' return type
5153 if (!FuncT->getResultType()->isVoidType())
5154 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5155 << Fn->getType() << Fn->getSourceRange());
5156 }
5157 }
5158
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00005159 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005160 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00005161 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00005162 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00005163 return ExprError();
5164
Chris Lattner925e60d2007-12-28 05:29:59 +00005165 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00005166 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00005167 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00005168
Douglas Gregor72564e72009-02-26 23:50:07 +00005169 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00005170 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00005171 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00005172 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00005173 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00005174 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00005175
Douglas Gregor74734d52009-04-02 15:37:10 +00005176 if (FDecl) {
5177 // Check if we have too few/too many template arguments, based
5178 // on our knowledge of the function definition.
5179 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00005180 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00005181 const FunctionProtoType *Proto
5182 = Def->getType()->getAs<FunctionProtoType>();
5183 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00005184 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5185 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00005186 }
Douglas Gregor46542412010-10-25 20:39:23 +00005187
5188 // If the function we're calling isn't a function prototype, but we have
5189 // a function prototype from a prior declaratiom, use that prototype.
5190 if (!FDecl->hasPrototype())
5191 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00005192 }
5193
Steve Naroffb291ab62007-08-28 23:30:39 +00005194 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00005195 for (unsigned i = 0; i != NumArgs; i++) {
5196 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00005197
5198 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00005199 InitializedEntity Entity
5200 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00005201 Proto->getArgType(i),
5202 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00005203 ExprResult ArgE = PerformCopyInitialization(Entity,
5204 SourceLocation(),
5205 Owned(Arg));
5206 if (ArgE.isInvalid())
5207 return true;
5208
5209 Arg = ArgE.takeAs<Expr>();
5210
5211 } else {
John Wiegley429bb272011-04-08 18:41:53 +00005212 ExprResult ArgE = DefaultArgumentPromotion(Arg);
5213
5214 if (ArgE.isInvalid())
5215 return true;
5216
5217 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00005218 }
5219
Douglas Gregor0700bbf2010-10-26 05:45:40 +00005220 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
5221 Arg->getType(),
5222 PDiag(diag::err_call_incomplete_argument)
5223 << Arg->getSourceRange()))
5224 return ExprError();
5225
Chris Lattner925e60d2007-12-28 05:29:59 +00005226 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00005227 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005228 }
Chris Lattner925e60d2007-12-28 05:29:59 +00005229
Douglas Gregor88a35142008-12-22 05:46:06 +00005230 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5231 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00005232 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5233 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00005234
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00005235 // Check for sentinels
5236 if (NDecl)
5237 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00005238
Chris Lattner59907c42007-08-10 20:18:51 +00005239 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00005240 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00005241 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00005242 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00005243
John McCall8e10f3b2011-02-26 05:39:39 +00005244 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00005245 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00005246 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00005247 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00005248 return ExprError();
5249 }
Chris Lattner59907c42007-08-10 20:18:51 +00005250
John McCall9ae2f072010-08-23 23:25:46 +00005251 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00005252}
5253
John McCall60d7b3a2010-08-24 06:29:42 +00005254ExprResult
John McCallb3d87482010-08-24 05:47:05 +00005255Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005256 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00005257 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00005258 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00005259 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00005260
5261 TypeSourceInfo *TInfo;
5262 QualType literalType = GetTypeFromParser(Ty, &TInfo);
5263 if (!TInfo)
5264 TInfo = Context.getTrivialTypeSourceInfo(literalType);
5265
John McCall9ae2f072010-08-23 23:25:46 +00005266 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00005267}
5268
John McCall60d7b3a2010-08-24 06:29:42 +00005269ExprResult
John McCall42f56b52010-01-18 19:35:47 +00005270Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCall9ae2f072010-08-23 23:25:46 +00005271 SourceLocation RParenLoc, Expr *literalExpr) {
John McCall42f56b52010-01-18 19:35:47 +00005272 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00005273
Eli Friedman6223c222008-05-20 05:22:08 +00005274 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00005275 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5276 PDiag(diag::err_illegal_decl_array_incomplete_type)
5277 << SourceRange(LParenLoc,
5278 literalExpr->getSourceRange().getEnd())))
5279 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00005280 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005281 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5282 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00005283 } else if (!literalType->isDependentType() &&
5284 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00005285 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005286 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00005287 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005288 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00005289
Douglas Gregor99a2e602009-12-16 01:38:02 +00005290 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00005291 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00005292 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00005293 = InitializationKind::CreateCStyleCast(LParenLoc,
5294 SourceRange(LParenLoc, RParenLoc));
Eli Friedman08544622009-12-22 02:35:53 +00005295 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00005296 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00005297 MultiExprArg(*this, &literalExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00005298 &literalType);
5299 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005300 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00005301 literalExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00005302
Chris Lattner371f2582008-12-04 23:50:19 +00005303 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00005304 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00005305 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005306 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00005307 }
Eli Friedman08544622009-12-22 02:35:53 +00005308
John McCallf89e55a2010-11-18 06:31:45 +00005309 // In C, compound literals are l-values for some reason.
5310 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
5311
Douglas Gregor751ec9b2011-06-17 04:59:12 +00005312 return MaybeBindToTemporary(
5313 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5314 VK, literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00005315}
5316
John McCall60d7b3a2010-08-24 06:29:42 +00005317ExprResult
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005318Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005319 SourceLocation RBraceLoc) {
5320 unsigned NumInit = initlist.size();
John McCall9ae2f072010-08-23 23:25:46 +00005321 Expr **InitList = initlist.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00005322
Steve Naroff08d92e42007-09-15 18:49:24 +00005323 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00005324 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005325
Ted Kremenek709210f2010-04-13 23:39:13 +00005326 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
5327 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00005328 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005329 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00005330}
5331
John McCallf3ea8cf2010-11-14 08:17:51 +00005332/// Prepares for a scalar cast, performing all the necessary stages
5333/// except the final cast and returning the kind required.
John Wiegley429bb272011-04-08 18:41:53 +00005334static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00005335 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5336 // Also, callers should have filtered out the invalid cases with
5337 // pointers. Everything else should be possible.
5338
John Wiegley429bb272011-04-08 18:41:53 +00005339 QualType SrcTy = Src.get()->getType();
John McCallf3ea8cf2010-11-14 08:17:51 +00005340 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00005341 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00005342
John McCalldaa8e4e2010-11-15 09:13:47 +00005343 switch (SrcTy->getScalarTypeKind()) {
5344 case Type::STK_MemberPointer:
5345 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00005346
John McCalldaa8e4e2010-11-15 09:13:47 +00005347 case Type::STK_Pointer:
5348 switch (DestTy->getScalarTypeKind()) {
5349 case Type::STK_Pointer:
5350 return DestTy->isObjCObjectPointerType() ?
John McCallf3ea8cf2010-11-14 08:17:51 +00005351 CK_AnyPointerToObjCPointerCast :
5352 CK_BitCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005353 case Type::STK_Bool:
5354 return CK_PointerToBoolean;
5355 case Type::STK_Integral:
5356 return CK_PointerToIntegral;
5357 case Type::STK_Floating:
5358 case Type::STK_FloatingComplex:
5359 case Type::STK_IntegralComplex:
5360 case Type::STK_MemberPointer:
5361 llvm_unreachable("illegal cast from pointer");
5362 }
5363 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005364
John McCalldaa8e4e2010-11-15 09:13:47 +00005365 case Type::STK_Bool: // casting from bool is like casting from an integer
5366 case Type::STK_Integral:
5367 switch (DestTy->getScalarTypeKind()) {
5368 case Type::STK_Pointer:
John Wiegley429bb272011-04-08 18:41:53 +00005369 if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00005370 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00005371 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005372 case Type::STK_Bool:
5373 return CK_IntegralToBoolean;
5374 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00005375 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005376 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00005377 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00005378 case Type::STK_IntegralComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005379 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5380 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00005381 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005382 case Type::STK_FloatingComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005383 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5384 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00005385 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005386 case Type::STK_MemberPointer:
5387 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005388 }
5389 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005390
John McCalldaa8e4e2010-11-15 09:13:47 +00005391 case Type::STK_Floating:
5392 switch (DestTy->getScalarTypeKind()) {
5393 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00005394 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005395 case Type::STK_Bool:
5396 return CK_FloatingToBoolean;
5397 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00005398 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00005399 case Type::STK_FloatingComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005400 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5401 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00005402 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005403 case Type::STK_IntegralComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005404 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5405 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00005406 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005407 case Type::STK_Pointer:
5408 llvm_unreachable("valid float->pointer cast?");
5409 case Type::STK_MemberPointer:
5410 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005411 }
5412 break;
5413
John McCalldaa8e4e2010-11-15 09:13:47 +00005414 case Type::STK_FloatingComplex:
5415 switch (DestTy->getScalarTypeKind()) {
5416 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005417 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005418 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005419 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00005420 case Type::STK_Floating: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00005421 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005422 if (S.Context.hasSameType(ET, DestTy))
5423 return CK_FloatingComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00005424 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00005425 return CK_FloatingCast;
5426 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005427 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00005428 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00005429 case Type::STK_Integral:
John Wiegley429bb272011-04-08 18:41:53 +00005430 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5431 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00005432 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00005433 case Type::STK_Pointer:
5434 llvm_unreachable("valid complex float->pointer cast?");
5435 case Type::STK_MemberPointer:
5436 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005437 }
5438 break;
5439
John McCalldaa8e4e2010-11-15 09:13:47 +00005440 case Type::STK_IntegralComplex:
5441 switch (DestTy->getScalarTypeKind()) {
5442 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005443 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005444 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005445 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00005446 case Type::STK_Integral: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00005447 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005448 if (S.Context.hasSameType(ET, DestTy))
5449 return CK_IntegralComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00005450 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00005451 return CK_IntegralCast;
5452 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005453 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00005454 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00005455 case Type::STK_Floating:
John Wiegley429bb272011-04-08 18:41:53 +00005456 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5457 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00005458 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00005459 case Type::STK_Pointer:
5460 llvm_unreachable("valid complex int->pointer cast?");
5461 case Type::STK_MemberPointer:
5462 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005463 }
5464 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00005465 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005466
John McCallf3ea8cf2010-11-14 08:17:51 +00005467 llvm_unreachable("Unhandled scalar cast");
5468 return CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00005469}
5470
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005471/// CheckCastTypes - Check type constraints for casting between types.
John McCallf85e1932011-06-15 23:02:42 +00005472ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyR,
5473 QualType castType, Expr *castExpr,
5474 CastKind& Kind, ExprValueKind &VK,
John Wiegley429bb272011-04-08 18:41:53 +00005475 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall1de4d4e2011-04-07 08:22:57 +00005476 if (castExpr->getType() == Context.UnknownAnyTy)
5477 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
5478
Sebastian Redl9cc11e72009-07-25 15:41:38 +00005479 if (getLangOptions().CPlusPlus)
John McCallf85e1932011-06-15 23:02:42 +00005480 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Douglas Gregor40749ee2010-11-03 00:35:38 +00005481 castExpr->getLocEnd()),
John McCallf89e55a2010-11-18 06:31:45 +00005482 castType, VK, castExpr, Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005483 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00005484
John McCallfb8721c2011-04-10 19:13:55 +00005485 assert(!castExpr->getType()->isPlaceholderType());
5486
John McCallf89e55a2010-11-18 06:31:45 +00005487 // We only support r-value casts in C.
5488 VK = VK_RValue;
5489
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005490 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
5491 // type needs to be scalar.
5492 if (castType->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +00005493 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley429bb272011-04-08 18:41:53 +00005494 ExprResult castExprRes = IgnoredValueConversions(castExpr);
5495 if (castExprRes.isInvalid())
5496 return ExprError();
5497 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00005498
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005499 // Cast to void allows any expr type.
John McCall2de56d12010-08-25 11:45:40 +00005500 Kind = CK_ToVoid;
John Wiegley429bb272011-04-08 18:41:53 +00005501 return Owned(castExpr);
Anders Carlssonebeaf202009-10-16 02:35:04 +00005502 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005503
John Wiegley429bb272011-04-08 18:41:53 +00005504 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
5505 if (castExprRes.isInvalid())
5506 return ExprError();
5507 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00005508
Eli Friedman8d438082010-07-17 20:43:49 +00005509 if (RequireCompleteType(TyR.getBegin(), castType,
5510 diag::err_typecheck_cast_to_incomplete))
John Wiegley429bb272011-04-08 18:41:53 +00005511 return ExprError();
Eli Friedman8d438082010-07-17 20:43:49 +00005512
Anders Carlssonebeaf202009-10-16 02:35:04 +00005513 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00005514 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005515 (castType->isStructureType() || castType->isUnionType())) {
5516 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005517 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005518 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
5519 << castType << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005520 Kind = CK_NoOp;
John Wiegley429bb272011-04-08 18:41:53 +00005521 return Owned(castExpr);
Anders Carlssonc3516322009-10-16 02:48:28 +00005522 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005523
Anders Carlssonc3516322009-10-16 02:48:28 +00005524 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005525 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00005526 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005527 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005528 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005529 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005530 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara8c4bfe52010-10-07 21:20:44 +00005531 castExpr->getType()) &&
5532 !Field->isUnnamedBitfield()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005533 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5534 << castExpr->getSourceRange();
5535 break;
5536 }
5537 }
John Wiegley429bb272011-04-08 18:41:53 +00005538 if (Field == FieldEnd) {
5539 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005540 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005541 return ExprError();
5542 }
John McCall2de56d12010-08-25 11:45:40 +00005543 Kind = CK_ToUnion;
John Wiegley429bb272011-04-08 18:41:53 +00005544 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005545 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005546
Anders Carlssonc3516322009-10-16 02:48:28 +00005547 // Reject any other conversions to non-scalar types.
John Wiegley429bb272011-04-08 18:41:53 +00005548 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlssonc3516322009-10-16 02:48:28 +00005549 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005550 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00005551 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005552
John McCallf3ea8cf2010-11-14 08:17:51 +00005553 // The type we're casting to is known to be a scalar or vector.
5554
5555 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005556 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00005557 !castExpr->getType()->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005558 Diag(castExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005559 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00005560 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005561 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00005562 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005563
5564 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00005565 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005566
Anton Yartsevd06fea82011-03-27 09:32:40 +00005567 if (castType->isVectorType()) {
5568 if (castType->getAs<VectorType>()->getVectorKind() ==
5569 VectorType::AltiVecVector &&
5570 (castExpr->getType()->isIntegerType() ||
5571 castExpr->getType()->isFloatingType())) {
5572 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00005573 return Owned(castExpr);
5574 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
5575 return ExprError();
Anton Yartsevd06fea82011-03-27 09:32:40 +00005576 } else
John Wiegley429bb272011-04-08 18:41:53 +00005577 return Owned(castExpr);
Anton Yartsevd06fea82011-03-27 09:32:40 +00005578 }
John Wiegley429bb272011-04-08 18:41:53 +00005579 if (castExpr->getType()->isVectorType()) {
5580 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
5581 return ExprError();
5582 else
5583 return Owned(castExpr);
5584 }
Anders Carlssonc3516322009-10-16 02:48:28 +00005585
John McCallf3ea8cf2010-11-14 08:17:51 +00005586 // The source and target types are both scalars, i.e.
5587 // - arithmetic types (fundamental, enum, and complex)
5588 // - all kinds of pointers
5589 // Note that member pointers were filtered out with C++, above.
5590
John Wiegley429bb272011-04-08 18:41:53 +00005591 if (isa<ObjCSelectorExpr>(castExpr)) {
5592 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
5593 return ExprError();
5594 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005595
John McCallf3ea8cf2010-11-14 08:17:51 +00005596 // If either type is a pointer, the other type has to be either an
5597 // integer or a pointer.
John McCallf85e1932011-06-15 23:02:42 +00005598 QualType castExprType = castExpr->getType();
Anders Carlssonc3516322009-10-16 02:48:28 +00005599 if (!castType->isArithmeticType()) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00005600 if (!castExprType->isIntegralType(Context) &&
John Wiegley429bb272011-04-08 18:41:53 +00005601 castExprType->isArithmeticType()) {
5602 Diag(castExpr->getLocStart(),
5603 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00005604 << castExprType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005605 return ExprError();
5606 }
Eli Friedman41826bb2009-05-01 02:23:58 +00005607 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005608 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
5609 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00005610 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005611 return ExprError();
5612 }
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005613 }
Anders Carlsson82debc72009-10-18 18:12:03 +00005614
John McCallf85e1932011-06-15 23:02:42 +00005615 if (getLangOptions().ObjCAutoRefCount) {
5616 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
5617 CheckObjCARCConversion(SourceRange(CastStartLoc, castExpr->getLocEnd()),
5618 castType, castExpr, CCK_CStyleCast);
5619
5620 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
5621 if (const PointerType *ExprPtr = castExprType->getAs<PointerType>()) {
5622 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
5623 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
5624 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
5625 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
5626 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
5627 Diag(castExpr->getLocStart(),
5628 diag::err_typecheck_incompatible_lifetime)
5629 << castExprType << castType << AA_Casting
5630 << castExpr->getSourceRange();
5631
5632 return ExprError();
5633 }
5634 }
5635 }
5636 }
5637
John Wiegley429bb272011-04-08 18:41:53 +00005638 castExprRes = Owned(castExpr);
5639 Kind = PrepareScalarCast(*this, castExprRes, castType);
5640 if (castExprRes.isInvalid())
5641 return ExprError();
5642 castExpr = castExprRes.take();
John McCallb7f4ffe2010-08-12 21:44:57 +00005643
John McCallf3ea8cf2010-11-14 08:17:51 +00005644 if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00005645 CheckCastAlign(castExpr, castType, TyR);
5646
John Wiegley429bb272011-04-08 18:41:53 +00005647 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005648}
5649
Anders Carlssonc3516322009-10-16 02:48:28 +00005650bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00005651 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00005652 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005653
Anders Carlssona64db8f2007-11-27 05:51:55 +00005654 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00005655 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00005656 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00005657 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00005658 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005659 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00005660 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005661 } else
5662 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005663 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00005664 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005665
John McCall2de56d12010-08-25 11:45:40 +00005666 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005667 return false;
5668}
5669
John Wiegley429bb272011-04-08 18:41:53 +00005670ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5671 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00005672 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005673
Anders Carlsson16a89042009-10-16 05:23:41 +00005674 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005675
Nate Begeman9b10da62009-06-27 22:05:55 +00005676 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5677 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00005678 if (SrcTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005679 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
5680 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00005681 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00005682 return ExprError();
5683 }
John McCall2de56d12010-08-25 11:45:40 +00005684 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00005685 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00005686 }
5687
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005688 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00005689 // conversion will take place first from scalar to elt type, and then
5690 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005691 if (SrcTy->isPointerType())
5692 return Diag(R.getBegin(),
5693 diag::err_invalid_conversion_between_vector_and_scalar)
5694 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00005695
5696 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00005697 ExprResult CastExprRes = Owned(CastExpr);
5698 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
5699 if (CastExprRes.isInvalid())
5700 return ExprError();
5701 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005702
John McCall2de56d12010-08-25 11:45:40 +00005703 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00005704 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00005705}
5706
John McCall60d7b3a2010-08-24 06:29:42 +00005707ExprResult
John McCallb3d87482010-08-24 05:47:05 +00005708Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005709 SourceLocation RParenLoc, Expr *castExpr) {
5710 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005711 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00005712
John McCall9d125032010-01-15 18:39:57 +00005713 TypeSourceInfo *castTInfo;
5714 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5715 if (!castTInfo)
John McCall42f56b52010-01-18 19:35:47 +00005716 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00005717
Nate Begeman2ef13e52009-08-10 23:49:36 +00005718 // If the Expr being casted is a ParenListExpr, handle it specially.
5719 if (isa<ParenListExpr>(castExpr))
John McCall9ae2f072010-08-23 23:25:46 +00005720 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCall42f56b52010-01-18 19:35:47 +00005721 castTInfo);
John McCallb042fdf2010-01-15 18:56:44 +00005722
John McCall9ae2f072010-08-23 23:25:46 +00005723 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallb042fdf2010-01-15 18:56:44 +00005724}
5725
John McCall60d7b3a2010-08-24 06:29:42 +00005726ExprResult
John McCallb042fdf2010-01-15 18:56:44 +00005727Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005728 SourceLocation RParenLoc, Expr *castExpr) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005729 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +00005730 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +00005731 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +00005732 ExprResult CastResult =
John McCallf85e1932011-06-15 23:02:42 +00005733 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
5734 castExpr, Kind, VK, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +00005735 if (CastResult.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005736 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00005737 castExpr = CastResult.take();
Anders Carlsson0aebc812009-09-09 21:33:21 +00005738
John McCallf871d0c2010-08-07 06:22:56 +00005739 return Owned(CStyleCastExpr::Create(Context,
John Wiegley429bb272011-04-08 18:41:53 +00005740 Ty->getType().getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +00005741 VK, Kind, castExpr, &BasePath, Ty,
John McCallf871d0c2010-08-07 06:22:56 +00005742 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00005743}
5744
Nate Begeman2ef13e52009-08-10 23:49:36 +00005745/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5746/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005747ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005748Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005749 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5750 if (!E)
5751 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00005752
John McCall60d7b3a2010-08-24 06:29:42 +00005753 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00005754
Nate Begeman2ef13e52009-08-10 23:49:36 +00005755 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00005756 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5757 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00005758
John McCall9ae2f072010-08-23 23:25:46 +00005759 if (Result.isInvalid()) return ExprError();
5760
5761 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005762}
5763
John McCall60d7b3a2010-08-24 06:29:42 +00005764ExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00005765Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00005766 SourceLocation RParenLoc, Expr *Op,
John McCall42f56b52010-01-18 19:35:47 +00005767 TypeSourceInfo *TInfo) {
John McCall9ae2f072010-08-23 23:25:46 +00005768 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCall42f56b52010-01-18 19:35:47 +00005769 QualType Ty = TInfo->getType();
Anton Yartsevd06fea82011-03-27 09:32:40 +00005770 bool isVectorLiteral = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005771
Anton Yartsevd06fea82011-03-27 09:32:40 +00005772 // Check for an altivec or OpenCL literal,
John Thompson8bb59a82010-06-30 22:55:51 +00005773 // i.e. all the elements are integer constants.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005774 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5775 if (PE->getNumExprs() == 0) {
5776 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5777 return ExprError();
5778 }
John Thompson8bb59a82010-06-30 22:55:51 +00005779 if (PE->getNumExprs() == 1) {
5780 if (!PE->getExpr(0)->getType()->isVectorType())
Anton Yartsevd06fea82011-03-27 09:32:40 +00005781 isVectorLiteral = true;
John Thompson8bb59a82010-06-30 22:55:51 +00005782 }
5783 else
Anton Yartsevd06fea82011-03-27 09:32:40 +00005784 isVectorLiteral = true;
John Thompson8bb59a82010-06-30 22:55:51 +00005785 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00005786
Anton Yartsevd06fea82011-03-27 09:32:40 +00005787 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
John Thompson8bb59a82010-06-30 22:55:51 +00005788 // then handle it as such.
Anton Yartsevd06fea82011-03-27 09:32:40 +00005789 if (isVectorLiteral) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005790 llvm::SmallVector<Expr *, 8> initExprs;
Anton Yartsevd06fea82011-03-27 09:32:40 +00005791 // '(...)' form of vector initialization in AltiVec: the number of
5792 // initializers must be one or must match the size of the vector.
5793 // If a single value is specified in the initializer then it will be
5794 // replicated to all the components of the vector
5795 if (Ty->getAs<VectorType>()->getVectorKind() ==
5796 VectorType::AltiVecVector) {
5797 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5798 // The number of initializers must be one or must match the size of the
5799 // vector. If a single value is specified in the initializer then it will
5800 // be replicated to all the components of the vector
5801 if (PE->getNumExprs() == 1) {
5802 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00005803 ExprResult Literal = Owned(PE->getExpr(0));
5804 Literal = ImpCastExprToType(Literal.take(), ElemTy,
5805 PrepareScalarCast(*this, Literal, ElemTy));
5806 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
Anton Yartsevd06fea82011-03-27 09:32:40 +00005807 }
5808 else if (PE->getNumExprs() < numElems) {
5809 Diag(PE->getExprLoc(),
5810 diag::err_incorrect_number_of_vector_initializers);
5811 return ExprError();
5812 }
5813 else
5814 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5815 initExprs.push_back(PE->getExpr(i));
5816 }
5817 else
5818 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5819 initExprs.push_back(PE->getExpr(i));
Nate Begeman2ef13e52009-08-10 23:49:36 +00005820
5821 // FIXME: This means that pretty-printing the final AST will produce curly
5822 // braces instead of the original commas.
Ted Kremenek709210f2010-04-13 23:39:13 +00005823 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5824 &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00005825 initExprs.size(), RParenLoc);
5826 E->setType(Ty);
John McCall9ae2f072010-08-23 23:25:46 +00005827 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005828 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00005829 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00005830 // sequence of BinOp comma operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005831 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCall9ae2f072010-08-23 23:25:46 +00005832 if (Result.isInvalid()) return ExprError();
5833 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005834 }
5835}
5836
John McCall60d7b3a2010-08-24 06:29:42 +00005837ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00005838 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005839 MultiExprArg Val,
John McCallb3d87482010-08-24 05:47:05 +00005840 ParsedType TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005841 unsigned nexprs = Val.size();
5842 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005843 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5844 Expr *expr;
5845 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5846 expr = new (Context) ParenExpr(L, R, exprs[0]);
5847 else
5848 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005849 return Owned(expr);
5850}
5851
Chandler Carruth82214a82011-02-18 23:54:50 +00005852/// \brief Emit a specialized diagnostic when one expression is a null pointer
5853/// constant and the other is not a pointer.
5854bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5855 SourceLocation QuestionLoc) {
5856 Expr *NullExpr = LHS;
5857 Expr *NonPointerExpr = RHS;
5858 Expr::NullPointerConstantKind NullKind =
5859 NullExpr->isNullPointerConstant(Context,
5860 Expr::NPC_ValueDependentIsNotNull);
5861
5862 if (NullKind == Expr::NPCK_NotNull) {
5863 NullExpr = RHS;
5864 NonPointerExpr = LHS;
5865 NullKind =
5866 NullExpr->isNullPointerConstant(Context,
5867 Expr::NPC_ValueDependentIsNotNull);
5868 }
5869
5870 if (NullKind == Expr::NPCK_NotNull)
5871 return false;
5872
5873 if (NullKind == Expr::NPCK_ZeroInteger) {
5874 // In this case, check to make sure that we got here from a "NULL"
5875 // string in the source code.
5876 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00005877 SourceLocation loc = NullExpr->getExprLoc();
5878 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00005879 return false;
5880 }
5881
5882 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5883 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5884 << NonPointerExpr->getType() << DiagType
5885 << NonPointerExpr->getSourceRange();
5886 return true;
5887}
5888
Sebastian Redl28507842009-02-26 14:39:58 +00005889/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5890/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00005891/// C99 6.5.15
John Wiegley429bb272011-04-08 18:41:53 +00005892QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005893 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00005894 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00005895
John McCallfb8721c2011-04-10 19:13:55 +00005896 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00005897 if (!lhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00005898 LHS = move(lhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00005899
John McCallfb8721c2011-04-10 19:13:55 +00005900 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00005901 if (!rhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00005902 RHS = move(rhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00005903
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005904 // C++ is sufficiently different to merit its own checker.
5905 if (getLangOptions().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00005906 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00005907
5908 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005909 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005910
John Wiegley429bb272011-04-08 18:41:53 +00005911 Cond = UsualUnaryConversions(Cond.take());
5912 if (Cond.isInvalid())
5913 return QualType();
5914 LHS = UsualUnaryConversions(LHS.take());
5915 if (LHS.isInvalid())
5916 return QualType();
5917 RHS = UsualUnaryConversions(RHS.take());
5918 if (RHS.isInvalid())
5919 return QualType();
5920
5921 QualType CondTy = Cond.get()->getType();
5922 QualType LHSTy = LHS.get()->getType();
5923 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005924
Reid Spencer5f016e22007-07-11 17:01:13 +00005925 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005926 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begeman6155d732010-09-20 22:41:17 +00005927 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5928 // Throw an error if its not either.
5929 if (getLangOptions().OpenCL) {
5930 if (!CondTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005931 Diag(Cond.get()->getLocStart(),
Nate Begeman6155d732010-09-20 22:41:17 +00005932 diag::err_typecheck_cond_expect_scalar_or_vector)
5933 << CondTy;
5934 return QualType();
5935 }
5936 }
5937 else {
John Wiegley429bb272011-04-08 18:41:53 +00005938 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00005939 << CondTy;
5940 return QualType();
5941 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005942 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005943
Chris Lattner70d67a92008-01-06 22:42:25 +00005944 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005945 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5946 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00005947
Nate Begeman6155d732010-09-20 22:41:17 +00005948 // OpenCL: If the condition is a vector, and both operands are scalar,
5949 // attempt to implicity convert them to the vector type to act like the
5950 // built in select.
5951 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5952 // Both operands should be of scalar type.
5953 if (!LHSTy->isScalarType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005954 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00005955 << CondTy;
5956 return QualType();
5957 }
5958 if (!RHSTy->isScalarType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005959 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00005960 << CondTy;
5961 return QualType();
5962 }
5963 // Implicity convert these scalars to the type of the condition.
John Wiegley429bb272011-04-08 18:41:53 +00005964 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5965 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begeman6155d732010-09-20 22:41:17 +00005966 }
5967
Chris Lattner70d67a92008-01-06 22:42:25 +00005968 // If both operands have arithmetic type, do the usual arithmetic conversions
5969 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005970 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5971 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00005972 if (LHS.isInvalid() || RHS.isInvalid())
5973 return QualType();
5974 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00005975 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005976
Chris Lattner70d67a92008-01-06 22:42:25 +00005977 // If both operands are the same structure or union type, the result is that
5978 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005979 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5980 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00005981 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005982 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00005983 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005984 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005985 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00005986 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005987
Chris Lattner70d67a92008-01-06 22:42:25 +00005988 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00005989 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005990 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5991 if (!LHSTy->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +00005992 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5993 << RHS.get()->getSourceRange();
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005994 if (!RHSTy->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +00005995 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5996 << LHS.get()->getSourceRange();
5997 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
5998 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00005999 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00006000 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00006001 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6002 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006003 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
John Wiegley429bb272011-04-08 18:41:53 +00006004 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00006005 // promote the null to a pointer.
John Wiegley429bb272011-04-08 18:41:53 +00006006 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00006007 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00006008 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006009 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
John Wiegley429bb272011-04-08 18:41:53 +00006010 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
6011 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00006012 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00006013 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006014
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006015 // All objective-c pointer type analysis is done here.
6016 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6017 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00006018 if (LHS.isInvalid() || RHS.isInvalid())
6019 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006020 if (!compositeType.isNull())
6021 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006022
6023
Steve Naroff7154a772009-07-01 14:36:47 +00006024 // Handle block pointer types.
6025 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
6026 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6027 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6028 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00006029 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
6030 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00006031 return destType;
6032 }
6033 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00006034 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00006035 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00006036 }
Steve Naroff7154a772009-07-01 14:36:47 +00006037 // We have 2 block pointer types.
6038 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6039 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00006040 return LHSTy;
6041 }
Steve Naroff7154a772009-07-01 14:36:47 +00006042 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00006043 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
6044 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006045
Steve Naroff7154a772009-07-01 14:36:47 +00006046 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
6047 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00006048 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00006049 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00006050 // In this situation, we assume void* type. No especially good
6051 // reason, but this is what gcc does, and we do have to pick
6052 // to get a consistent AST.
6053 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00006054 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6055 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00006056 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006057 }
Steve Naroff7154a772009-07-01 14:36:47 +00006058 // The block pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00006059 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
6060 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00006061 return LHSTy;
6062 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006063
Steve Naroff7154a772009-07-01 14:36:47 +00006064 // Check constraints for C object pointers types (C99 6.5.15p3,6).
6065 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
6066 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00006067 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6068 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00006069
6070 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6071 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6072 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00006073 QualType destPointee
6074 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00006075 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00006076 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00006077 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00006078 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00006079 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00006080 return destType;
6081 }
6082 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00006083 QualType destPointee
6084 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00006085 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00006086 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00006087 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00006088 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00006089 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00006090 return destType;
6091 }
6092
6093 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6094 // Two identical pointer types are always compatible.
6095 return LHSTy;
6096 }
6097 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
6098 rhptee.getUnqualifiedType())) {
6099 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00006100 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00006101 // In this situation, we assume void* type. No especially good
6102 // reason, but this is what gcc does, and we do have to pick
6103 // to get a consistent AST.
6104 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00006105 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6106 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00006107 return incompatTy;
6108 }
6109 // The pointer types are compatible.
6110 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
6111 // differently qualified versions of compatible types, the result type is
6112 // a pointer to an appropriately qualified version of the *composite*
6113 // type.
6114 // FIXME: Need to calculate the composite type.
6115 // FIXME: Need to add qualifiers
John Wiegley429bb272011-04-08 18:41:53 +00006116 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
6117 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00006118 return LHSTy;
6119 }
Mike Stump1eb44332009-09-09 15:08:12 +00006120
John McCall404cd162010-11-13 01:35:44 +00006121 // GCC compatibility: soften pointer/integer mismatch. Note that
6122 // null pointers have been filtered out by this point.
Steve Naroff7154a772009-07-01 14:36:47 +00006123 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
6124 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley429bb272011-04-08 18:41:53 +00006125 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6126 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00006127 return RHSTy;
6128 }
6129 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
6130 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley429bb272011-04-08 18:41:53 +00006131 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6132 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00006133 return LHSTy;
6134 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00006135
Chandler Carruth82214a82011-02-18 23:54:50 +00006136 // Emit a better diagnostic if one of the expressions is a null pointer
6137 // constant and the other is not a pointer type. In this case, the user most
6138 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00006139 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00006140 return QualType();
6141
Chris Lattner70d67a92008-01-06 22:42:25 +00006142 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00006143 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00006144 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006145 return QualType();
6146}
6147
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006148/// FindCompositeObjCPointerType - Helper method to find composite type of
6149/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00006150QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006151 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00006152 QualType LHSTy = LHS.get()->getType();
6153 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006154
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006155 // Handle things like Class and struct objc_class*. Here we case the result
6156 // to the pseudo-builtin, because that will be implicitly cast back to the
6157 // redefinition type if an attempt is made to access its fields.
6158 if (LHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00006159 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006160 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006161 return LHSTy;
6162 }
6163 if (RHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00006164 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006165 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006166 return RHSTy;
6167 }
6168 // And the same for struct objc_object* / id
6169 if (LHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00006170 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006171 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006172 return LHSTy;
6173 }
6174 if (RHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00006175 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006176 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006177 return RHSTy;
6178 }
6179 // And the same for struct objc_selector* / SEL
6180 if (Context.isObjCSelType(LHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00006181 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006182 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006183 return LHSTy;
6184 }
6185 if (Context.isObjCSelType(RHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00006186 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006187 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006188 return RHSTy;
6189 }
6190 // Check constraints for Objective-C object pointers types.
6191 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006192
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006193 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6194 // Two identical object pointer types are always compatible.
6195 return LHSTy;
6196 }
6197 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
6198 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
6199 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006200
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006201 // If both operands are interfaces and either operand can be
6202 // assigned to the other, use that type as the composite
6203 // type. This allows
6204 // xxx ? (A*) a : (B*) b
6205 // where B is a subclass of A.
6206 //
6207 // Additionally, as for assignment, if either type is 'id'
6208 // allow silent coercion. Finally, if the types are
6209 // incompatible then make sure to use 'id' as the composite
6210 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006211
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006212 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6213 // It could return the composite type.
6214 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6215 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6216 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6217 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6218 } else if ((LHSTy->isObjCQualifiedIdType() ||
6219 RHSTy->isObjCQualifiedIdType()) &&
6220 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6221 // Need to handle "id<xx>" explicitly.
6222 // GCC allows qualified id and any Objective-C type to devolve to
6223 // id. Currently localizing to here until clear this should be
6224 // part of ObjCQualifiedIdTypesAreCompatible.
6225 compositeType = Context.getObjCIdType();
6226 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6227 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006228 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006229 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
6230 ;
6231 else {
6232 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6233 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00006234 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006235 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00006236 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6237 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006238 return incompatTy;
6239 }
6240 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00006241 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
6242 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006243 return compositeType;
6244 }
6245 // Check Objective-C object pointer types and 'void *'
6246 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6247 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6248 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6249 QualType destPointee
6250 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6251 QualType destType = Context.getPointerType(destPointee);
6252 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00006253 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006254 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00006255 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006256 return destType;
6257 }
6258 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6259 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6260 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6261 QualType destPointee
6262 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6263 QualType destType = Context.getPointerType(destPointee);
6264 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00006265 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006266 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00006267 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006268 return destType;
6269 }
6270 return QualType();
6271}
6272
Chandler Carruthf0b60d62011-06-16 01:05:14 +00006273/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006274/// ParenRange in parentheses.
6275static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00006276 const PartialDiagnostic &Note,
6277 SourceRange ParenRange) {
6278 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6279 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6280 EndLoc.isValid()) {
6281 Self.Diag(Loc, Note)
6282 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6283 << FixItHint::CreateInsertion(EndLoc, ")");
6284 } else {
6285 // We can't display the parentheses, so just show the bare note.
6286 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006287 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006288}
6289
6290static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6291 return Opc >= BO_Mul && Opc <= BO_Shr;
6292}
6293
Hans Wennborg2f072b42011-06-09 17:06:51 +00006294/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6295/// expression, either using a built-in or overloaded operator,
6296/// and sets *OpCode to the opcode and *RHS to the right-hand side expression.
6297static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6298 Expr **RHS) {
6299 E = E->IgnoreParenImpCasts();
6300 E = E->IgnoreConversionOperator();
6301 E = E->IgnoreParenImpCasts();
6302
6303 // Built-in binary operator.
6304 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6305 if (IsArithmeticOp(OP->getOpcode())) {
6306 *Opcode = OP->getOpcode();
6307 *RHS = OP->getRHS();
6308 return true;
6309 }
6310 }
6311
6312 // Overloaded operator.
6313 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6314 if (Call->getNumArgs() != 2)
6315 return false;
6316
6317 // Make sure this is really a binary operator that is safe to pass into
6318 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6319 OverloadedOperatorKind OO = Call->getOperator();
6320 if (OO < OO_Plus || OO > OO_Arrow)
6321 return false;
6322
6323 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6324 if (IsArithmeticOp(OpKind)) {
6325 *Opcode = OpKind;
6326 *RHS = Call->getArg(1);
6327 return true;
6328 }
6329 }
6330
6331 return false;
6332}
6333
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006334static bool IsLogicOp(BinaryOperatorKind Opc) {
6335 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
6336}
6337
Hans Wennborg2f072b42011-06-09 17:06:51 +00006338/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6339/// or is a logical expression such as (x==y) which has int type, but is
6340/// commonly interpreted as boolean.
6341static bool ExprLooksBoolean(Expr *E) {
6342 E = E->IgnoreParenImpCasts();
6343
6344 if (E->getType()->isBooleanType())
6345 return true;
6346 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6347 return IsLogicOp(OP->getOpcode());
6348 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6349 return OP->getOpcode() == UO_LNot;
6350
6351 return false;
6352}
6353
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006354/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6355/// and binary operator are mixed in a way that suggests the programmer assumed
6356/// the conditional operator has higher precedence, for example:
6357/// "int x = a + someBinaryCondition ? 1 : 2".
6358static void DiagnoseConditionalPrecedence(Sema &Self,
6359 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00006360 Expr *Condition,
6361 Expr *LHS,
6362 Expr *RHS) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00006363 BinaryOperatorKind CondOpcode;
6364 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006365
Chandler Carruth43bc78d2011-06-16 01:05:08 +00006366 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00006367 return;
6368 if (!ExprLooksBoolean(CondRHS))
6369 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006370
Hans Wennborg2f072b42011-06-09 17:06:51 +00006371 // The condition is an arithmetic binary expression, with a right-
6372 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006373
Chandler Carruthf0b60d62011-06-16 01:05:14 +00006374 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00006375 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00006376 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006377
Chandler Carruthf0b60d62011-06-16 01:05:14 +00006378 SuggestParentheses(Self, OpLoc,
6379 Self.PDiag(diag::note_precedence_conditional_silence)
6380 << BinaryOperator::getOpcodeStr(CondOpcode),
6381 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006382
Chandler Carruthf0b60d62011-06-16 01:05:14 +00006383 SuggestParentheses(Self, OpLoc,
6384 Self.PDiag(diag::note_precedence_conditional_first),
6385 SourceRange(CondRHS->getLocStart(), RHS->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006386}
6387
Steve Narofff69936d2007-09-16 03:34:24 +00006388/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00006389/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00006390ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00006391 SourceLocation ColonLoc,
6392 Expr *CondExpr, Expr *LHSExpr,
6393 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00006394 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6395 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00006396 OpaqueValueExpr *opaqueValue = 0;
6397 Expr *commonExpr = 0;
6398 if (LHSExpr == 0) {
6399 commonExpr = CondExpr;
6400
6401 // We usually want to apply unary conversions *before* saving, except
6402 // in the special case of a C++ l-value conditional.
6403 if (!(getLangOptions().CPlusPlus
6404 && !commonExpr->isTypeDependent()
6405 && commonExpr->getValueKind() == RHSExpr->getValueKind()
6406 && commonExpr->isGLValue()
6407 && commonExpr->isOrdinaryOrBitFieldObject()
6408 && RHSExpr->isOrdinaryOrBitFieldObject()
6409 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00006410 ExprResult commonRes = UsualUnaryConversions(commonExpr);
6411 if (commonRes.isInvalid())
6412 return ExprError();
6413 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00006414 }
6415
6416 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6417 commonExpr->getType(),
6418 commonExpr->getValueKind(),
6419 commonExpr->getObjectKind());
6420 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00006421 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006422
John McCallf89e55a2010-11-18 06:31:45 +00006423 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00006424 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00006425 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
6426 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00006427 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00006428 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6429 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006430 return ExprError();
6431
Hans Wennborg9cfdae32011-06-03 18:00:36 +00006432 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6433 RHS.get());
6434
John McCall56ca35d2011-02-17 10:25:35 +00006435 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00006436 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
6437 LHS.take(), ColonLoc,
6438 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00006439
6440 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00006441 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
6442 RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00006443}
6444
John McCalle4be87e2011-01-31 23:13:11 +00006445// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00006446// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00006447// routine is it effectively iqnores the qualifiers on the top level pointee.
6448// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6449// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00006450static Sema::AssignConvertType
6451checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6452 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6453 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006454
Reid Spencer5f016e22007-07-11 17:01:13 +00006455 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00006456 const Type *lhptee, *rhptee;
6457 Qualifiers lhq, rhq;
6458 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
6459 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006460
John McCalle4be87e2011-01-31 23:13:11 +00006461 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006462
6463 // C99 6.5.16.1p1: This following citation is common to constraints
6464 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6465 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00006466 Qualifiers lq;
6467
John McCallf85e1932011-06-15 23:02:42 +00006468 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
6469 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
6470 lhq.compatiblyIncludesObjCLifetime(rhq)) {
6471 // Ignore lifetime for further calculation.
6472 lhq.removeObjCLifetime();
6473 rhq.removeObjCLifetime();
6474 }
6475
John McCall86c05f32011-02-01 00:10:29 +00006476 if (!lhq.compatiblyIncludes(rhq)) {
6477 // Treat address-space mismatches as fatal. TODO: address subspaces
6478 if (lhq.getAddressSpace() != rhq.getAddressSpace())
6479 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6480
John McCallf85e1932011-06-15 23:02:42 +00006481 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00006482 // and from void*.
John McCallf85e1932011-06-15 23:02:42 +00006483 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
6484 .compatiblyIncludes(
6485 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall22348732011-03-26 02:56:45 +00006486 && (lhptee->isVoidType() || rhptee->isVoidType()))
6487 ; // keep old
6488
John McCallf85e1932011-06-15 23:02:42 +00006489 // Treat lifetime mismatches as fatal.
6490 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6491 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6492
John McCall86c05f32011-02-01 00:10:29 +00006493 // For GCC compatibility, other qualifier mismatches are treated
6494 // as still compatible in C.
6495 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6496 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006497
Mike Stumpeed9cac2009-02-19 03:04:26 +00006498 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6499 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00006500 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006501 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00006502 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00006503 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006504
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006505 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00006506 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00006507 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006508 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006509
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006510 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00006511 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00006512 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006513
6514 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00006515 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00006516 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006517 }
John McCall86c05f32011-02-01 00:10:29 +00006518
Mike Stumpeed9cac2009-02-19 03:04:26 +00006519 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00006520 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00006521 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6522 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006523 // Check if the pointee types are compatible ignoring the sign.
6524 // We explicitly check for char so that we catch "char" vs
6525 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00006526 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00006527 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00006528 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00006529 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006530
Chris Lattner6a2b9262009-10-17 20:33:28 +00006531 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00006532 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00006533 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00006534 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00006535
John McCall86c05f32011-02-01 00:10:29 +00006536 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006537 // Types are compatible ignoring the sign. Qualifier incompatibility
6538 // takes priority over sign incompatibility because the sign
6539 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00006540 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006541 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00006542
John McCalle4be87e2011-01-31 23:13:11 +00006543 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006544 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006545
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006546 // If we are a multi-level pointer, it's possible that our issue is simply
6547 // one of qualification - e.g. char ** -> const char ** is not allowed. If
6548 // the eventual target type is the same and the pointers have the same
6549 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00006550 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006551 do {
John McCall86c05f32011-02-01 00:10:29 +00006552 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6553 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00006554 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006555
John McCall86c05f32011-02-01 00:10:29 +00006556 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00006557 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006558 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006559
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006560 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00006561 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006562 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00006563 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006564}
6565
John McCalle4be87e2011-01-31 23:13:11 +00006566/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00006567/// block pointer types are compatible or whether a block and normal pointer
6568/// are compatible. It is more restrict than comparing two function pointer
6569// types.
John McCalle4be87e2011-01-31 23:13:11 +00006570static Sema::AssignConvertType
6571checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
6572 QualType rhsType) {
6573 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6574 assert(rhsType.isCanonical() && "RHS not canonicalized!");
6575
Steve Naroff1c7d0672008-09-04 15:10:53 +00006576 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006577
Steve Naroff1c7d0672008-09-04 15:10:53 +00006578 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCalle4be87e2011-01-31 23:13:11 +00006579 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
6580 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006581
John McCalle4be87e2011-01-31 23:13:11 +00006582 // In C++, the types have to match exactly.
6583 if (S.getLangOptions().CPlusPlus)
6584 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006585
John McCalle4be87e2011-01-31 23:13:11 +00006586 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006587
Steve Naroff1c7d0672008-09-04 15:10:53 +00006588 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00006589 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6590 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006591
John McCalle4be87e2011-01-31 23:13:11 +00006592 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
6593 return Sema::IncompatibleBlockPointer;
6594
Steve Naroff1c7d0672008-09-04 15:10:53 +00006595 return ConvTy;
6596}
6597
John McCalle4be87e2011-01-31 23:13:11 +00006598/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006599/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00006600static Sema::AssignConvertType
6601checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6602 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
6603 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
6604
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00006605 if (lhsType->isObjCBuiltinType()) {
6606 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00006607 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
6608 !rhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00006609 return Sema::IncompatiblePointer;
6610 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00006611 }
6612 if (rhsType->isObjCBuiltinType()) {
6613 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00006614 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
6615 !lhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00006616 return Sema::IncompatiblePointer;
6617 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00006618 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006619 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006620 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006621 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006622 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006623
John McCalle4be87e2011-01-31 23:13:11 +00006624 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
6625 return Sema::CompatiblePointerDiscardsQualifiers;
6626
6627 if (S.Context.typesAreCompatible(lhsType, rhsType))
6628 return Sema::Compatible;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006629 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00006630 return Sema::IncompatibleObjCQualifiedId;
6631 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006632}
6633
John McCall1c23e912010-11-16 02:32:08 +00006634Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00006635Sema::CheckAssignmentConstraints(SourceLocation Loc,
6636 QualType lhsType, QualType rhsType) {
John McCall1c23e912010-11-16 02:32:08 +00006637 // Fake up an opaque expression. We don't actually care about what
6638 // cast operations are required, so if CheckAssignmentConstraints
6639 // adds casts to this they'll be wasted, but fortunately that doesn't
6640 // usually happen on valid code.
Douglas Gregorb608b982011-01-28 02:26:04 +00006641 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00006642 ExprResult rhsPtr = &rhs;
John McCall1c23e912010-11-16 02:32:08 +00006643 CastKind K = CK_Invalid;
6644
6645 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
6646}
6647
Mike Stumpeed9cac2009-02-19 03:04:26 +00006648/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6649/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00006650/// pointers. Here are some objectionable examples that GCC considers warnings:
6651///
6652/// int a, *pint;
6653/// short *pshort;
6654/// struct foo *pfoo;
6655///
6656/// pint = pshort; // warning: assignment from incompatible pointer type
6657/// a = pint; // warning: assignment makes integer from pointer without a cast
6658/// pint = a; // warning: assignment makes pointer from integer without a cast
6659/// pint = pfoo; // warning: assignment from incompatible pointer type
6660///
6661/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00006662/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00006663///
John McCalldaa8e4e2010-11-15 09:13:47 +00006664/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00006665Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00006666Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCalldaa8e4e2010-11-15 09:13:47 +00006667 CastKind &Kind) {
John Wiegley429bb272011-04-08 18:41:53 +00006668 QualType rhsType = rhs.get()->getType();
John McCall1c23e912010-11-16 02:32:08 +00006669
Chris Lattnerfc144e22008-01-04 23:18:45 +00006670 // Get canonical types. We're not formatting these types, just comparing
6671 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00006672 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
6673 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006674
John McCallb6cfa242011-01-31 22:28:28 +00006675 // Common case: no conversion required.
John McCalldaa8e4e2010-11-15 09:13:47 +00006676 if (lhsType == rhsType) {
6677 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00006678 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00006679 }
6680
Douglas Gregor9d293df2008-10-28 00:22:11 +00006681 // If the left-hand side is a reference type, then we are in a
6682 // (rare!) case where we've allowed the use of references in C,
6683 // e.g., as a parameter type in a built-in function. In this case,
6684 // just make sure that the type referenced is compatible with the
6685 // right-hand side type. The caller is responsible for adjusting
6686 // lhsType so that the resulting expression does not have reference
6687 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00006688 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006689 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
6690 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00006691 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006692 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00006693 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00006694 }
John McCallb6cfa242011-01-31 22:28:28 +00006695
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006696 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6697 // to the same ExtVector type.
6698 if (lhsType->isExtVectorType()) {
6699 if (rhsType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00006700 return Incompatible;
6701 if (rhsType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00006702 // CK_VectorSplat does T -> vector T, so first cast to the
6703 // element type.
6704 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
6705 if (elType != rhsType) {
6706 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley429bb272011-04-08 18:41:53 +00006707 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00006708 }
6709 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006710 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006711 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006712 }
Mike Stump1eb44332009-09-09 15:08:12 +00006713
John McCallb6cfa242011-01-31 22:28:28 +00006714 // Conversions to or from vector type.
Nate Begemanbe2341d2008-07-14 18:02:46 +00006715 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor255210e2010-08-06 10:14:59 +00006716 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00006717 // Allow assignments of an AltiVec vector type to an equivalent GCC
6718 // vector type and vice versa
6719 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6720 Kind = CK_BitCast;
6721 return Compatible;
6722 }
6723
Douglas Gregor255210e2010-08-06 10:14:59 +00006724 // If we are allowing lax vector conversions, and LHS and RHS are both
6725 // vectors, the total size only needs to be the same. This is a bitcast;
6726 // no bits are changed but the result type is different.
6727 if (getLangOptions().LaxVectorConversions &&
John McCalldaa8e4e2010-11-15 09:13:47 +00006728 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00006729 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006730 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00006731 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00006732 }
6733 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006734 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006735
John McCallb6cfa242011-01-31 22:28:28 +00006736 // Arithmetic conversions.
Douglas Gregor88623ad2010-05-23 21:53:47 +00006737 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00006738 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall1c23e912010-11-16 02:32:08 +00006739 Kind = PrepareScalarCast(*this, rhs, lhsType);
Reid Spencer5f016e22007-07-11 17:01:13 +00006740 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006741 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006742
John McCallb6cfa242011-01-31 22:28:28 +00006743 // Conversions to normal pointers.
6744 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
6745 // U* -> T*
John McCalldaa8e4e2010-11-15 09:13:47 +00006746 if (isa<PointerType>(rhsType)) {
6747 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00006748 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006749 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006750
John McCallb6cfa242011-01-31 22:28:28 +00006751 // int -> T*
6752 if (rhsType->isIntegerType()) {
6753 Kind = CK_IntegralToPointer; // FIXME: null?
6754 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00006755 }
John McCallb6cfa242011-01-31 22:28:28 +00006756
6757 // C pointers are not compatible with ObjC object pointers,
6758 // with two exceptions:
6759 if (isa<ObjCObjectPointerType>(rhsType)) {
6760 // - conversions to void*
6761 if (lhsPointer->getPointeeType()->isVoidType()) {
6762 Kind = CK_AnyPointerToObjCPointerCast;
6763 return Compatible;
6764 }
6765
6766 // - conversions from 'Class' to the redefinition type
6767 if (rhsType->isObjCClassType() &&
6768 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006769 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00006770 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006771 }
Steve Naroffb4406862008-09-29 18:10:17 +00006772
John McCallb6cfa242011-01-31 22:28:28 +00006773 Kind = CK_BitCast;
6774 return IncompatiblePointer;
6775 }
6776
6777 // U^ -> void*
6778 if (rhsType->getAs<BlockPointerType>()) {
6779 if (lhsPointer->getPointeeType()->isVoidType()) {
6780 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00006781 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006782 }
Steve Naroffb4406862008-09-29 18:10:17 +00006783 }
John McCallb6cfa242011-01-31 22:28:28 +00006784
Steve Naroff1c7d0672008-09-04 15:10:53 +00006785 return Incompatible;
6786 }
6787
John McCallb6cfa242011-01-31 22:28:28 +00006788 // Conversions to block pointers.
Steve Naroff1c7d0672008-09-04 15:10:53 +00006789 if (isa<BlockPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006790 // U^ -> T^
6791 if (rhsType->isBlockPointerType()) {
6792 Kind = CK_AnyPointerToBlockPointerCast;
John McCalle4be87e2011-01-31 23:13:11 +00006793 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00006794 }
6795
6796 // int or null -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00006797 if (rhsType->isIntegerType()) {
6798 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00006799 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00006800 }
6801
John McCallb6cfa242011-01-31 22:28:28 +00006802 // id -> T^
6803 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6804 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00006805 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006806 }
Steve Naroffb4406862008-09-29 18:10:17 +00006807
John McCallb6cfa242011-01-31 22:28:28 +00006808 // void* -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00006809 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00006810 if (RHSPT->getPointeeType()->isVoidType()) {
6811 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00006812 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006813 }
John McCalldaa8e4e2010-11-15 09:13:47 +00006814
Chris Lattnerfc144e22008-01-04 23:18:45 +00006815 return Incompatible;
6816 }
6817
John McCallb6cfa242011-01-31 22:28:28 +00006818 // Conversions to Objective-C pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00006819 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006820 // A* -> B*
6821 if (rhsType->isObjCObjectPointerType()) {
6822 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00006823 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00006824 }
6825
6826 // int or null -> A*
John McCalldaa8e4e2010-11-15 09:13:47 +00006827 if (rhsType->isIntegerType()) {
6828 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00006829 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00006830 }
6831
John McCallb6cfa242011-01-31 22:28:28 +00006832 // In general, C pointers are not compatible with ObjC object pointers,
6833 // with two exceptions:
Steve Naroff14108da2009-07-10 23:34:53 +00006834 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006835 // - conversions from 'void*'
6836 if (rhsType->isVoidPointerType()) {
6837 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006838 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006839 }
6840
6841 // - conversions to 'Class' from its redefinition type
6842 if (lhsType->isObjCClassType() &&
6843 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6844 Kind = CK_BitCast;
6845 return Compatible;
6846 }
6847
6848 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006849 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00006850 }
John McCallb6cfa242011-01-31 22:28:28 +00006851
6852 // T^ -> A*
6853 if (rhsType->isBlockPointerType()) {
6854 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00006855 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006856 }
6857
Steve Naroff14108da2009-07-10 23:34:53 +00006858 return Incompatible;
6859 }
John McCallb6cfa242011-01-31 22:28:28 +00006860
6861 // Conversions from pointers that are not covered by the above.
Chris Lattner78eca282008-04-07 06:49:41 +00006862 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006863 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00006864 if (lhsType == Context.BoolTy) {
6865 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006866 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006867 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006868
John McCallb6cfa242011-01-31 22:28:28 +00006869 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00006870 if (lhsType->isIntegerType()) {
6871 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006872 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006873 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006874
Chris Lattnerfc144e22008-01-04 23:18:45 +00006875 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00006876 }
John McCallb6cfa242011-01-31 22:28:28 +00006877
6878 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff14108da2009-07-10 23:34:53 +00006879 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006880 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00006881 if (lhsType == Context.BoolTy) {
6882 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00006883 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006884 }
Steve Naroff14108da2009-07-10 23:34:53 +00006885
John McCallb6cfa242011-01-31 22:28:28 +00006886 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00006887 if (lhsType->isIntegerType()) {
6888 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00006889 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006890 }
6891
Steve Naroff14108da2009-07-10 23:34:53 +00006892 return Incompatible;
6893 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006894
John McCallb6cfa242011-01-31 22:28:28 +00006895 // struct A -> struct B
Chris Lattnerfc144e22008-01-04 23:18:45 +00006896 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006897 if (Context.typesAreCompatible(lhsType, rhsType)) {
6898 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00006899 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006900 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006901 }
John McCallb6cfa242011-01-31 22:28:28 +00006902
Reid Spencer5f016e22007-07-11 17:01:13 +00006903 return Incompatible;
6904}
6905
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006906/// \brief Constructs a transparent union from an expression that is
6907/// used to initialize the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00006908static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006909 QualType UnionType, FieldDecl *Field) {
6910 // Build an initializer list that designates the appropriate member
6911 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00006912 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00006913 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00006914 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006915 SourceLocation());
6916 Initializer->setType(UnionType);
6917 Initializer->setInitializedFieldInUnion(Field);
6918
6919 // Build a compound literal constructing a value of the transparent
6920 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00006921 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00006922 EResult = S.Owned(
6923 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6924 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006925}
6926
6927Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00006928Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
6929 QualType FromType = rExpr.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006930
Mike Stump1eb44332009-09-09 15:08:12 +00006931 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006932 // transparent_union GCC extension.
6933 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006934 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006935 return Incompatible;
6936
6937 // The field to initialize within the transparent union.
6938 RecordDecl *UD = UT->getDecl();
6939 FieldDecl *InitField = 0;
6940 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006941 for (RecordDecl::field_iterator it = UD->field_begin(),
6942 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006943 it != itend; ++it) {
6944 if (it->getType()->isPointerType()) {
6945 // If the transparent union contains a pointer type, we allow:
6946 // 1) void pointer
6947 // 2) null pointer constant
6948 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00006949 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006950 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006951 InitField = *it;
6952 break;
6953 }
Mike Stump1eb44332009-09-09 15:08:12 +00006954
John Wiegley429bb272011-04-08 18:41:53 +00006955 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006956 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00006957 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006958 InitField = *it;
6959 break;
6960 }
6961 }
6962
John McCalldaa8e4e2010-11-15 09:13:47 +00006963 CastKind Kind = CK_Invalid;
John Wiegley429bb272011-04-08 18:41:53 +00006964 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006965 == Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +00006966 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006967 InitField = *it;
6968 break;
6969 }
6970 }
6971
6972 if (!InitField)
6973 return Incompatible;
6974
John Wiegley429bb272011-04-08 18:41:53 +00006975 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006976 return Compatible;
6977}
6978
Chris Lattner5cf216b2008-01-04 18:04:52 +00006979Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00006980Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00006981 if (getLangOptions().CPlusPlus) {
6982 if (!lhsType->isRecordType()) {
6983 // C++ 5.17p3: If the left operand is not of class type, the
6984 // expression is implicitly converted (C++ 4) to the
6985 // cv-unqualified type of the left operand.
John Wiegley429bb272011-04-08 18:41:53 +00006986 ExprResult Res = PerformImplicitConversion(rExpr.get(),
6987 lhsType.getUnqualifiedType(),
6988 AA_Assigning);
6989 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00006990 return Incompatible;
John Wiegley429bb272011-04-08 18:41:53 +00006991 rExpr = move(Res);
Chris Lattner2c4463f2009-04-12 09:02:39 +00006992 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00006993 }
6994
6995 // FIXME: Currently, we fall through and treat C++ classes like C
6996 // structures.
John McCallf6a16482010-12-04 03:47:34 +00006997 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00006998
Steve Naroff529a4ad2007-11-27 17:58:44 +00006999 // C99 6.5.16.1p1: the left operand is a pointer and the right is
7000 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00007001 if ((lhsType->isPointerType() ||
7002 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00007003 lhsType->isBlockPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00007004 && rExpr.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007005 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00007006 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00007007 return Compatible;
7008 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007009
Chris Lattner943140e2007-10-16 02:55:40 +00007010 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00007011 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00007012 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00007013 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00007014 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00007015 // Suppress this for references: C++ 8.5.3p5.
John Wiegley429bb272011-04-08 18:41:53 +00007016 if (!lhsType->isReferenceType()) {
7017 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
7018 if (rExpr.isInvalid())
7019 return Incompatible;
7020 }
Steve Narofff1120de2007-08-24 22:33:52 +00007021
John McCalldaa8e4e2010-11-15 09:13:47 +00007022 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007023 Sema::AssignConvertType result =
John McCall1c23e912010-11-16 02:32:08 +00007024 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007025
Steve Narofff1120de2007-08-24 22:33:52 +00007026 // C99 6.5.16.1p2: The value of the right operand is converted to the
7027 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00007028 // CheckAssignmentConstraints allows the left-hand side to be a reference,
7029 // so that we can use references in built-in functions even in C.
7030 // The getNonReferenceType() call makes sure that the resulting expression
7031 // does not have reference type.
John Wiegley429bb272011-04-08 18:41:53 +00007032 if (result != Incompatible && rExpr.get()->getType() != lhsType)
7033 rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00007034 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00007035}
7036
John Wiegley429bb272011-04-08 18:41:53 +00007037QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007038 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley429bb272011-04-08 18:41:53 +00007039 << lex.get()->getType() << rex.get()->getType()
7040 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00007041 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007042}
7043
John Wiegley429bb272011-04-08 18:41:53 +00007044QualType Sema::CheckVectorOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00007045 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00007046 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00007047 QualType lhsType =
John Wiegley429bb272011-04-08 18:41:53 +00007048 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattnerb77792e2008-07-26 22:17:49 +00007049 QualType rhsType =
John Wiegley429bb272011-04-08 18:41:53 +00007050 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007051
Nate Begemanbe2341d2008-07-14 18:02:46 +00007052 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00007053 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00007054 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00007055
Nate Begemanbe2341d2008-07-14 18:02:46 +00007056 // Handle the case of a vector & extvector type of the same size and element
7057 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00007058 if (getLangOptions().LaxVectorConversions) {
John McCall183700f2009-09-21 23:43:11 +00007059 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth629f9e42010-08-30 07:36:24 +00007060 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00007061 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00007062 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregor26bcf672010-05-19 03:21:00 +00007063 if (lhsType->isExtVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00007064 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00007065 return lhsType;
7066 }
7067
John Wiegley429bb272011-04-08 18:41:53 +00007068 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00007069 return rhsType;
Eric Christophere84f9eb2010-08-26 00:42:16 +00007070 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
7071 // If we are allowing lax vector conversions, and LHS and RHS are both
7072 // vectors, the total size only needs to be the same. This is a
7073 // bitcast; no bits are changed but the result type is different.
John Wiegley429bb272011-04-08 18:41:53 +00007074 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Eric Christophere84f9eb2010-08-26 00:42:16 +00007075 return lhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00007076 }
Eric Christophere84f9eb2010-08-26 00:42:16 +00007077 }
Chandler Carruth629f9e42010-08-30 07:36:24 +00007078 }
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00007079 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007080
Douglas Gregor255210e2010-08-06 10:14:59 +00007081 // Handle the case of equivalent AltiVec and GCC vector types
7082 if (lhsType->isVectorType() && rhsType->isVectorType() &&
7083 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John Wiegley429bb272011-04-08 18:41:53 +00007084 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor255210e2010-08-06 10:14:59 +00007085 return rhsType;
7086 }
7087
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00007088 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
7089 // swap back (so that we don't reverse the inputs to a subtract, for instance.
7090 bool swapped = false;
7091 if (rhsType->isExtVectorType()) {
7092 swapped = true;
7093 std::swap(rex, lex);
7094 std::swap(rhsType, lhsType);
7095 }
Mike Stump1eb44332009-09-09 15:08:12 +00007096
Nate Begemandde25982009-06-28 19:12:57 +00007097 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00007098 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00007099 QualType EltTy = LV->getElementType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00007100 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00007101 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
7102 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00007103 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00007104 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00007105 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00007106 if (swapped) std::swap(rex, lex);
7107 return lhsType;
7108 }
7109 }
7110 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
7111 rhsType->isRealFloatingType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00007112 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
7113 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00007114 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00007115 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00007116 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00007117 if (swapped) std::swap(rex, lex);
7118 return lhsType;
7119 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00007120 }
7121 }
Mike Stump1eb44332009-09-09 15:08:12 +00007122
Nate Begemandde25982009-06-28 19:12:57 +00007123 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007124 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley429bb272011-04-08 18:41:53 +00007125 << lex.get()->getType() << rex.get()->getType()
7126 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007127 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00007128}
7129
Chris Lattner7ef655a2010-01-12 21:23:57 +00007130QualType Sema::CheckMultiplyDivideOperands(
John Wiegley429bb272011-04-08 18:41:53 +00007131 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
7132 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007133 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007134
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007135 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00007136 if (lex.isInvalid() || rex.isInvalid())
7137 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007138
John Wiegley429bb272011-04-08 18:41:53 +00007139 if (!lex.get()->getType()->isArithmeticType() ||
7140 !rex.get()->getType()->isArithmeticType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00007141 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007142
Chris Lattner7ef655a2010-01-12 21:23:57 +00007143 // Check for division by zero.
7144 if (isDiv &&
John Wiegley429bb272011-04-08 18:41:53 +00007145 rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
7146 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
7147 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007148
Chris Lattner7ef655a2010-01-12 21:23:57 +00007149 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00007150}
7151
Chris Lattner7ef655a2010-01-12 21:23:57 +00007152QualType Sema::CheckRemainderOperands(
John Wiegley429bb272011-04-08 18:41:53 +00007153 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
7154 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
7155 if (lex.get()->getType()->hasIntegerRepresentation() &&
7156 rex.get()->getType()->hasIntegerRepresentation())
Daniel Dunbar523aa602009-01-05 22:55:36 +00007157 return CheckVectorOperands(Loc, lex, rex);
7158 return InvalidOperands(Loc, lex, rex);
7159 }
Steve Naroff90045e82007-07-13 23:32:42 +00007160
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007161 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00007162 if (lex.isInvalid() || rex.isInvalid())
7163 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007164
John Wiegley429bb272011-04-08 18:41:53 +00007165 if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00007166 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007167
Chris Lattner7ef655a2010-01-12 21:23:57 +00007168 // Check for remainder by zero.
John Wiegley429bb272011-04-08 18:41:53 +00007169 if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
7170 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
7171 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007172
Chris Lattner7ef655a2010-01-12 21:23:57 +00007173 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00007174}
7175
Chris Lattner7ef655a2010-01-12 21:23:57 +00007176QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00007177 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
7178 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00007179 QualType compType = CheckVectorOperands(Loc, lex, rex);
7180 if (CompLHSTy) *CompLHSTy = compType;
7181 return compType;
7182 }
Steve Naroff49b45262007-07-13 16:58:59 +00007183
Eli Friedmanab3a8522009-03-28 01:22:36 +00007184 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00007185 if (lex.isInvalid() || rex.isInvalid())
7186 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00007187
Reid Spencer5f016e22007-07-11 17:01:13 +00007188 // handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00007189 if (lex.get()->getType()->isArithmeticType() &&
7190 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00007191 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007192 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00007193 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007194
Eli Friedmand72d16e2008-05-18 18:08:51 +00007195 // Put any potential pointer into PExp
John Wiegley429bb272011-04-08 18:41:53 +00007196 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00007197 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00007198 std::swap(PExp, IExp);
7199
Steve Naroff58f9f2c2009-07-14 18:25:06 +00007200 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00007201
Eli Friedmand72d16e2008-05-18 18:08:51 +00007202 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00007203 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00007204
Chris Lattnerb5f15622009-04-24 23:50:08 +00007205 // Check for arithmetic on pointers to incomplete types.
7206 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00007207 if (getLangOptions().CPlusPlus) {
7208 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley429bb272011-04-08 18:41:53 +00007209 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007210 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00007211 }
Douglas Gregore7450f52009-03-24 19:52:54 +00007212
7213 // GNU extension: arithmetic on pointer to void
7214 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley429bb272011-04-08 18:41:53 +00007215 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00007216 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00007217 if (getLangOptions().CPlusPlus) {
7218 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley429bb272011-04-08 18:41:53 +00007219 << lex.get()->getType() << lex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00007220 return QualType();
7221 }
7222
7223 // GNU extension: arithmetic on pointer to function
7224 Diag(Loc, diag::ext_gnu_ptr_func_arith)
John Wiegley429bb272011-04-08 18:41:53 +00007225 << lex.get()->getType() << lex.get()->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00007226 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00007227 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00007228 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00007229 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00007230 PExp->getType()->isObjCObjectPointerType()) &&
7231 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00007232 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
7233 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00007234 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00007235 return QualType();
7236 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00007237 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00007238 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00007239 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
7240 << PointeeTy << PExp->getSourceRange();
7241 return QualType();
7242 }
Mike Stump1eb44332009-09-09 15:08:12 +00007243
Eli Friedmanab3a8522009-03-28 01:22:36 +00007244 if (CompLHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00007245 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman04e83572009-08-20 04:21:42 +00007246 if (LHSTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +00007247 LHSTy = lex.get()->getType();
Eli Friedman04e83572009-08-20 04:21:42 +00007248 if (LHSTy->isPromotableIntegerType())
7249 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00007250 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00007251 *CompLHSTy = LHSTy;
7252 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00007253 return PExp->getType();
7254 }
7255 }
7256
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007257 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007258}
7259
Chris Lattnereca7be62008-04-07 05:30:13 +00007260// C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00007261QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00007262 SourceLocation Loc, QualType* CompLHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00007263 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00007264 QualType compType = CheckVectorOperands(Loc, lex, rex);
7265 if (CompLHSTy) *CompLHSTy = compType;
7266 return compType;
7267 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007268
Eli Friedmanab3a8522009-03-28 01:22:36 +00007269 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00007270 if (lex.isInvalid() || rex.isInvalid())
7271 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007272
Chris Lattner6e4ab612007-12-09 21:53:25 +00007273 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007274
Chris Lattner6e4ab612007-12-09 21:53:25 +00007275 // Handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00007276 if (lex.get()->getType()->isArithmeticType() &&
7277 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00007278 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007279 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00007280 }
Mike Stump1eb44332009-09-09 15:08:12 +00007281
Chris Lattner6e4ab612007-12-09 21:53:25 +00007282 // Either ptr - int or ptr - ptr.
John Wiegley429bb272011-04-08 18:41:53 +00007283 if (lex.get()->getType()->isAnyPointerType()) {
7284 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007285
Douglas Gregore7450f52009-03-24 19:52:54 +00007286 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00007287
Douglas Gregore7450f52009-03-24 19:52:54 +00007288 bool ComplainAboutVoid = false;
7289 Expr *ComplainAboutFunc = 0;
7290 if (lpointee->isVoidType()) {
7291 if (getLangOptions().CPlusPlus) {
7292 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley429bb272011-04-08 18:41:53 +00007293 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00007294 return QualType();
7295 }
7296
7297 // GNU C extension: arithmetic on pointer to void
7298 ComplainAboutVoid = true;
7299 } else if (lpointee->isFunctionType()) {
7300 if (getLangOptions().CPlusPlus) {
7301 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley429bb272011-04-08 18:41:53 +00007302 << lex.get()->getType() << lex.get()->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00007303 return QualType();
7304 }
Douglas Gregore7450f52009-03-24 19:52:54 +00007305
7306 // GNU C extension: arithmetic on pointer to function
John Wiegley429bb272011-04-08 18:41:53 +00007307 ComplainAboutFunc = lex.get();
Douglas Gregore7450f52009-03-24 19:52:54 +00007308 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00007309 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00007310 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley429bb272011-04-08 18:41:53 +00007311 << lex.get()->getSourceRange()
7312 << lex.get()->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00007313 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00007314
Chris Lattnerb5f15622009-04-24 23:50:08 +00007315 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00007316 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00007317 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley429bb272011-04-08 18:41:53 +00007318 << lpointee << lex.get()->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00007319 return QualType();
7320 }
Mike Stump1eb44332009-09-09 15:08:12 +00007321
Chris Lattner6e4ab612007-12-09 21:53:25 +00007322 // The result type of a pointer-int computation is the pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00007323 if (rex.get()->getType()->isIntegerType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00007324 if (ComplainAboutVoid)
7325 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley429bb272011-04-08 18:41:53 +00007326 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00007327 if (ComplainAboutFunc)
7328 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00007329 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00007330 << ComplainAboutFunc->getSourceRange();
7331
John Wiegley429bb272011-04-08 18:41:53 +00007332 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
7333 return lex.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00007334 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007335
Chris Lattner6e4ab612007-12-09 21:53:25 +00007336 // Handle pointer-pointer subtractions.
John Wiegley429bb272011-04-08 18:41:53 +00007337 if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00007338 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007339
Douglas Gregore7450f52009-03-24 19:52:54 +00007340 // RHS must be a completely-type object type.
7341 // Handle the GNU void* extension.
7342 if (rpointee->isVoidType()) {
7343 if (getLangOptions().CPlusPlus) {
7344 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley429bb272011-04-08 18:41:53 +00007345 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00007346 return QualType();
7347 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007348
Douglas Gregore7450f52009-03-24 19:52:54 +00007349 ComplainAboutVoid = true;
7350 } else if (rpointee->isFunctionType()) {
7351 if (getLangOptions().CPlusPlus) {
7352 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley429bb272011-04-08 18:41:53 +00007353 << rex.get()->getType() << rex.get()->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00007354 return QualType();
7355 }
Douglas Gregore7450f52009-03-24 19:52:54 +00007356
7357 // GNU extension: arithmetic on pointer to function
7358 if (!ComplainAboutFunc)
John Wiegley429bb272011-04-08 18:41:53 +00007359 ComplainAboutFunc = rex.get();
Douglas Gregore7450f52009-03-24 19:52:54 +00007360 } else if (!rpointee->isDependentType() &&
7361 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00007362 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley429bb272011-04-08 18:41:53 +00007363 << rex.get()->getSourceRange()
7364 << rex.get()->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00007365 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007366
Eli Friedman88d936b2009-05-16 13:54:38 +00007367 if (getLangOptions().CPlusPlus) {
7368 // Pointee types must be the same: C++ [expr.add]
7369 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7370 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley429bb272011-04-08 18:41:53 +00007371 << lex.get()->getType() << rex.get()->getType()
7372 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman88d936b2009-05-16 13:54:38 +00007373 return QualType();
7374 }
7375 } else {
7376 // Pointee types must be compatible C99 6.5.6p3
7377 if (!Context.typesAreCompatible(
7378 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7379 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7380 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley429bb272011-04-08 18:41:53 +00007381 << lex.get()->getType() << rex.get()->getType()
7382 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman88d936b2009-05-16 13:54:38 +00007383 return QualType();
7384 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00007385 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007386
Douglas Gregore7450f52009-03-24 19:52:54 +00007387 if (ComplainAboutVoid)
7388 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley429bb272011-04-08 18:41:53 +00007389 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00007390 if (ComplainAboutFunc)
7391 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00007392 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00007393 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00007394
John Wiegley429bb272011-04-08 18:41:53 +00007395 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00007396 return Context.getPointerDiffType();
7397 }
7398 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007399
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007400 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007401}
7402
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007403static bool isScopedEnumerationType(QualType T) {
7404 if (const EnumType *ET = dyn_cast<EnumType>(T))
7405 return ET->getDecl()->isScoped();
7406 return false;
7407}
7408
John Wiegley429bb272011-04-08 18:41:53 +00007409static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth21206d52011-02-23 23:34:11 +00007410 SourceLocation Loc, unsigned Opc,
7411 QualType LHSTy) {
7412 llvm::APSInt Right;
7413 // Check right/shifter operand
John Wiegley429bb272011-04-08 18:41:53 +00007414 if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00007415 return;
7416
7417 if (Right.isNegative()) {
John Wiegley429bb272011-04-08 18:41:53 +00007418 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00007419 S.PDiag(diag::warn_shift_negative)
John Wiegley429bb272011-04-08 18:41:53 +00007420 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00007421 return;
7422 }
7423 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley429bb272011-04-08 18:41:53 +00007424 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00007425 if (Right.uge(LeftBits)) {
John Wiegley429bb272011-04-08 18:41:53 +00007426 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00007427 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley429bb272011-04-08 18:41:53 +00007428 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00007429 return;
7430 }
7431 if (Opc != BO_Shl)
7432 return;
7433
7434 // When left shifting an ICE which is signed, we can check for overflow which
7435 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7436 // integers have defined behavior modulo one more than the maximum value
7437 // representable in the result type, so never warn for those.
7438 llvm::APSInt Left;
John Wiegley429bb272011-04-08 18:41:53 +00007439 if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth21206d52011-02-23 23:34:11 +00007440 LHSTy->hasUnsignedIntegerRepresentation())
7441 return;
7442 llvm::APInt ResultBits =
7443 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7444 if (LeftBits.uge(ResultBits))
7445 return;
7446 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7447 Result = Result.shl(Right);
7448
Ted Kremenekfa821382011-06-15 00:54:52 +00007449 // Print the bit representation of the signed integer as an unsigned
7450 // hexadecimal number.
7451 llvm::SmallString<40> HexResult;
7452 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7453
Chandler Carruth21206d52011-02-23 23:34:11 +00007454 // If we are only missing a sign bit, this is less likely to result in actual
7455 // bugs -- if the result is cast back to an unsigned type, it will have the
7456 // expected value. Thus we place this behind a different warning that can be
7457 // turned off separately if needed.
7458 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00007459 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
7460 << HexResult.str() << LHSTy
John Wiegley429bb272011-04-08 18:41:53 +00007461 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00007462 return;
7463 }
7464
7465 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Ted Kremenekfa821382011-06-15 00:54:52 +00007466 << HexResult.str() << Result.getMinSignedBits() << LHSTy
John Wiegley429bb272011-04-08 18:41:53 +00007467 << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00007468}
7469
Chris Lattnereca7be62008-04-07 05:30:13 +00007470// C99 6.5.7
John Wiegley429bb272011-04-08 18:41:53 +00007471QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Chandler Carruth21206d52011-02-23 23:34:11 +00007472 unsigned Opc, bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00007473 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley429bb272011-04-08 18:41:53 +00007474 if (!lex.get()->getType()->hasIntegerRepresentation() ||
7475 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007476 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007477
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007478 // C++0x: Don't allow scoped enums. FIXME: Use something better than
7479 // hasIntegerRepresentation() above instead of this.
John Wiegley429bb272011-04-08 18:41:53 +00007480 if (isScopedEnumerationType(lex.get()->getType()) ||
7481 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007482 return InvalidOperands(Loc, lex, rex);
7483 }
7484
Nate Begeman2207d792009-10-25 02:26:48 +00007485 // Vector shifts promote their scalar inputs to vector type.
John Wiegley429bb272011-04-08 18:41:53 +00007486 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Nate Begeman2207d792009-10-25 02:26:48 +00007487 return CheckVectorOperands(Loc, lex, rex);
7488
Chris Lattnerca5eede2007-12-12 05:47:28 +00007489 // Shifts don't perform usual arithmetic conversions, they just do integer
7490 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00007491
John McCall1bc80af2010-12-16 19:28:59 +00007492 // For the LHS, do usual unary conversions, but then reset them away
7493 // if this is a compound assignment.
John Wiegley429bb272011-04-08 18:41:53 +00007494 ExprResult old_lex = lex;
7495 lex = UsualUnaryConversions(lex.take());
7496 if (lex.isInvalid())
7497 return QualType();
7498 QualType LHSTy = lex.get()->getType();
John McCall1bc80af2010-12-16 19:28:59 +00007499 if (isCompAssign) lex = old_lex;
7500
7501 // The RHS is simpler.
John Wiegley429bb272011-04-08 18:41:53 +00007502 rex = UsualUnaryConversions(rex.take());
7503 if (rex.isInvalid())
7504 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007505
Ryan Flynnd0439682009-08-07 16:20:20 +00007506 // Sanity-check shift operands
Chandler Carruth21206d52011-02-23 23:34:11 +00007507 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnd0439682009-08-07 16:20:20 +00007508
Chris Lattnerca5eede2007-12-12 05:47:28 +00007509 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00007510 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007511}
7512
Chandler Carruth99919472010-07-10 12:30:03 +00007513static bool IsWithinTemplateSpecialization(Decl *D) {
7514 if (DeclContext *DC = D->getDeclContext()) {
7515 if (isa<ClassTemplateSpecializationDecl>(DC))
7516 return true;
7517 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7518 return FD->isFunctionTemplateSpecialization();
7519 }
7520 return false;
7521}
7522
Douglas Gregor0c6db942009-05-04 06:07:12 +00007523// C99 6.5.8, C++ [expr.rel]
John Wiegley429bb272011-04-08 18:41:53 +00007524QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00007525 unsigned OpaqueOpc, bool isRelational) {
John McCall2de56d12010-08-25 11:45:40 +00007526 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00007527
Chris Lattner02dd4b12009-12-05 05:40:13 +00007528 // Handle vector comparisons separately.
John Wiegley429bb272011-04-08 18:41:53 +00007529 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007530 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007531
John Wiegley429bb272011-04-08 18:41:53 +00007532 QualType lType = lex.get()->getType();
7533 QualType rType = rex.get()->getType();
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007534
John Wiegley429bb272011-04-08 18:41:53 +00007535 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
7536 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00007537 QualType LHSStrippedType = LHSStripped->getType();
7538 QualType RHSStrippedType = RHSStripped->getType();
7539
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007540
7541
Chandler Carruth543cb652011-02-17 08:37:06 +00007542 // Two different enums will raise a warning when compared.
7543 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
7544 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
7545 if (LHSEnumType->getDecl()->getIdentifier() &&
7546 RHSEnumType->getDecl()->getIdentifier() &&
7547 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
7548 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7549 << LHSStrippedType << RHSStrippedType
John Wiegley429bb272011-04-08 18:41:53 +00007550 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth543cb652011-02-17 08:37:06 +00007551 }
7552 }
7553 }
7554
Douglas Gregor8eee1192010-06-22 22:12:46 +00007555 if (!lType->hasFloatingRepresentation() &&
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00007556 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley429bb272011-04-08 18:41:53 +00007557 !lex.get()->getLocStart().isMacroID() &&
7558 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00007559 // For non-floating point types, check for self-comparisons of the form
7560 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7561 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00007562 //
7563 // NOTE: Don't warn about comparison expressions resulting from macro
7564 // expansion. Also don't warn about comparisons which are only self
7565 // comparisons within a template specialization. The warnings should catch
7566 // obvious cases in the definition of the template anyways. The idea is to
7567 // warn when the typed comparison operator will always evaluate to the same
7568 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00007569 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00007570 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00007571 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00007572 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00007573 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00007574 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00007575 << (Opc == BO_EQ
7576 || Opc == BO_LE
7577 || Opc == BO_GE));
Douglas Gregord64fdd02010-06-08 19:50:34 +00007578 } else if (lType->isArrayType() && rType->isArrayType() &&
7579 !DRL->getDecl()->getType()->isReferenceType() &&
7580 !DRR->getDecl()->getType()->isReferenceType()) {
7581 // what is it always going to eval to?
7582 char always_evals_to;
7583 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007584 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00007585 always_evals_to = 0; // false
7586 break;
John McCall2de56d12010-08-25 11:45:40 +00007587 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00007588 always_evals_to = 1; // true
7589 break;
7590 default:
7591 // best we can say is 'a constant'
7592 always_evals_to = 2; // e.g. array1 <= array2
7593 break;
7594 }
Ted Kremenek351ba912011-02-23 01:52:04 +00007595 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00007596 << 1 // array
7597 << always_evals_to);
7598 }
7599 }
Chandler Carruth99919472010-07-10 12:30:03 +00007600 }
Mike Stump1eb44332009-09-09 15:08:12 +00007601
Chris Lattner55660a72009-03-08 19:39:53 +00007602 if (isa<CastExpr>(LHSStripped))
7603 LHSStripped = LHSStripped->IgnoreParenCasts();
7604 if (isa<CastExpr>(RHSStripped))
7605 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00007606
Chris Lattner55660a72009-03-08 19:39:53 +00007607 // Warn about comparisons against a string constant (unless the other
7608 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00007609 Expr *literalString = 0;
7610 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00007611 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007612 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007613 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00007614 literalString = lex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007615 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00007616 } else if ((isa<StringLiteral>(RHSStripped) ||
7617 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007618 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007619 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00007620 literalString = rex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007621 literalStringStripped = RHSStripped;
7622 }
7623
7624 if (literalString) {
7625 std::string resultComparison;
7626 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007627 case BO_LT: resultComparison = ") < 0"; break;
7628 case BO_GT: resultComparison = ") > 0"; break;
7629 case BO_LE: resultComparison = ") <= 0"; break;
7630 case BO_GE: resultComparison = ") >= 0"; break;
7631 case BO_EQ: resultComparison = ") == 0"; break;
7632 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregora86b8322009-04-06 18:45:53 +00007633 default: assert(false && "Invalid comparison operator");
7634 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007635
Ted Kremenek351ba912011-02-23 01:52:04 +00007636 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00007637 PDiag(diag::warn_stringcompare)
7638 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00007639 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00007640 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00007641 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007642
Douglas Gregord64fdd02010-06-08 19:50:34 +00007643 // C99 6.5.8p3 / C99 6.5.9p4
John Wiegley429bb272011-04-08 18:41:53 +00007644 if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00007645 UsualArithmeticConversions(lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00007646 if (lex.isInvalid() || rex.isInvalid())
7647 return QualType();
7648 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00007649 else {
John Wiegley429bb272011-04-08 18:41:53 +00007650 lex = UsualUnaryConversions(lex.take());
7651 if (lex.isInvalid())
7652 return QualType();
7653
7654 rex = UsualUnaryConversions(rex.take());
7655 if (rex.isInvalid())
7656 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007657 }
7658
John Wiegley429bb272011-04-08 18:41:53 +00007659 lType = lex.get()->getType();
7660 rType = rex.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007661
Douglas Gregor447b69e2008-11-19 03:25:36 +00007662 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00007663 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00007664
Chris Lattnera5937dd2007-08-26 01:18:55 +00007665 if (isRelational) {
7666 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007667 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007668 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00007669 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007670 if (lType->hasFloatingRepresentation())
John Wiegley429bb272011-04-08 18:41:53 +00007671 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007672
Chris Lattnera5937dd2007-08-26 01:18:55 +00007673 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007674 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007675 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007676
John Wiegley429bb272011-04-08 18:41:53 +00007677 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007678 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00007679 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007680 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007681
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007682 // All of the following pointer-related warnings are GCC extensions, except
7683 // when handling null pointer constants.
Steve Naroff77878cc2007-08-27 04:08:11 +00007684 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00007685 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00007686 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00007687 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00007688 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007689
Douglas Gregor0c6db942009-05-04 06:07:12 +00007690 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00007691 if (LCanPointeeTy == RCanPointeeTy)
7692 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007693 if (!isRelational &&
7694 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7695 // Valid unless comparison between non-null pointer and function pointer
7696 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007697 // In a SFINAE context, we treat this as a hard error to maintain
7698 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007699 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7700 && !LHSIsNull && !RHSIsNull) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007701 Diag(Loc,
7702 isSFINAEContext()?
7703 diag::err_typecheck_comparison_of_fptr_to_void
7704 : diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley429bb272011-04-08 18:41:53 +00007705 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007706
7707 if (isSFINAEContext())
7708 return QualType();
7709
John Wiegley429bb272011-04-08 18:41:53 +00007710 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007711 return ResultTy;
7712 }
7713 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007714
Douglas Gregor0c6db942009-05-04 06:07:12 +00007715 // C++ [expr.rel]p2:
7716 // [...] Pointer conversions (4.10) and qualification
7717 // conversions (4.4) are performed on pointer operands (or on
7718 // a pointer operand and a null pointer constant) to bring
7719 // them to their composite pointer type. [...]
7720 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00007721 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00007722 // comparisons of pointers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007723 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00007724 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007725 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor0c6db942009-05-04 06:07:12 +00007726 if (T.isNull()) {
7727 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007728 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00007729 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007730 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007731 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007732 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007733 << lType << rType << T
John Wiegley429bb272011-04-08 18:41:53 +00007734 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00007735 }
7736
John Wiegley429bb272011-04-08 18:41:53 +00007737 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7738 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00007739 return ResultTy;
7740 }
Eli Friedman3075e762009-08-23 00:27:47 +00007741 // C99 6.5.9p2 and C99 6.5.8p2
7742 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7743 RCanPointeeTy.getUnqualifiedType())) {
7744 // Valid unless a relational comparison of function pointers
7745 if (isRelational && LCanPointeeTy->isFunctionType()) {
7746 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007747 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007748 }
7749 } else if (!isRelational &&
7750 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7751 // Valid unless comparison between non-null pointer and function pointer
7752 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7753 && !LHSIsNull && !RHSIsNull) {
7754 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley429bb272011-04-08 18:41:53 +00007755 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007756 }
7757 } else {
7758 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007759 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007760 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007761 }
John McCall34d6f932011-03-11 04:25:25 +00007762 if (LCanPointeeTy != RCanPointeeTy) {
7763 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007764 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007765 else
John Wiegley429bb272011-04-08 18:41:53 +00007766 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007767 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00007768 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00007769 }
Mike Stump1eb44332009-09-09 15:08:12 +00007770
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007771 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007772 // Comparison of nullptr_t with itself.
7773 if (lType->isNullPtrType() && rType->isNullPtrType())
7774 return ResultTy;
7775
Mike Stump1eb44332009-09-09 15:08:12 +00007776 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00007777 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00007778 if (RHSIsNull &&
Douglas Gregor17e37c72011-06-01 15:12:24 +00007779 ((lType->isAnyPointerType() || lType->isNullPtrType()) ||
Douglas Gregor16cd4b72011-06-16 18:52:05 +00007780 (!isRelational &&
7781 (lType->isMemberPointerType() || lType->isBlockPointerType())))) {
John Wiegley429bb272011-04-08 18:41:53 +00007782 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregor443c2122010-08-07 13:36:37 +00007783 lType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007784 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007785 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007786 return ResultTy;
7787 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007788 if (LHSIsNull &&
Douglas Gregor17e37c72011-06-01 15:12:24 +00007789 ((rType->isAnyPointerType() || rType->isNullPtrType()) ||
Douglas Gregor16cd4b72011-06-16 18:52:05 +00007790 (!isRelational &&
7791 (rType->isMemberPointerType() || rType->isBlockPointerType())))) {
John Wiegley429bb272011-04-08 18:41:53 +00007792 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregor443c2122010-08-07 13:36:37 +00007793 rType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007794 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007795 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007796 return ResultTy;
7797 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007798
7799 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00007800 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00007801 lType->isMemberPointerType() && rType->isMemberPointerType()) {
7802 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00007803 // In addition, pointers to members can be compared, or a pointer to
7804 // member and a null pointer constant. Pointer to member conversions
7805 // (4.11) and qualification conversions (4.4) are performed to bring
7806 // them to a common type. If one operand is a null pointer constant,
7807 // the common type is the type of the other operand. Otherwise, the
7808 // common type is a pointer to member type similar (4.4) to the type
7809 // of one of the operands, with a cv-qualification signature (4.4)
7810 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00007811 // types.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007812 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00007813 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007814 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor20b3e992009-08-24 17:42:35 +00007815 if (T.isNull()) {
7816 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007817 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00007818 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007819 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007820 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007821 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007822 << lType << rType << T
John Wiegley429bb272011-04-08 18:41:53 +00007823 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00007824 }
Mike Stump1eb44332009-09-09 15:08:12 +00007825
John Wiegley429bb272011-04-08 18:41:53 +00007826 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7827 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00007828 return ResultTy;
7829 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007830
7831 // Handle scoped enumeration types specifically, since they don't promote
7832 // to integers.
John Wiegley429bb272011-04-08 18:41:53 +00007833 if (lex.get()->getType()->isEnumeralType() &&
7834 Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00007835 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007836 }
Mike Stump1eb44332009-09-09 15:08:12 +00007837
Steve Naroff1c7d0672008-09-04 15:10:53 +00007838 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00007839 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00007840 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7841 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007842
Steve Naroff1c7d0672008-09-04 15:10:53 +00007843 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00007844 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007845 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley429bb272011-04-08 18:41:53 +00007846 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00007847 }
John Wiegley429bb272011-04-08 18:41:53 +00007848 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007849 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007850 }
John Wiegley429bb272011-04-08 18:41:53 +00007851
Steve Naroff59f53942008-09-28 01:11:11 +00007852 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00007853 if (!isRelational
7854 && ((lType->isBlockPointerType() && rType->isPointerType())
7855 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00007856 if (!LHSIsNull && !RHSIsNull) {
John McCall34d6f932011-03-11 04:25:25 +00007857 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007858 ->getPointeeType()->isVoidType())
John McCall34d6f932011-03-11 04:25:25 +00007859 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007860 ->getPointeeType()->isVoidType())))
7861 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley429bb272011-04-08 18:41:53 +00007862 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00007863 }
John McCall34d6f932011-03-11 04:25:25 +00007864 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007865 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007866 else
John Wiegley429bb272011-04-08 18:41:53 +00007867 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007868 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00007869 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00007870
John McCall34d6f932011-03-11 04:25:25 +00007871 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
7872 const PointerType *LPT = lType->getAs<PointerType>();
7873 const PointerType *RPT = rType->getAs<PointerType>();
7874 if (LPT || RPT) {
7875 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7876 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007877
Steve Naroffa8069f12008-11-17 19:49:16 +00007878 if (!LPtrToVoid && !RPtrToVoid &&
7879 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007880 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007881 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00007882 }
John McCall34d6f932011-03-11 04:25:25 +00007883 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007884 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007885 else
John Wiegley429bb272011-04-08 18:41:53 +00007886 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007887 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00007888 }
Steve Naroff14108da2009-07-10 23:34:53 +00007889 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007890 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00007891 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007892 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
John McCall34d6f932011-03-11 04:25:25 +00007893 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007894 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007895 else
John Wiegley429bb272011-04-08 18:41:53 +00007896 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007897 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00007898 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00007899 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007900 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7901 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007902 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007903 bool isError = false;
7904 if ((LHSIsNull && lType->isIntegerType()) ||
7905 (RHSIsNull && rType->isIntegerType())) {
7906 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007907 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007908 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007909 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007910 else if (getLangOptions().CPlusPlus) {
7911 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7912 isError = true;
7913 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007914 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007915
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007916 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007917 Diag(Loc, DiagID)
John Wiegley429bb272011-04-08 18:41:53 +00007918 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007919 if (isError)
7920 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007921 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007922
7923 if (lType->isIntegerType())
John Wiegley429bb272011-04-08 18:41:53 +00007924 lex = ImpCastExprToType(lex.take(), rType,
John McCall404cd162010-11-13 01:35:44 +00007925 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007926 else
John Wiegley429bb272011-04-08 18:41:53 +00007927 rex = ImpCastExprToType(rex.take(), lType,
John McCall404cd162010-11-13 01:35:44 +00007928 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007929 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007930 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007931
Steve Naroff39218df2008-09-04 16:56:14 +00007932 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00007933 if (!isRelational && RHSIsNull
7934 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00007935 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007936 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007937 }
Mike Stumpaf199f32009-05-07 18:43:07 +00007938 if (!isRelational && LHSIsNull
7939 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00007940 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007941 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007942 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007943
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007944 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007945}
7946
Nate Begemanbe2341d2008-07-14 18:02:46 +00007947/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007948/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007949/// like a scalar comparison, a vector comparison produces a vector of integer
7950/// types.
John Wiegley429bb272011-04-08 18:41:53 +00007951QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007952 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007953 bool isRelational) {
7954 // Check to make sure we're operating on vectors of the same type and width,
7955 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007956 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007957 if (vType.isNull())
7958 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007959
John Wiegley429bb272011-04-08 18:41:53 +00007960 QualType lType = lex.get()->getType();
7961 QualType rType = rex.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007962
Anton Yartsev7870b132011-03-27 15:36:07 +00007963 // If AltiVec, the comparison results in a numeric type, i.e.
7964 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00007965 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00007966 return Context.getLogicalOperationType();
7967
Nate Begemanbe2341d2008-07-14 18:02:46 +00007968 // For non-floating point types, check for self-comparisons of the form
7969 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7970 // often indicate logic errors in the program.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007971 if (!lType->hasFloatingRepresentation()) {
John Wiegley429bb272011-04-08 18:41:53 +00007972 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
7973 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007974 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00007975 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00007976 PDiag(diag::warn_comparison_always)
7977 << 0 // self-
7978 << 2 // "a constant"
7979 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007980 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007981
Nate Begemanbe2341d2008-07-14 18:02:46 +00007982 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007983 if (!isRelational && lType->hasFloatingRepresentation()) {
7984 assert (rType->hasFloatingRepresentation());
John Wiegley429bb272011-04-08 18:41:53 +00007985 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007986 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007987
Nate Begemanbe2341d2008-07-14 18:02:46 +00007988 // Return the type for the comparison, which is the same as vector type for
7989 // integer vectors, or an integer type of identical size and number of
7990 // elements for floating point vectors.
Douglas Gregorf6094622010-07-23 15:58:24 +00007991 if (lType->hasIntegerRepresentation())
Nate Begemanbe2341d2008-07-14 18:02:46 +00007992 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007993
John McCall183700f2009-09-21 23:43:11 +00007994 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00007995 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00007996 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007997 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00007998 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00007999 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
8000
Mike Stumpeed9cac2009-02-19 03:04:26 +00008001 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00008002 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00008003 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
8004}
8005
Reid Spencer5f016e22007-07-11 17:01:13 +00008006inline QualType Sema::CheckBitwiseOperands(
John Wiegley429bb272011-04-08 18:41:53 +00008007 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
8008 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
8009 if (lex.get()->getType()->hasIntegerRepresentation() &&
8010 rex.get()->getType()->hasIntegerRepresentation())
Douglas Gregorf6094622010-07-23 15:58:24 +00008011 return CheckVectorOperands(Loc, lex, rex);
8012
8013 return InvalidOperands(Loc, lex, rex);
8014 }
Steve Naroff90045e82007-07-13 23:32:42 +00008015
John Wiegley429bb272011-04-08 18:41:53 +00008016 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
8017 QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
8018 if (lexResult.isInvalid() || rexResult.isInvalid())
8019 return QualType();
8020 lex = lexResult.take();
8021 rex = rexResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00008022
John Wiegley429bb272011-04-08 18:41:53 +00008023 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
8024 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00008025 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008026 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00008027}
8028
8029inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley429bb272011-04-08 18:41:53 +00008030 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00008031
8032 // Diagnose cases where the user write a logical and/or but probably meant a
8033 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
8034 // is a constant.
John Wiegley429bb272011-04-08 18:41:53 +00008035 if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
8036 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Chris Lattner23ef3e42010-07-15 00:26:43 +00008037 // Don't warn in macros.
Chris Lattnerb7690b42010-07-24 01:10:11 +00008038 !Loc.isMacroID()) {
8039 // If the RHS can be constant folded, and if it constant folds to something
8040 // that isn't 0 or 1 (which indicate a potential logical operation that
8041 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00008042 // Parens on the RHS are ignored.
Chris Lattnerb7690b42010-07-24 01:10:11 +00008043 Expr::EvalResult Result;
Chandler Carruth0683a142011-05-31 05:41:42 +00008044 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
8045 if ((getLangOptions().Bool && !rex.get()->getType()->isBooleanType()) ||
8046 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
8047 Diag(Loc, diag::warn_logical_instead_of_bitwise)
8048 << rex.get()->getSourceRange()
8049 << (Opc == BO_LAnd ? "&&" : "||")
8050 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattnerb7690b42010-07-24 01:10:11 +00008051 }
8052 }
Chris Lattner90a8f272010-07-13 19:41:32 +00008053
Anders Carlssona4c98cd2009-11-23 21:47:44 +00008054 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00008055 lex = UsualUnaryConversions(lex.take());
8056 if (lex.isInvalid())
8057 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00008058
John Wiegley429bb272011-04-08 18:41:53 +00008059 rex = UsualUnaryConversions(rex.take());
8060 if (rex.isInvalid())
8061 return QualType();
8062
8063 if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00008064 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008065
Anders Carlssona4c98cd2009-11-23 21:47:44 +00008066 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00008067 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008068
John McCall75f7c0f2010-06-04 00:29:51 +00008069 // The following is safe because we only use this method for
8070 // non-overloadable operands.
8071
Anders Carlssona4c98cd2009-11-23 21:47:44 +00008072 // C++ [expr.log.and]p1
8073 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00008074 // The operands are both contextually converted to type bool.
John Wiegley429bb272011-04-08 18:41:53 +00008075 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
8076 if (lexRes.isInvalid())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00008077 return InvalidOperands(Loc, lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00008078 lex = move(lexRes);
8079
8080 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
8081 if (rexRes.isInvalid())
8082 return InvalidOperands(Loc, lex, rex);
8083 rex = move(rexRes);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008084
Anders Carlssona4c98cd2009-11-23 21:47:44 +00008085 // C++ [expr.log.and]p2
8086 // C++ [expr.log.or]p2
8087 // The result is a bool.
8088 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00008089}
8090
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00008091/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
8092/// is a read-only property; return true if so. A readonly property expression
8093/// depends on various declarations and thus must be treated specially.
8094///
Mike Stump1eb44332009-09-09 15:08:12 +00008095static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00008096 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
8097 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCall12f78a62010-12-02 01:19:52 +00008098 if (PropExpr->isImplicitProperty()) return false;
8099
8100 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
8101 QualType BaseType = PropExpr->isSuperReceiver() ?
8102 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00008103 PropExpr->getBase()->getType();
8104
John McCall12f78a62010-12-02 01:19:52 +00008105 if (const ObjCObjectPointerType *OPT =
8106 BaseType->getAsObjCInterfacePointerType())
8107 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
8108 if (S.isPropertyReadonly(PDecl, IFace))
8109 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00008110 }
8111 return false;
8112}
8113
Fariborz Jahanian14086762011-03-28 23:47:18 +00008114static bool IsConstProperty(Expr *E, Sema &S) {
8115 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
8116 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
8117 if (PropExpr->isImplicitProperty()) return false;
8118
8119 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
8120 QualType T = PDecl->getType();
8121 if (T->isReferenceType())
Fariborz Jahanian61750f22011-03-30 16:59:30 +00008122 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanian14086762011-03-28 23:47:18 +00008123 CanQualType CT = S.Context.getCanonicalType(T);
8124 return CT.isConstQualified();
8125 }
8126 return false;
8127}
8128
Fariborz Jahanian077f4902011-03-26 19:48:30 +00008129static bool IsReadonlyMessage(Expr *E, Sema &S) {
8130 if (E->getStmtClass() != Expr::MemberExprClass)
8131 return false;
8132 const MemberExpr *ME = cast<MemberExpr>(E);
8133 NamedDecl *Member = ME->getMemberDecl();
8134 if (isa<FieldDecl>(Member)) {
8135 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
8136 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
8137 return false;
8138 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
8139 }
8140 return false;
8141}
8142
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008143/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
8144/// emit an error and return true. If so, return false.
8145static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00008146 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00008147 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00008148 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00008149 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
8150 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian14086762011-03-28 23:47:18 +00008151 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
8152 IsLV = Expr::MLV_Valid;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00008153 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
8154 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008155 if (IsLV == Expr::MLV_Valid)
8156 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008157
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008158 unsigned Diag = 0;
8159 bool NeedType = false;
8160 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00008161 case Expr::MLV_ConstQualified:
8162 Diag = diag::err_typecheck_assign_const;
8163
John McCall7acddac2011-06-17 06:42:21 +00008164 // In ARC, use some specialized diagnostics for occasions where we
8165 // infer 'const'. These are always pseudo-strong variables.
John McCallf85e1932011-06-15 23:02:42 +00008166 if (S.getLangOptions().ObjCAutoRefCount) {
8167 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
8168 if (declRef && isa<VarDecl>(declRef->getDecl())) {
8169 VarDecl *var = cast<VarDecl>(declRef->getDecl());
8170
John McCall7acddac2011-06-17 06:42:21 +00008171 // Use the normal diagnostic if it's pseudo-__strong but the
8172 // user actually wrote 'const'.
8173 if (var->isARCPseudoStrong() &&
8174 (!var->getTypeSourceInfo() ||
8175 !var->getTypeSourceInfo()->getType().isConstQualified())) {
8176 // There are two pseudo-strong cases:
8177 // - self
John McCallf85e1932011-06-15 23:02:42 +00008178 ObjCMethodDecl *method = S.getCurMethodDecl();
8179 if (method && var == method->getSelfDecl())
8180 Diag = diag::err_typecheck_arr_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00008181
8182 // - fast enumeration variables
8183 else
John McCallf85e1932011-06-15 23:02:42 +00008184 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00008185
John McCallf85e1932011-06-15 23:02:42 +00008186 SourceRange Assign;
8187 if (Loc != OrigLoc)
8188 Assign = SourceRange(OrigLoc, OrigLoc);
8189 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8190 // We need to preserve the AST regardless, so migration tool
8191 // can do its job.
8192 return false;
8193 }
8194 }
8195 }
8196
8197 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008198 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008199 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
8200 NeedType = true;
8201 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008202 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008203 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
8204 NeedType = true;
8205 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00008206 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008207 Diag = diag::err_typecheck_lvalue_casts_not_supported;
8208 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00008209 case Expr::MLV_Valid:
8210 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00008211 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00008212 case Expr::MLV_MemberFunction:
8213 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008214 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
8215 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008216 case Expr::MLV_IncompleteType:
8217 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00008218 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008219 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00008220 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00008221 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008222 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
8223 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00008224 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008225 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
8226 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00008227 case Expr::MLV_ReadonlyProperty:
8228 Diag = diag::error_readonly_property_assignment;
8229 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00008230 case Expr::MLV_NoSetterProperty:
8231 Diag = diag::error_nosetter_property_assignment;
8232 break;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00008233 case Expr::MLV_InvalidMessageExpression:
8234 Diag = diag::error_readonly_message_assignment;
8235 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00008236 case Expr::MLV_SubObjCPropertySetting:
8237 Diag = diag::error_no_subobject_property_setting;
8238 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008239 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00008240
Daniel Dunbar44e35f72009-04-15 00:08:05 +00008241 SourceRange Assign;
8242 if (Loc != OrigLoc)
8243 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008244 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00008245 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008246 else
Mike Stump1eb44332009-09-09 15:08:12 +00008247 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008248 return true;
8249}
8250
8251
8252
8253// C99 6.5.16.1
John Wiegley429bb272011-04-08 18:41:53 +00008254QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008255 SourceLocation Loc,
8256 QualType CompoundType) {
8257 // Verify that LHS is a modifiable lvalue, and emit error if not.
8258 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00008259 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008260
8261 QualType LHSType = LHS->getType();
John Wiegley429bb272011-04-08 18:41:53 +00008262 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008263 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008264 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00008265 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00008266 // Simple assignment "x = y".
John Wiegley429bb272011-04-08 18:41:53 +00008267 if (LHS->getObjectKind() == OK_ObjCProperty) {
8268 ExprResult LHSResult = Owned(LHS);
8269 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
8270 if (LHSResult.isInvalid())
8271 return QualType();
8272 LHS = LHSResult.take();
8273 }
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00008274 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00008275 if (RHS.isInvalid())
8276 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00008277 // Special case of NSObject attributes on c-style pointer types.
8278 if (ConvTy == IncompatiblePointer &&
8279 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00008280 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00008281 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00008282 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00008283 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008284
John McCallf89e55a2010-11-18 06:31:45 +00008285 if (ConvTy == Compatible &&
8286 getLangOptions().ObjCNonFragileABI &&
8287 LHSType->isObjCObjectType())
8288 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
8289 << LHSType;
8290
Chris Lattner2c156472008-08-21 18:04:13 +00008291 // If the RHS is a unary plus or minus, check to see if they = and + are
8292 // right next to each other. If so, the user may have typo'd "x =+ 4"
8293 // instead of "x += 4".
John Wiegley429bb272011-04-08 18:41:53 +00008294 Expr *RHSCheck = RHS.get();
Chris Lattner2c156472008-08-21 18:04:13 +00008295 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8296 RHSCheck = ICE->getSubExpr();
8297 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00008298 if ((UO->getOpcode() == UO_Plus ||
8299 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008300 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00008301 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00008302 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
8303 // And there is a space or other character before the subexpr of the
8304 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00008305 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
8306 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008307 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00008308 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008309 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00008310 }
Chris Lattner2c156472008-08-21 18:04:13 +00008311 }
John McCallf85e1932011-06-15 23:02:42 +00008312
8313 if (ConvTy == Compatible) {
8314 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
8315 checkRetainCycles(LHS, RHS.get());
8316 else
8317 checkUnsafeAssigns(Loc, LHSType, RHS.get());
8318 }
Chris Lattner2c156472008-08-21 18:04:13 +00008319 } else {
8320 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00008321 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00008322 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00008323
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008324 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00008325 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00008326 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00008327
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +00008328 CheckForNullPointerDereference(*this, LHS);
Ted Kremeneka0125d82011-02-16 01:57:07 +00008329 // Check for trivial buffer overflows.
Ted Kremenek3aea4da2011-03-01 18:41:00 +00008330 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremeneka0125d82011-02-16 01:57:07 +00008331
Reid Spencer5f016e22007-07-11 17:01:13 +00008332 // C99 6.5.16p3: The type of an assignment expression is the type of the
8333 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00008334 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00008335 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8336 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008337 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00008338 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00008339 return (getLangOptions().CPlusPlus
8340 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008341}
8342
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008343// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00008344static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00008345 SourceLocation Loc) {
John Wiegley429bb272011-04-08 18:41:53 +00008346 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00008347
John McCallfb8721c2011-04-10 19:13:55 +00008348 LHS = S.CheckPlaceholderExpr(LHS.take());
8349 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00008350 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00008351 return QualType();
8352
John McCallcf2e5062010-10-12 07:14:40 +00008353 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8354 // operands, but not unary promotions.
8355 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008356
John McCallf6a16482010-12-04 03:47:34 +00008357 // So we treat the LHS as a ignored value, and in C++ we allow the
8358 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00008359 LHS = S.IgnoredValueConversions(LHS.take());
8360 if (LHS.isInvalid())
8361 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00008362
8363 if (!S.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00008364 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8365 if (RHS.isInvalid())
8366 return QualType();
8367 if (!RHS.get()->getType()->isVoidType())
8368 S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00008369 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008370
John Wiegley429bb272011-04-08 18:41:53 +00008371 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008372}
8373
Steve Naroff49b45262007-07-13 16:58:59 +00008374/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8375/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00008376static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8377 ExprValueKind &VK,
8378 SourceLocation OpLoc,
8379 bool isInc, bool isPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00008380 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008381 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008382
Chris Lattner3528d352008-11-21 07:05:48 +00008383 QualType ResType = Op->getType();
8384 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008385
John McCall09431682010-11-18 19:01:18 +00008386 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00008387 // Decrement of bool is not allowed.
8388 if (!isInc) {
John McCall09431682010-11-18 19:01:18 +00008389 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00008390 return QualType();
8391 }
8392 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00008393 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00008394 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00008395 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00008396 } else if (ResType->isAnyPointerType()) {
8397 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00008398
Chris Lattner3528d352008-11-21 07:05:48 +00008399 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00008400 if (PointeeTy->isVoidType()) {
John McCall09431682010-11-18 19:01:18 +00008401 if (S.getLangOptions().CPlusPlus) {
8402 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00008403 << Op->getSourceRange();
8404 return QualType();
8405 }
8406
8407 // Pointer to void is a GNU extension in C.
John McCall09431682010-11-18 19:01:18 +00008408 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00008409 } else if (PointeeTy->isFunctionType()) {
John McCall09431682010-11-18 19:01:18 +00008410 if (S.getLangOptions().CPlusPlus) {
8411 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00008412 << Op->getType() << Op->getSourceRange();
8413 return QualType();
8414 }
8415
John McCall09431682010-11-18 19:01:18 +00008416 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00008417 << ResType << Op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00008418 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
8419 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00008420 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00008421 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00008422 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00008423 // Diagnose bad cases where we step over interface counts.
John McCall09431682010-11-18 19:01:18 +00008424 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
8425 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00008426 << PointeeTy << Op->getSourceRange();
8427 return QualType();
8428 }
Eli Friedman5b088a12010-01-03 00:20:48 +00008429 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00008430 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00008431 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00008432 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008433 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008434 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008435 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008436 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8437 isInc, isPrefix);
Anton Yartsev683564a2011-02-07 02:17:30 +00008438 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
8439 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00008440 } else {
John McCall09431682010-11-18 19:01:18 +00008441 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00008442 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00008443 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008444 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008445 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00008446 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00008447 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00008448 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008449 // In C++, a prefix increment is the same type as the operand. Otherwise
8450 // (in C or with postfix), the increment is the unqualified type of the
8451 // operand.
John McCall09431682010-11-18 19:01:18 +00008452 if (isPrefix && S.getLangOptions().CPlusPlus) {
8453 VK = VK_LValue;
8454 return ResType;
8455 } else {
8456 VK = VK_RValue;
8457 return ResType.getUnqualifiedType();
8458 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008459}
8460
John Wiegley429bb272011-04-08 18:41:53 +00008461ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCallf6a16482010-12-04 03:47:34 +00008462 assert(E->getValueKind() == VK_LValue &&
8463 E->getObjectKind() == OK_ObjCProperty);
8464 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
8465
Douglas Gregor926df6c2011-06-11 01:09:30 +00008466 QualType T = E->getType();
8467 QualType ReceiverType;
8468 if (PRE->isObjectReceiver())
8469 ReceiverType = PRE->getBase()->getType();
8470 else if (PRE->isSuperReceiver())
8471 ReceiverType = PRE->getSuperReceiverType();
8472 else
8473 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
8474
John McCallf6a16482010-12-04 03:47:34 +00008475 ExprValueKind VK = VK_RValue;
8476 if (PRE->isImplicitProperty()) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00008477 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian99130e52010-12-22 19:46:35 +00008478 PRE->getImplicitPropertyGetter()) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00008479 T = getMessageSendResultType(ReceiverType, GetterMethod,
8480 PRE->isClassReceiver(),
8481 PRE->isSuperReceiver());
8482 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian99130e52010-12-22 19:46:35 +00008483 }
8484 else {
8485 Diag(PRE->getLocation(), diag::err_getter_not_found)
8486 << PRE->getBase()->getType();
8487 }
John McCallf6a16482010-12-04 03:47:34 +00008488 }
Douglas Gregor926df6c2011-06-11 01:09:30 +00008489
8490 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCallf6a16482010-12-04 03:47:34 +00008491 E, 0, VK);
John McCalldb67e2f2010-12-10 01:49:45 +00008492
8493 ExprResult Result = MaybeBindToTemporary(E);
8494 if (!Result.isInvalid())
8495 E = Result.take();
John Wiegley429bb272011-04-08 18:41:53 +00008496
8497 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00008498}
8499
John Wiegley429bb272011-04-08 18:41:53 +00008500void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
8501 assert(LHS.get()->getValueKind() == VK_LValue &&
8502 LHS.get()->getObjectKind() == OK_ObjCProperty);
8503 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCallf6a16482010-12-04 03:47:34 +00008504
John McCallf85e1932011-06-15 23:02:42 +00008505 bool Consumed = false;
8506
John Wiegley429bb272011-04-08 18:41:53 +00008507 if (PropRef->isImplicitProperty()) {
John McCallf6a16482010-12-04 03:47:34 +00008508 // If using property-dot syntax notation for assignment, and there is a
8509 // setter, RHS expression is being passed to the setter argument. So,
8510 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley429bb272011-04-08 18:41:53 +00008511 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCallf6a16482010-12-04 03:47:34 +00008512 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
8513 LHSTy = (*P)->getType();
John McCallf85e1932011-06-15 23:02:42 +00008514 Consumed = (getLangOptions().ObjCAutoRefCount &&
8515 (*P)->hasAttr<NSConsumedAttr>());
John McCallf6a16482010-12-04 03:47:34 +00008516
8517 // Otherwise, if the getter returns an l-value, just call that.
8518 } else {
John Wiegley429bb272011-04-08 18:41:53 +00008519 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCallf6a16482010-12-04 03:47:34 +00008520 ExprValueKind VK = Expr::getValueKindForType(Result);
8521 if (VK == VK_LValue) {
John Wiegley429bb272011-04-08 18:41:53 +00008522 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
8523 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCallf6a16482010-12-04 03:47:34 +00008524 return;
John McCall12f78a62010-12-02 01:19:52 +00008525 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008526 }
John McCallf85e1932011-06-15 23:02:42 +00008527 } else if (getLangOptions().ObjCAutoRefCount) {
8528 const ObjCMethodDecl *setter
8529 = PropRef->getExplicitProperty()->getSetterMethodDecl();
8530 if (setter) {
8531 ObjCMethodDecl::param_iterator P = setter->param_begin();
8532 LHSTy = (*P)->getType();
8533 Consumed = (*P)->hasAttr<NSConsumedAttr>();
8534 }
John McCallf6a16482010-12-04 03:47:34 +00008535 }
8536
John McCallf85e1932011-06-15 23:02:42 +00008537 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
8538 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008539 InitializedEntity Entity =
John McCallf85e1932011-06-15 23:02:42 +00008540 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley429bb272011-04-08 18:41:53 +00008541 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCallf85e1932011-06-15 23:02:42 +00008542 if (!ArgE.isInvalid()) {
John Wiegley429bb272011-04-08 18:41:53 +00008543 RHS = ArgE;
John McCallf85e1932011-06-15 23:02:42 +00008544 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
8545 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
8546 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008547 }
8548}
8549
8550
Anders Carlsson369dee42008-02-01 07:15:58 +00008551/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00008552/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008553/// where the declaration is needed for type checking. We only need to
8554/// handle cases when the expression references a function designator
8555/// or is an lvalue. Here are some examples:
8556/// - &(x) => x
8557/// - &*****f => f for f a function designator.
8558/// - &s.xx => s
8559/// - &s.zz[1].yy -> s, if zz is an array
8560/// - *(x + 1) -> x, if x is an array
8561/// - &"123"[2] -> 0
8562/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00008563static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00008564 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00008565 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00008566 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00008567 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00008568 // If this is an arrow operator, the address is an offset from
8569 // the base's value, so the object the base refers to is
8570 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00008571 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00008572 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00008573 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00008574 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00008575 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00008576 // FIXME: This code shouldn't be necessary! We should catch the implicit
8577 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00008578 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8579 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8580 if (ICE->getSubExpr()->getType()->isArrayType())
8581 return getPrimaryDecl(ICE->getSubExpr());
8582 }
8583 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00008584 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008585 case Stmt::UnaryOperatorClass: {
8586 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008587
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008588 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00008589 case UO_Real:
8590 case UO_Imag:
8591 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008592 return getPrimaryDecl(UO->getSubExpr());
8593 default:
8594 return 0;
8595 }
8596 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008597 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00008598 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00008599 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00008600 // If the result of an implicit cast is an l-value, we care about
8601 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00008602 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00008603 default:
8604 return 0;
8605 }
8606}
8607
8608/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00008609/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00008610/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008611/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00008612/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008613/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00008614/// we allow the '&' but retain the overloaded-function type.
John McCall09431682010-11-18 19:01:18 +00008615static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
8616 SourceLocation OpLoc) {
John McCall9c72c602010-08-27 09:08:28 +00008617 if (OrigOp->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008618 return S.Context.DependentTy;
8619 if (OrigOp->getType() == S.Context.OverloadTy)
8620 return S.Context.OverloadTy;
John McCall755d8492011-04-12 00:42:48 +00008621 if (OrigOp->getType() == S.Context.UnknownAnyTy)
8622 return S.Context.UnknownAnyTy;
John McCall864c0412011-04-26 20:42:42 +00008623 if (OrigOp->getType() == S.Context.BoundMemberTy) {
8624 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8625 << OrigOp->getSourceRange();
8626 return QualType();
8627 }
John McCall9c72c602010-08-27 09:08:28 +00008628
John McCall755d8492011-04-12 00:42:48 +00008629 assert(!OrigOp->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00008630
John McCall9c72c602010-08-27 09:08:28 +00008631 // Make sure to ignore parentheses in subsequent checks
8632 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00008633
John McCall09431682010-11-18 19:01:18 +00008634 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00008635 // Implement C99-only parts of addressof rules.
8636 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00008637 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00008638 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8639 // (assuming the deref expression is valid).
8640 return uOp->getSubExpr()->getType();
8641 }
8642 // Technically, there should be a check for array subscript
8643 // expressions here, but the result of one is always an lvalue anyway.
8644 }
John McCall5808ce42011-02-03 08:15:49 +00008645 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00008646 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00008647
Fariborz Jahanian077f4902011-03-26 19:48:30 +00008648 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00008649 bool sfinae = S.isSFINAEContext();
8650 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8651 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00008652 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00008653 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00008654 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00008655 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008656 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00008657 } else if (lval == Expr::LV_MemberFunction) {
8658 // If it's an instance method, make a member pointer.
8659 // The expression must have exactly the form &A::foo.
8660
8661 // If the underlying expression isn't a decl ref, give up.
8662 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008663 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00008664 << OrigOp->getSourceRange();
8665 return QualType();
8666 }
8667 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8668 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8669
8670 // The id-expression was parenthesized.
8671 if (OrigOp != DRE) {
John McCall09431682010-11-18 19:01:18 +00008672 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00008673 << OrigOp->getSourceRange();
8674
8675 // The method was named without a qualifier.
8676 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00008677 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00008678 << op->getSourceRange();
8679 }
8680
John McCall09431682010-11-18 19:01:18 +00008681 return S.Context.getMemberPointerType(op->getType(),
8682 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00008683 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00008684 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008685 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00008686 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00008687 // FIXME: emit more specific diag...
John McCall09431682010-11-18 19:01:18 +00008688 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008689 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00008690 return QualType();
8691 }
John McCall7eb0a9e2010-11-24 05:12:34 +00008692 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008693 // The operand cannot be a bit-field
John McCall09431682010-11-18 19:01:18 +00008694 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman23d58ce2009-04-20 08:23:18 +00008695 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00008696 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00008697 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00008698 // The operand cannot be an element of a vector
John McCall09431682010-11-18 19:01:18 +00008699 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00008700 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00008701 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00008702 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian0337f212009-07-07 18:50:52 +00008703 // cannot take address of a property expression.
John McCall09431682010-11-18 19:01:18 +00008704 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian0337f212009-07-07 18:50:52 +00008705 << "property expression" << op->getSourceRange();
8706 return QualType();
Steve Naroffbcb2b612008-02-29 23:30:25 +00008707 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00008708 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00008709 // with the register storage-class specifier.
8710 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00008711 // in C++ it is not error to take address of a register
8712 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00008713 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00008714 !S.getLangOptions().CPlusPlus) {
8715 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008716 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00008717 return QualType();
8718 }
John McCallba135432009-11-21 08:51:07 +00008719 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00008720 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00008721 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00008722 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00008723 // Could be a pointer to member, though, if there is an explicit
8724 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00008725 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00008726 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008727 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00008728 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00008729 S.Diag(OpLoc,
8730 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00008731 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008732 return QualType();
8733 }
Mike Stump1eb44332009-09-09 15:08:12 +00008734
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00008735 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8736 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00008737 return S.Context.getMemberPointerType(op->getType(),
8738 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008739 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00008740 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00008741 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00008742 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00008743 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00008744
Eli Friedman441cf102009-05-16 23:27:50 +00008745 if (lval == Expr::LV_IncompleteVoidType) {
8746 // Taking the address of a void variable is technically illegal, but we
8747 // allow it in cases which are otherwise valid.
8748 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00008749 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00008750 }
8751
Reid Spencer5f016e22007-07-11 17:01:13 +00008752 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00008753 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00008754 return S.Context.getObjCObjectPointerType(op->getType());
8755 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008756}
8757
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008758/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00008759static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8760 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00008761 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008762 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008763
John Wiegley429bb272011-04-08 18:41:53 +00008764 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8765 if (ConvResult.isInvalid())
8766 return QualType();
8767 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008768 QualType OpTy = Op->getType();
8769 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00008770
8771 if (isa<CXXReinterpretCastExpr>(Op)) {
8772 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8773 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8774 Op->getSourceRange());
8775 }
8776
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008777 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8778 // is an incomplete type or void. It would be possible to warn about
8779 // dereferencing a void pointer, but it's completely well-defined, and such a
8780 // warning is unlikely to catch any mistakes.
8781 if (const PointerType *PT = OpTy->getAs<PointerType>())
8782 Result = PT->getPointeeType();
8783 else if (const ObjCObjectPointerType *OPT =
8784 OpTy->getAs<ObjCObjectPointerType>())
8785 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00008786 else {
John McCallfb8721c2011-04-10 19:13:55 +00008787 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008788 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008789 if (PR.take() != Op)
8790 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00008791 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008792
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008793 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00008794 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008795 << OpTy << Op->getSourceRange();
8796 return QualType();
8797 }
John McCall09431682010-11-18 19:01:18 +00008798
8799 // Dereferences are usually l-values...
8800 VK = VK_LValue;
8801
8802 // ...except that certain expressions are never l-values in C.
8803 if (!S.getLangOptions().CPlusPlus &&
8804 IsCForbiddenLValueType(S.Context, Result))
8805 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008806
8807 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00008808}
8809
John McCall2de56d12010-08-25 11:45:40 +00008810static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008811 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008812 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008813 switch (Kind) {
8814 default: assert(0 && "Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00008815 case tok::periodstar: Opc = BO_PtrMemD; break;
8816 case tok::arrowstar: Opc = BO_PtrMemI; break;
8817 case tok::star: Opc = BO_Mul; break;
8818 case tok::slash: Opc = BO_Div; break;
8819 case tok::percent: Opc = BO_Rem; break;
8820 case tok::plus: Opc = BO_Add; break;
8821 case tok::minus: Opc = BO_Sub; break;
8822 case tok::lessless: Opc = BO_Shl; break;
8823 case tok::greatergreater: Opc = BO_Shr; break;
8824 case tok::lessequal: Opc = BO_LE; break;
8825 case tok::less: Opc = BO_LT; break;
8826 case tok::greaterequal: Opc = BO_GE; break;
8827 case tok::greater: Opc = BO_GT; break;
8828 case tok::exclaimequal: Opc = BO_NE; break;
8829 case tok::equalequal: Opc = BO_EQ; break;
8830 case tok::amp: Opc = BO_And; break;
8831 case tok::caret: Opc = BO_Xor; break;
8832 case tok::pipe: Opc = BO_Or; break;
8833 case tok::ampamp: Opc = BO_LAnd; break;
8834 case tok::pipepipe: Opc = BO_LOr; break;
8835 case tok::equal: Opc = BO_Assign; break;
8836 case tok::starequal: Opc = BO_MulAssign; break;
8837 case tok::slashequal: Opc = BO_DivAssign; break;
8838 case tok::percentequal: Opc = BO_RemAssign; break;
8839 case tok::plusequal: Opc = BO_AddAssign; break;
8840 case tok::minusequal: Opc = BO_SubAssign; break;
8841 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8842 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8843 case tok::ampequal: Opc = BO_AndAssign; break;
8844 case tok::caretequal: Opc = BO_XorAssign; break;
8845 case tok::pipeequal: Opc = BO_OrAssign; break;
8846 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008847 }
8848 return Opc;
8849}
8850
John McCall2de56d12010-08-25 11:45:40 +00008851static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008852 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008853 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008854 switch (Kind) {
8855 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00008856 case tok::plusplus: Opc = UO_PreInc; break;
8857 case tok::minusminus: Opc = UO_PreDec; break;
8858 case tok::amp: Opc = UO_AddrOf; break;
8859 case tok::star: Opc = UO_Deref; break;
8860 case tok::plus: Opc = UO_Plus; break;
8861 case tok::minus: Opc = UO_Minus; break;
8862 case tok::tilde: Opc = UO_Not; break;
8863 case tok::exclaim: Opc = UO_LNot; break;
8864 case tok::kw___real: Opc = UO_Real; break;
8865 case tok::kw___imag: Opc = UO_Imag; break;
8866 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008867 }
8868 return Opc;
8869}
8870
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008871/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8872/// This warning is only emitted for builtin assignment operations. It is also
8873/// suppressed in the event of macro expansions.
8874static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
8875 SourceLocation OpLoc) {
8876 if (!S.ActiveTemplateInstantiations.empty())
8877 return;
8878 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8879 return;
8880 lhs = lhs->IgnoreParenImpCasts();
8881 rhs = rhs->IgnoreParenImpCasts();
8882 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
8883 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
8884 if (!LeftDeclRef || !RightDeclRef ||
8885 LeftDeclRef->getLocation().isMacroID() ||
8886 RightDeclRef->getLocation().isMacroID())
8887 return;
8888 const ValueDecl *LeftDecl =
8889 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
8890 const ValueDecl *RightDecl =
8891 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
8892 if (LeftDecl != RightDecl)
8893 return;
8894 if (LeftDecl->getType().isVolatileQualified())
8895 return;
8896 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
8897 if (RefTy->getPointeeType().isVolatileQualified())
8898 return;
8899
8900 S.Diag(OpLoc, diag::warn_self_assignment)
8901 << LeftDeclRef->getType()
8902 << lhs->getSourceRange() << rhs->getSourceRange();
8903}
8904
Douglas Gregoreaebc752008-11-06 23:29:22 +00008905/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8906/// operator @p Opc at location @c TokLoc. This routine only supports
8907/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00008908ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008909 BinaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008910 Expr *lhsExpr, Expr *rhsExpr) {
8911 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008912 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00008913 // The following two variables are used for compound assignment operators
8914 QualType CompLHSTy; // Type of LHS after promotions for computation
8915 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00008916 ExprValueKind VK = VK_RValue;
8917 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00008918
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008919 // Check if a 'foo<int>' involved in a binary op, identifies a single
8920 // function unambiguously (i.e. an lvalue ala 13.4)
8921 // But since an assignment can trigger target based overload, exclude it in
8922 // our blind search. i.e:
8923 // template<class T> void f(); template<class T, class U> void f(U);
8924 // f<int> == 0; // resolve f<int> blindly
8925 // void (*p)(int); p = f<int>; // resolve f<int> using target
8926 if (Opc != BO_Assign) {
John McCallfb8721c2011-04-10 19:13:55 +00008927 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008928 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008929 lhs = move(resolvedLHS);
John McCall1de4d4e2011-04-07 08:22:57 +00008930
John McCallfb8721c2011-04-10 19:13:55 +00008931 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008932 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008933 rhs = move(resolvedRHS);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008934 }
8935
Richard Trieu3e95ba92011-06-16 21:36:56 +00008936 bool LeftNull = Expr::NPCK_GNUNull ==
8937 lhs.get()->isNullPointerConstant(Context,
8938 Expr::NPC_ValueDependentIsNotNull);
8939 bool RightNull = Expr::NPCK_GNUNull ==
8940 rhs.get()->isNullPointerConstant(Context,
8941 Expr::NPC_ValueDependentIsNotNull);
8942
8943 // Detect when a NULL constant is used improperly in an expression. These
8944 // are mainly cases where the null pointer is used as an integer instead
8945 // of a pointer.
8946 if (LeftNull || RightNull) {
8947 if (Opc == BO_Mul || Opc == BO_Div || Opc == BO_Rem || Opc == BO_Add ||
8948 Opc == BO_Sub || Opc == BO_Shl || Opc == BO_Shr || Opc == BO_And ||
8949 Opc == BO_Xor || Opc == BO_Or || Opc == BO_MulAssign ||
8950 Opc == BO_DivAssign || Opc == BO_AddAssign || Opc == BO_SubAssign ||
8951 Opc == BO_RemAssign || Opc == BO_ShlAssign || Opc == BO_ShrAssign ||
8952 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign) {
8953 // These are the operations that would not make sense with a null pointer
8954 // no matter what the other expression is.
8955 if (LeftNull && RightNull) {
8956 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
8957 << lhs.get()->getSourceRange() << rhs.get()->getSourceRange();
8958 } else if (LeftNull) {
8959 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
8960 << lhs.get()->getSourceRange();
8961 } else if (RightNull) {
8962 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
8963 << rhs.get()->getSourceRange();
8964 }
8965 } else if (Opc == BO_LE || Opc == BO_LT || Opc == BO_GE || Opc == BO_GT ||
8966 Opc == BO_EQ || Opc == BO_NE) {
8967 // These are the operations that would not make sense with a null pointer
8968 // if the other expression the other expression is not a pointer.
8969 QualType LeftType = lhs.get()->getType();
8970 QualType RightType = rhs.get()->getType();
8971 bool LeftPointer = LeftType->isPointerType() ||
8972 LeftType->isBlockPointerType() ||
8973 LeftType->isMemberPointerType() ||
8974 LeftType->isObjCObjectPointerType();
8975 bool RightPointer = RightType->isPointerType() ||
8976 RightType->isBlockPointerType() ||
8977 RightType->isMemberPointerType() ||
8978 RightType->isObjCObjectPointerType();
8979 if ((LeftNull != RightNull) && !LeftPointer && !RightPointer) {
8980 if (LeftNull)
8981 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
8982 << lhs.get()->getSourceRange();
8983 if (RightNull)
8984 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
8985 << rhs.get()->getSourceRange();
8986 }
8987 }
8988 }
8989
Douglas Gregoreaebc752008-11-06 23:29:22 +00008990 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008991 case BO_Assign:
John Wiegley429bb272011-04-08 18:41:53 +00008992 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00008993 if (getLangOptions().CPlusPlus &&
John Wiegley429bb272011-04-08 18:41:53 +00008994 lhs.get()->getObjectKind() != OK_ObjCProperty) {
8995 VK = lhs.get()->getValueKind();
8996 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008997 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008998 if (!ResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00008999 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00009000 break;
John McCall2de56d12010-08-25 11:45:40 +00009001 case BO_PtrMemD:
9002 case BO_PtrMemI:
John McCallf89e55a2010-11-18 06:31:45 +00009003 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00009004 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00009005 break;
John McCall2de56d12010-08-25 11:45:40 +00009006 case BO_Mul:
9007 case BO_Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00009008 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00009009 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00009010 break;
John McCall2de56d12010-08-25 11:45:40 +00009011 case BO_Rem:
Douglas Gregoreaebc752008-11-06 23:29:22 +00009012 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
9013 break;
John McCall2de56d12010-08-25 11:45:40 +00009014 case BO_Add:
Douglas Gregoreaebc752008-11-06 23:29:22 +00009015 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
9016 break;
John McCall2de56d12010-08-25 11:45:40 +00009017 case BO_Sub:
Douglas Gregoreaebc752008-11-06 23:29:22 +00009018 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
9019 break;
John McCall2de56d12010-08-25 11:45:40 +00009020 case BO_Shl:
9021 case BO_Shr:
Chandler Carruth21206d52011-02-23 23:34:11 +00009022 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00009023 break;
John McCall2de56d12010-08-25 11:45:40 +00009024 case BO_LE:
9025 case BO_LT:
9026 case BO_GE:
9027 case BO_GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00009028 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00009029 break;
John McCall2de56d12010-08-25 11:45:40 +00009030 case BO_EQ:
9031 case BO_NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00009032 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00009033 break;
John McCall2de56d12010-08-25 11:45:40 +00009034 case BO_And:
9035 case BO_Xor:
9036 case BO_Or:
Douglas Gregoreaebc752008-11-06 23:29:22 +00009037 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
9038 break;
John McCall2de56d12010-08-25 11:45:40 +00009039 case BO_LAnd:
9040 case BO_LOr:
Chris Lattner90a8f272010-07-13 19:41:32 +00009041 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00009042 break;
John McCall2de56d12010-08-25 11:45:40 +00009043 case BO_MulAssign:
9044 case BO_DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00009045 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00009046 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00009047 CompLHSTy = CompResultTy;
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_RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00009052 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
9053 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00009054 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9055 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00009056 break;
John McCall2de56d12010-08-25 11:45:40 +00009057 case BO_AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00009058 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00009059 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9060 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00009061 break;
John McCall2de56d12010-08-25 11:45:40 +00009062 case BO_SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00009063 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00009064 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9065 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00009066 break;
John McCall2de56d12010-08-25 11:45:40 +00009067 case BO_ShlAssign:
9068 case BO_ShrAssign:
Chandler Carruth21206d52011-02-23 23:34:11 +00009069 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00009070 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00009071 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9072 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00009073 break;
John McCall2de56d12010-08-25 11:45:40 +00009074 case BO_AndAssign:
9075 case BO_XorAssign:
9076 case BO_OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00009077 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
9078 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00009079 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9080 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00009081 break;
John McCall2de56d12010-08-25 11:45:40 +00009082 case BO_Comma:
John McCall09431682010-11-18 19:01:18 +00009083 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009084 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
9085 VK = rhs.get()->getValueKind();
9086 OK = rhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00009087 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00009088 break;
9089 }
John Wiegley429bb272011-04-08 18:41:53 +00009090 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00009091 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00009092 if (CompResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00009093 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
9094 ResultTy, VK, OK, OpLoc));
9095 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00009096 VK = VK_LValue;
John Wiegley429bb272011-04-08 18:41:53 +00009097 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00009098 }
John Wiegley429bb272011-04-08 18:41:53 +00009099 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
9100 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00009101 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00009102}
9103
Sebastian Redlaee3c932009-10-27 12:10:02 +00009104/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
9105/// operators are mixed in a way that suggests that the programmer forgot that
9106/// comparison operators have higher precedence. The most typical example of
9107/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00009108static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00009109 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00009110 typedef BinaryOperator BinOp;
9111 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
9112 rhsopc = static_cast<BinOp::Opcode>(-1);
9113 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00009114 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00009115 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00009116 rhsopc = BO->getOpcode();
9117
9118 // Subs are not binary operators.
9119 if (lhsopc == -1 && rhsopc == -1)
9120 return;
9121
9122 // Bitwise operations are sometimes used as eager logical ops.
9123 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00009124 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
9125 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00009126 return;
9127
Chandler Carruthf0b60d62011-06-16 01:05:14 +00009128 if (BinOp::isComparisonOp(lhsopc)) {
9129 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9130 << SourceRange(lhs->getLocStart(), OpLoc)
9131 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc);
Sebastian Redl6b169ac2009-10-26 17:01:32 +00009132 SuggestParentheses(Self, OpLoc,
Douglas Gregor55b38842010-04-14 16:09:52 +00009133 Self.PDiag(diag::note_precedence_bitwise_silence)
9134 << BinOp::getOpcodeStr(lhsopc),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00009135 lhs->getSourceRange());
9136 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009137 Self.PDiag(diag::note_precedence_bitwise_first)
9138 << BinOp::getOpcodeStr(Opc),
9139 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
Chandler Carruthf0b60d62011-06-16 01:05:14 +00009140 } else if (BinOp::isComparisonOp(rhsopc)) {
9141 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9142 << SourceRange(OpLoc, rhs->getLocEnd())
9143 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc);
Sebastian Redl6b169ac2009-10-26 17:01:32 +00009144 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009145 Self.PDiag(diag::note_precedence_bitwise_silence)
9146 << BinOp::getOpcodeStr(rhsopc),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00009147 rhs->getSourceRange());
9148 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00009149 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00009150 << BinOp::getOpcodeStr(Opc),
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009151 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Chandler Carruthf0b60d62011-06-16 01:05:14 +00009152 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00009153}
9154
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00009155/// \brief It accepts a '&&' expr that is inside a '||' one.
9156/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
9157/// in parentheses.
9158static void
9159EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00009160 BinaryOperator *Bop) {
9161 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00009162 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
9163 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00009164 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00009165 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00009166 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00009167}
9168
9169/// \brief Returns true if the given expression can be evaluated as a constant
9170/// 'true'.
9171static bool EvaluatesAsTrue(Sema &S, Expr *E) {
9172 bool Res;
9173 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
9174}
9175
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00009176/// \brief Returns true if the given expression can be evaluated as a constant
9177/// 'false'.
9178static bool EvaluatesAsFalse(Sema &S, Expr *E) {
9179 bool Res;
9180 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
9181}
9182
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00009183/// \brief Look for '&&' in the left hand of a '||' expr.
9184static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00009185 Expr *OrLHS, Expr *OrRHS) {
9186 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00009187 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00009188 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
9189 if (EvaluatesAsFalse(S, OrRHS))
9190 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00009191 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
9192 if (!EvaluatesAsTrue(S, Bop->getLHS()))
9193 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9194 } else if (Bop->getOpcode() == BO_LOr) {
9195 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
9196 // If it's "a || b && 1 || c" we didn't warn earlier for
9197 // "a || b && 1", but warn now.
9198 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
9199 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
9200 }
9201 }
9202 }
9203}
9204
9205/// \brief Look for '&&' in the right hand of a '||' expr.
9206static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00009207 Expr *OrLHS, Expr *OrRHS) {
9208 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00009209 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00009210 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
9211 if (EvaluatesAsFalse(S, OrLHS))
9212 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00009213 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
9214 if (!EvaluatesAsTrue(S, Bop->getRHS()))
9215 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00009216 }
9217 }
9218}
9219
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00009220/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00009221/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00009222static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00009223 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00009224 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00009225 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00009226 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
9227
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00009228 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9229 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00009230 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00009231 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
9232 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00009233 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00009234}
9235
Reid Spencer5f016e22007-07-11 17:01:13 +00009236// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00009237ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00009238 tok::TokenKind Kind,
9239 Expr *lhs, Expr *rhs) {
9240 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Narofff69936d2007-09-16 03:34:24 +00009241 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
9242 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00009243
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00009244 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
9245 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
9246
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009247 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
9248}
9249
John McCall60d7b3a2010-08-24 06:29:42 +00009250ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00009251 BinaryOperatorKind Opc,
9252 Expr *lhs, Expr *rhs) {
John McCall01b2e4e2010-12-06 05:26:58 +00009253 if (getLangOptions().CPlusPlus) {
9254 bool UseBuiltinOperator;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009255
John McCall01b2e4e2010-12-06 05:26:58 +00009256 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
9257 UseBuiltinOperator = false;
9258 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
9259 UseBuiltinOperator = true;
9260 } else {
9261 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
9262 !rhs->getType()->isOverloadableType();
9263 }
9264
9265 if (!UseBuiltinOperator) {
9266 // Find all of the overloaded operators visible from this
9267 // point. We perform both an operator-name lookup from the local
9268 // scope and an argument-dependent lookup based on the types of
9269 // the arguments.
9270 UnresolvedSet<16> Functions;
9271 OverloadedOperatorKind OverOp
9272 = BinaryOperator::getOverloadedOperator(Opc);
9273 if (S && OverOp != OO_None)
9274 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
9275 Functions);
9276
9277 // Build the (potentially-overloaded, potentially-dependent)
9278 // binary operation.
9279 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
9280 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00009281 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009282
Douglas Gregoreaebc752008-11-06 23:29:22 +00009283 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009284 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00009285}
9286
John McCall60d7b3a2010-08-24 06:29:42 +00009287ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00009288 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00009289 Expr *InputExpr) {
9290 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00009291 ExprValueKind VK = VK_RValue;
9292 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00009293 QualType resultType;
9294 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00009295 case UO_PreInc:
9296 case UO_PreDec:
9297 case UO_PostInc:
9298 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00009299 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00009300 Opc == UO_PreInc ||
9301 Opc == UO_PostInc,
9302 Opc == UO_PreInc ||
9303 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00009304 break;
John McCall2de56d12010-08-25 11:45:40 +00009305 case UO_AddrOf:
John Wiegley429bb272011-04-08 18:41:53 +00009306 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00009307 break;
John McCall1de4d4e2011-04-07 08:22:57 +00009308 case UO_Deref: {
John McCallfb8721c2011-04-10 19:13:55 +00009309 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall1de4d4e2011-04-07 08:22:57 +00009310 if (!resolved.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009311 Input = move(resolved);
9312 Input = DefaultFunctionArrayLvalueConversion(Input.take());
9313 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00009314 break;
John McCall1de4d4e2011-04-07 08:22:57 +00009315 }
John McCall2de56d12010-08-25 11:45:40 +00009316 case UO_Plus:
9317 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00009318 Input = UsualUnaryConversions(Input.take());
9319 if (Input.isInvalid()) return ExprError();
9320 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00009321 if (resultType->isDependentType())
9322 break;
Douglas Gregor00619622010-06-22 23:41:02 +00009323 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9324 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00009325 break;
9326 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
9327 resultType->isEnumeralType())
9328 break;
9329 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00009330 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00009331 resultType->isPointerType())
9332 break;
John McCall2cd11fe2010-10-12 02:09:17 +00009333 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00009334 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00009335 if (Input.isInvalid()) return ExprError();
9336 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00009337 }
Douglas Gregor74253732008-11-19 15:42:04 +00009338
Sebastian Redl0eb23302009-01-19 00:08:26 +00009339 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00009340 << resultType << Input.get()->getSourceRange());
9341
John McCall2de56d12010-08-25 11:45:40 +00009342 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00009343 Input = UsualUnaryConversions(Input.take());
9344 if (Input.isInvalid()) return ExprError();
9345 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00009346 if (resultType->isDependentType())
9347 break;
Chris Lattner02a65142008-07-25 23:52:49 +00009348 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9349 if (resultType->isComplexType() || resultType->isComplexIntegerType())
9350 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00009351 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00009352 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00009353 else if (resultType->hasIntegerRepresentation())
9354 break;
9355 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00009356 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00009357 if (Input.isInvalid()) return ExprError();
9358 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00009359 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00009360 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00009361 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00009362 }
Reid Spencer5f016e22007-07-11 17:01:13 +00009363 break;
John Wiegley429bb272011-04-08 18:41:53 +00009364
John McCall2de56d12010-08-25 11:45:40 +00009365 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00009366 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00009367 Input = DefaultFunctionArrayLvalueConversion(Input.take());
9368 if (Input.isInvalid()) return ExprError();
9369 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00009370 if (resultType->isDependentType())
9371 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00009372 if (resultType->isScalarType()) {
9373 // C99 6.5.3.3p1: ok, fallthrough;
9374 if (Context.getLangOptions().CPlusPlus) {
9375 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9376 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00009377 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
9378 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00009379 }
John McCall2cd11fe2010-10-12 02:09:17 +00009380 } else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00009381 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00009382 if (Input.isInvalid()) return ExprError();
9383 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00009384 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00009385 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00009386 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00009387 }
Douglas Gregorea844f32010-09-20 17:13:33 +00009388
Reid Spencer5f016e22007-07-11 17:01:13 +00009389 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00009390 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00009391 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00009392 break;
John McCall2de56d12010-08-25 11:45:40 +00009393 case UO_Real:
9394 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00009395 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00009396 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley429bb272011-04-08 18:41:53 +00009397 if (Input.isInvalid()) return ExprError();
9398 if (Input.get()->getValueKind() != VK_RValue &&
9399 Input.get()->getObjectKind() == OK_Ordinary)
9400 VK = Input.get()->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00009401 break;
John McCall2de56d12010-08-25 11:45:40 +00009402 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00009403 resultType = Input.get()->getType();
9404 VK = Input.get()->getValueKind();
9405 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00009406 break;
9407 }
John Wiegley429bb272011-04-08 18:41:53 +00009408 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00009409 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009410
John Wiegley429bb272011-04-08 18:41:53 +00009411 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00009412 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00009413}
9414
John McCall60d7b3a2010-08-24 06:29:42 +00009415ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00009416 UnaryOperatorKind Opc,
9417 Expr *Input) {
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00009418 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00009419 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009420 // Find all of the overloaded operators visible from this
9421 // point. We perform both an operator-name lookup from the local
9422 // scope and an argument-dependent lookup based on the types of
9423 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00009424 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009425 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00009426 if (S && OverOp != OO_None)
9427 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9428 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009429
John McCall9ae2f072010-08-23 23:25:46 +00009430 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009431 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009432
John McCall9ae2f072010-08-23 23:25:46 +00009433 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009434}
9435
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009436// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00009437ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00009438 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00009439 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009440}
9441
Steve Naroff1b273c42007-09-16 14:56:35 +00009442/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00009443ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00009444 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00009445 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00009446 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00009447 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009448 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00009449}
9450
John McCallf85e1932011-06-15 23:02:42 +00009451/// Given the last statement in a statement-expression, check whether
9452/// the result is a producing expression (like a call to an
9453/// ns_returns_retained function) and, if so, rebuild it to hoist the
9454/// release out of the full-expression. Otherwise, return null.
9455/// Cannot fail.
9456static Expr *maybeRebuildARCConsumingStmt(Stmt *s) {
9457 // Should always be wrapped with one of these.
9458 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(s);
9459 if (!cleanups) return 0;
9460
9461 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
9462 if (!cast || cast->getCastKind() != CK_ObjCConsumeObject)
9463 return 0;
9464
9465 // Splice out the cast. This shouldn't modify any interesting
9466 // features of the statement.
9467 Expr *producer = cast->getSubExpr();
9468 assert(producer->getType() == cast->getType());
9469 assert(producer->getValueKind() == cast->getValueKind());
9470 cleanups->setSubExpr(producer);
9471 return cleanups;
9472}
9473
John McCall60d7b3a2010-08-24 06:29:42 +00009474ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00009475Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009476 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009477 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9478 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9479
Douglas Gregordd8f5692010-03-10 04:54:39 +00009480 bool isFileScope
9481 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00009482 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00009483 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00009484
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009485 // FIXME: there are a variety of strange constraints to enforce here, for
9486 // example, it is not possible to goto into a stmt expression apparently.
9487 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00009488
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009489 // If there are sub stmts in the compound stmt, take the type of the last one
9490 // as the type of the stmtexpr.
9491 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009492 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009493 if (!Compound->body_empty()) {
9494 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009495 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009496 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009497 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9498 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009499 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009500 }
John McCallf85e1932011-06-15 23:02:42 +00009501
John Wiegley429bb272011-04-08 18:41:53 +00009502 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00009503 // Do function/array conversion on the last expression, but not
9504 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00009505 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9506 if (LastExpr.isInvalid())
9507 return ExprError();
9508 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00009509
John Wiegley429bb272011-04-08 18:41:53 +00009510 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00009511 // In ARC, if the final expression ends in a consume, splice
9512 // the consume out and bind it later. In the alternate case
9513 // (when dealing with a retainable type), the result
9514 // initialization will create a produce. In both cases the
9515 // result will be +1, and we'll need to balance that out with
9516 // a bind.
9517 if (Expr *rebuiltLastStmt
9518 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9519 LastExpr = rebuiltLastStmt;
9520 } else {
9521 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009522 InitializedEntity::InitializeResult(LPLoc,
9523 Ty,
9524 false),
9525 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00009526 LastExpr);
9527 }
9528
John Wiegley429bb272011-04-08 18:41:53 +00009529 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009530 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009531 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009532 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00009533 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009534 else
John Wiegley429bb272011-04-08 18:41:53 +00009535 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009536 StmtExprMayBindToTemp = true;
9537 }
9538 }
9539 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00009540 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009541
Eli Friedmanb1d796d2009-03-23 00:24:07 +00009542 // FIXME: Check that expression type is complete/non-abstract; statement
9543 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009544 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9545 if (StmtExprMayBindToTemp)
9546 return MaybeBindToTemporary(ResStmtExpr);
9547 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009548}
Steve Naroffd34e9152007-08-01 22:05:33 +00009549
John McCall60d7b3a2010-08-24 06:29:42 +00009550ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009551 TypeSourceInfo *TInfo,
9552 OffsetOfComponent *CompPtr,
9553 unsigned NumComponents,
9554 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009555 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00009556 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009557 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009558
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009559 // We must have at least one component that refers to the type, and the first
9560 // one is known to be a field designator. Verify that the ArgTy represents
9561 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00009562 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009563 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9564 << ArgTy << TypeRange);
9565
9566 // Type must be complete per C99 7.17p3 because a declaring a variable
9567 // with an incomplete type would be ill-formed.
9568 if (!Dependent
9569 && RequireCompleteType(BuiltinLoc, ArgTy,
9570 PDiag(diag::err_offsetof_incomplete_type)
9571 << TypeRange))
9572 return ExprError();
9573
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009574 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9575 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00009576 // FIXME: This diagnostic isn't actually visible because the location is in
9577 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009578 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00009579 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9580 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009581
9582 bool DidWarnAboutNonPOD = false;
9583 QualType CurrentType = ArgTy;
9584 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9585 llvm::SmallVector<OffsetOfNode, 4> Comps;
9586 llvm::SmallVector<Expr*, 4> Exprs;
9587 for (unsigned i = 0; i != NumComponents; ++i) {
9588 const OffsetOfComponent &OC = CompPtr[i];
9589 if (OC.isBrackets) {
9590 // Offset of an array sub-field. TODO: Should we allow vector elements?
9591 if (!CurrentType->isDependentType()) {
9592 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9593 if(!AT)
9594 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9595 << CurrentType);
9596 CurrentType = AT->getElementType();
9597 } else
9598 CurrentType = Context.DependentTy;
9599
9600 // The expression must be an integral expression.
9601 // FIXME: An integral constant expression?
9602 Expr *Idx = static_cast<Expr*>(OC.U.E);
9603 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9604 !Idx->getType()->isIntegerType())
9605 return ExprError(Diag(Idx->getLocStart(),
9606 diag::err_typecheck_subscript_not_integer)
9607 << Idx->getSourceRange());
9608
9609 // Record this array index.
9610 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9611 Exprs.push_back(Idx);
9612 continue;
9613 }
9614
9615 // Offset of a field.
9616 if (CurrentType->isDependentType()) {
9617 // We have the offset of a field, but we can't look into the dependent
9618 // type. Just record the identifier of the field.
9619 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9620 CurrentType = Context.DependentTy;
9621 continue;
9622 }
9623
9624 // We need to have a complete type to look into.
9625 if (RequireCompleteType(OC.LocStart, CurrentType,
9626 diag::err_offsetof_incomplete_type))
9627 return ExprError();
9628
9629 // Look for the designated field.
9630 const RecordType *RC = CurrentType->getAs<RecordType>();
9631 if (!RC)
9632 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9633 << CurrentType);
9634 RecordDecl *RD = RC->getDecl();
9635
9636 // C++ [lib.support.types]p5:
9637 // The macro offsetof accepts a restricted set of type arguments in this
9638 // International Standard. type shall be a POD structure or a POD union
9639 // (clause 9).
9640 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9641 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00009642 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009643 PDiag(diag::warn_offsetof_non_pod_type)
9644 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9645 << CurrentType))
9646 DidWarnAboutNonPOD = true;
9647 }
9648
9649 // Look for the field.
9650 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9651 LookupQualifiedName(R, RD);
9652 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00009653 IndirectFieldDecl *IndirectMemberDecl = 0;
9654 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00009655 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00009656 MemberDecl = IndirectMemberDecl->getAnonField();
9657 }
9658
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009659 if (!MemberDecl)
9660 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9661 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9662 OC.LocEnd));
9663
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009664 // C99 7.17p3:
9665 // (If the specified member is a bit-field, the behavior is undefined.)
9666 //
9667 // We diagnose this as an error.
9668 if (MemberDecl->getBitWidth()) {
9669 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9670 << MemberDecl->getDeclName()
9671 << SourceRange(BuiltinLoc, RParenLoc);
9672 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9673 return ExprError();
9674 }
Eli Friedman19410a72010-08-05 10:11:36 +00009675
9676 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00009677 if (IndirectMemberDecl)
9678 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00009679
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009680 // If the member was found in a base class, introduce OffsetOfNodes for
9681 // the base class indirections.
9682 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9683 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00009684 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009685 CXXBasePath &Path = Paths.front();
9686 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9687 B != BEnd; ++B)
9688 Comps.push_back(OffsetOfNode(B->Base));
9689 }
Eli Friedman19410a72010-08-05 10:11:36 +00009690
Francois Pichet87c2e122010-11-21 06:08:52 +00009691 if (IndirectMemberDecl) {
9692 for (IndirectFieldDecl::chain_iterator FI =
9693 IndirectMemberDecl->chain_begin(),
9694 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9695 assert(isa<FieldDecl>(*FI));
9696 Comps.push_back(OffsetOfNode(OC.LocStart,
9697 cast<FieldDecl>(*FI), OC.LocEnd));
9698 }
9699 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009700 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00009701
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009702 CurrentType = MemberDecl->getType().getNonReferenceType();
9703 }
9704
9705 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9706 TInfo, Comps.data(), Comps.size(),
9707 Exprs.data(), Exprs.size(), RParenLoc));
9708}
Mike Stumpeed9cac2009-02-19 03:04:26 +00009709
John McCall60d7b3a2010-08-24 06:29:42 +00009710ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00009711 SourceLocation BuiltinLoc,
9712 SourceLocation TypeLoc,
9713 ParsedType argty,
9714 OffsetOfComponent *CompPtr,
9715 unsigned NumComponents,
9716 SourceLocation RPLoc) {
9717
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009718 TypeSourceInfo *ArgTInfo;
9719 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
9720 if (ArgTy.isNull())
9721 return ExprError();
9722
Eli Friedman5a15dc12010-08-05 10:15:45 +00009723 if (!ArgTInfo)
9724 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9725
9726 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9727 RPLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009728}
9729
9730
John McCall60d7b3a2010-08-24 06:29:42 +00009731ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009732 Expr *CondExpr,
9733 Expr *LHSExpr, Expr *RHSExpr,
9734 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00009735 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9736
John McCallf89e55a2010-11-18 06:31:45 +00009737 ExprValueKind VK = VK_RValue;
9738 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00009739 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00009740 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00009741 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00009742 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00009743 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00009744 } else {
9745 // The conditional expression is required to be a constant expression.
9746 llvm::APSInt condEval(32);
9747 SourceLocation ExpLoc;
9748 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00009749 return ExprError(Diag(ExpLoc,
9750 diag::err_typecheck_choose_expr_requires_constant)
9751 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00009752
Sebastian Redl28507842009-02-26 14:39:58 +00009753 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00009754 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9755
9756 resType = ActiveExpr->getType();
9757 ValueDependent = ActiveExpr->isValueDependent();
9758 VK = ActiveExpr->getValueKind();
9759 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00009760 }
9761
Sebastian Redlf53597f2009-03-15 17:47:39 +00009762 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00009763 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00009764 resType->isDependentType(),
9765 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00009766}
9767
Steve Naroff4eb206b2008-09-03 18:15:37 +00009768//===----------------------------------------------------------------------===//
9769// Clang Extensions.
9770//===----------------------------------------------------------------------===//
9771
9772/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00009773void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009774 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9775 PushBlockScope(BlockScope, Block);
9776 CurContext->addDecl(Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009777 if (BlockScope)
9778 PushDeclContext(BlockScope, Block);
9779 else
9780 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00009781}
9782
Mike Stump98eb8a72009-02-04 22:31:32 +00009783void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00009784 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00009785 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009786 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009787
John McCallbf1a0282010-06-04 23:28:52 +00009788 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00009789 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00009790
John McCall711c52b2011-01-05 12:14:39 +00009791 // GetTypeForDeclarator always produces a function type for a block
9792 // literal signature. Furthermore, it is always a FunctionProtoType
9793 // unless the function was written with a typedef.
9794 assert(T->isFunctionType() &&
9795 "GetTypeForDeclarator made a non-function block signature");
9796
9797 // Look for an explicit signature in that function type.
9798 FunctionProtoTypeLoc ExplicitSignature;
9799
9800 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9801 if (isa<FunctionProtoTypeLoc>(tmp)) {
9802 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9803
9804 // Check whether that explicit signature was synthesized by
9805 // GetTypeForDeclarator. If so, don't save that as part of the
9806 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00009807 if (ExplicitSignature.getLocalRangeBegin() ==
9808 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00009809 // This would be much cheaper if we stored TypeLocs instead of
9810 // TypeSourceInfos.
9811 TypeLoc Result = ExplicitSignature.getResultLoc();
9812 unsigned Size = Result.getFullDataSize();
9813 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9814 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9815
9816 ExplicitSignature = FunctionProtoTypeLoc();
9817 }
John McCall82dc0092010-06-04 11:21:44 +00009818 }
Mike Stump1eb44332009-09-09 15:08:12 +00009819
John McCall711c52b2011-01-05 12:14:39 +00009820 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9821 CurBlock->FunctionType = T;
9822
9823 const FunctionType *Fn = T->getAs<FunctionType>();
9824 QualType RetTy = Fn->getResultType();
9825 bool isVariadic =
9826 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9827
John McCallc71a4912010-06-04 19:02:56 +00009828 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00009829
John McCall82dc0092010-06-04 11:21:44 +00009830 // Don't allow returning a objc interface by value.
9831 if (RetTy->isObjCObjectType()) {
9832 Diag(ParamInfo.getSourceRange().getBegin(),
9833 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9834 return;
9835 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009836
John McCall82dc0092010-06-04 11:21:44 +00009837 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00009838 // return type. TODO: what should we do with declarators like:
9839 // ^ * { ... }
9840 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00009841 if (RetTy != Context.DependentTy)
9842 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009843
John McCall82dc0092010-06-04 11:21:44 +00009844 // Push block parameters from the declarator if we had them.
John McCallc71a4912010-06-04 19:02:56 +00009845 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00009846 if (ExplicitSignature) {
9847 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9848 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009849 if (Param->getIdentifier() == 0 &&
9850 !Param->isImplicit() &&
9851 !Param->isInvalidDecl() &&
9852 !getLangOptions().CPlusPlus)
9853 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00009854 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009855 }
John McCall82dc0092010-06-04 11:21:44 +00009856
9857 // Fake up parameter variables if we have a typedef, like
9858 // ^ fntype { ... }
9859 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9860 for (FunctionProtoType::arg_type_iterator
9861 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9862 ParmVarDecl *Param =
9863 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9864 ParamInfo.getSourceRange().getBegin(),
9865 *I);
John McCallc71a4912010-06-04 19:02:56 +00009866 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00009867 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009868 }
John McCall82dc0092010-06-04 11:21:44 +00009869
John McCallc71a4912010-06-04 19:02:56 +00009870 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00009871 if (!Params.empty()) {
John McCallc71a4912010-06-04 19:02:56 +00009872 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregor82aa7132010-11-01 18:37:59 +00009873 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9874 CurBlock->TheDecl->param_end(),
9875 /*CheckParameterNames=*/false);
9876 }
9877
John McCall82dc0092010-06-04 11:21:44 +00009878 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009879 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00009880
John McCallc71a4912010-06-04 19:02:56 +00009881 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00009882 Diag(ParamInfo.getAttributes()->getLoc(),
9883 diag::warn_attribute_sentinel_not_variadic) << 1;
9884 // FIXME: remove the attribute.
9885 }
9886
9887 // Put the parameter variables in scope. We can bail out immediately
9888 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00009889 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00009890 return;
9891
Steve Naroff090276f2008-10-10 01:28:17 +00009892 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00009893 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9894 (*AI)->setOwningFunction(CurBlock->TheDecl);
9895
Steve Naroff090276f2008-10-10 01:28:17 +00009896 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009897 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009898 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00009899
Steve Naroff090276f2008-10-10 01:28:17 +00009900 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00009901 }
John McCall7a9813c2010-01-22 00:28:27 +00009902 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009903}
9904
9905/// ActOnBlockError - If there is an error parsing a block, this callback
9906/// is invoked to pop the information about the block from the action impl.
9907void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00009908 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00009909 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009910 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009911}
9912
9913/// ActOnBlockStmtExpr - This is called when the body of a block statement
9914/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00009915ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00009916 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00009917 // If blocks are disabled, emit an error.
9918 if (!LangOpts.Blocks)
9919 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00009920
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009921 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009922
Steve Naroff090276f2008-10-10 01:28:17 +00009923 PopDeclContext();
9924
Steve Naroff4eb206b2008-09-03 18:15:37 +00009925 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00009926 if (!BSI->ReturnType.isNull())
9927 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009928
Mike Stump56925862009-07-28 22:04:01 +00009929 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009930 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00009931
John McCall469a1eb2011-02-02 13:00:07 +00009932 // Set the captured variables on the block.
John McCall6b5a61b2011-02-07 10:33:21 +00009933 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
9934 BSI->CapturesCXXThis);
John McCall469a1eb2011-02-02 13:00:07 +00009935
John McCallc71a4912010-06-04 19:02:56 +00009936 // If the user wrote a function type in some form, try to use that.
9937 if (!BSI->FunctionType.isNull()) {
9938 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9939
9940 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9941 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9942
9943 // Turn protoless block types into nullary block types.
9944 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00009945 FunctionProtoType::ExtProtoInfo EPI;
9946 EPI.ExtInfo = Ext;
9947 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009948
9949 // Otherwise, if we don't need to change anything about the function type,
9950 // preserve its sugar structure.
9951 } else if (FTy->getResultType() == RetTy &&
9952 (!NoReturn || FTy->getNoReturnAttr())) {
9953 BlockTy = BSI->FunctionType;
9954
9955 // Otherwise, make the minimal modifications to the function type.
9956 } else {
9957 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00009958 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9959 EPI.TypeQuals = 0; // FIXME: silently?
9960 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00009961 BlockTy = Context.getFunctionType(RetTy,
9962 FPT->arg_type_begin(),
9963 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00009964 EPI);
John McCallc71a4912010-06-04 19:02:56 +00009965 }
9966
9967 // If we don't have a function type, just build one from nothing.
9968 } else {
John McCalle23cf432010-12-14 08:05:40 +00009969 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00009970 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00009971 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009972 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009973
John McCallc71a4912010-06-04 19:02:56 +00009974 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9975 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00009976 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009977
Chris Lattner17a78302009-04-19 05:28:12 +00009978 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00009979 if (getCurFunction()->NeedsScopeChecking() &&
9980 !hasAnyUnrecoverableErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00009981 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00009982
Chris Lattnere476bdc2011-02-17 23:58:47 +00009983 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009984
John McCall469a1eb2011-02-02 13:00:07 +00009985 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCalle0054f62010-08-25 05:56:39 +00009986
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009987 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9988 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009989 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00009990}
9991
John McCall60d7b3a2010-08-24 06:29:42 +00009992ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallb3d87482010-08-24 05:47:05 +00009993 Expr *expr, ParsedType type,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009994 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009995 TypeSourceInfo *TInfo;
Jeffrey Yasskindec09842011-01-18 02:00:16 +00009996 GetTypeFromParser(type, &TInfo);
John McCall9ae2f072010-08-23 23:25:46 +00009997 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009998}
9999
John McCall60d7b3a2010-08-24 06:29:42 +000010000ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +000010001 Expr *E, TypeSourceInfo *TInfo,
10002 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +000010003 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +000010004
Eli Friedmanc34bcde2008-08-09 23:32:40 +000010005 // Get the va_list type
10006 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +000010007 if (VaListType->isArrayType()) {
10008 // Deal with implicit array decay; for example, on x86-64,
10009 // va_list is an array, but it's supposed to decay to
10010 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +000010011 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +000010012 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +000010013 ExprResult Result = UsualUnaryConversions(E);
10014 if (Result.isInvalid())
10015 return ExprError();
10016 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +000010017 } else {
10018 // Otherwise, the va_list argument must be an l-value because
10019 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +000010020 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +000010021 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +000010022 return ExprError();
10023 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +000010024
Douglas Gregordd027302009-05-19 23:10:31 +000010025 if (!E->isTypeDependent() &&
10026 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +000010027 return ExprError(Diag(E->getLocStart(),
10028 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +000010029 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +000010030 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000010031
David Majnemer0adde122011-06-14 05:17:32 +000010032 if (!TInfo->getType()->isDependentType()) {
10033 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
10034 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
10035 << TInfo->getTypeLoc().getSourceRange()))
10036 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +000010037
David Majnemer0adde122011-06-14 05:17:32 +000010038 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
10039 TInfo->getType(),
10040 PDiag(diag::err_second_parameter_to_va_arg_abstract)
10041 << TInfo->getTypeLoc().getSourceRange()))
10042 return ExprError();
10043
John McCallf85e1932011-06-15 23:02:42 +000010044 if (!TInfo->getType().isPODType(Context))
David Majnemer0adde122011-06-14 05:17:32 +000010045 Diag(TInfo->getTypeLoc().getBeginLoc(),
10046 diag::warn_second_parameter_to_va_arg_not_pod)
10047 << TInfo->getType()
10048 << TInfo->getTypeLoc().getSourceRange();
10049 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000010050
Abramo Bagnara2cad9002010-08-10 10:06:15 +000010051 QualType T = TInfo->getType().getNonLValueExprType(Context);
10052 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +000010053}
10054
John McCall60d7b3a2010-08-24 06:29:42 +000010055ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +000010056 // The type of __null will be int or long, depending on the size of
10057 // pointers on the target.
10058 QualType Ty;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +000010059 unsigned pw = Context.Target.getPointerWidth(0);
10060 if (pw == Context.Target.getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +000010061 Ty = Context.IntTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +000010062 else if (pw == Context.Target.getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +000010063 Ty = Context.LongTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +000010064 else if (pw == Context.Target.getLongLongWidth())
10065 Ty = Context.LongLongTy;
10066 else {
10067 assert(!"I don't know size of pointer!");
10068 Ty = Context.IntTy;
10069 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +000010070
Sebastian Redlf53597f2009-03-15 17:47:39 +000010071 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +000010072}
10073
Sean Hunt1e3f5ba2010-04-28 23:02:27 +000010074static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +000010075 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +000010076 if (!SemaRef.getLangOptions().ObjC1)
10077 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010078
Anders Carlssonb76cd3d2009-11-10 04:46:30 +000010079 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10080 if (!PT)
10081 return;
10082
10083 // Check if the destination is of type 'id'.
10084 if (!PT->isObjCIdType()) {
10085 // Check if the destination is the 'NSString' interface.
10086 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10087 if (!ID || !ID->getIdentifier()->isStr("NSString"))
10088 return;
10089 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010090
Anders Carlssonb76cd3d2009-11-10 04:46:30 +000010091 // Strip off any parens and casts.
10092 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
10093 if (!SL || SL->isWide())
10094 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010095
Douglas Gregor849b2432010-03-31 17:46:05 +000010096 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +000010097}
10098
Chris Lattner5cf216b2008-01-04 18:04:52 +000010099bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10100 SourceLocation Loc,
10101 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +000010102 Expr *SrcExpr, AssignmentAction Action,
10103 bool *Complained) {
10104 if (Complained)
10105 *Complained = false;
10106
Chris Lattner5cf216b2008-01-04 18:04:52 +000010107 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +000010108 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +000010109 bool isInvalid = false;
10110 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +000010111 FixItHint Hint;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010112
Chris Lattner5cf216b2008-01-04 18:04:52 +000010113 switch (ConvTy) {
10114 default: assert(0 && "Unknown conversion type");
10115 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +000010116 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +000010117 DiagKind = diag::ext_typecheck_convert_pointer_int;
10118 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +000010119 case IntToPointer:
10120 DiagKind = diag::ext_typecheck_convert_int_pointer;
10121 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +000010122 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +000010123 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +000010124 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +000010125 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10126 SrcType->isObjCObjectPointerType();
Chris Lattner5cf216b2008-01-04 18:04:52 +000010127 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +000010128 case IncompatiblePointerSign:
10129 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10130 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +000010131 case FunctionVoidPointer:
10132 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10133 break;
John McCall86c05f32011-02-01 00:10:29 +000010134 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +000010135 // Perform array-to-pointer decay if necessary.
10136 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10137
John McCall86c05f32011-02-01 00:10:29 +000010138 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10139 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10140 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10141 DiagKind = diag::err_typecheck_incompatible_address_space;
10142 break;
John McCallf85e1932011-06-15 23:02:42 +000010143
10144
10145 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
10146 DiagKind = diag::err_typecheck_incompatible_lifetime;
10147 break;
John McCall86c05f32011-02-01 00:10:29 +000010148 }
10149
10150 llvm_unreachable("unknown error case for discarding qualifiers!");
10151 // fallthrough
10152 }
Chris Lattner5cf216b2008-01-04 18:04:52 +000010153 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +000010154 // If the qualifiers lost were because we were applying the
10155 // (deprecated) C++ conversion from a string literal to a char*
10156 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
10157 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +000010158 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +000010159 // bit of refactoring (so that the second argument is an
10160 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +000010161 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +000010162 // C++ semantics.
10163 if (getLangOptions().CPlusPlus &&
10164 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10165 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +000010166 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10167 break;
Sean Huntc9132b62009-11-08 07:46:34 +000010168 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +000010169 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +000010170 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +000010171 case IntToBlockPointer:
10172 DiagKind = diag::err_int_to_block_pointer;
10173 break;
10174 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +000010175 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +000010176 break;
Steve Naroff39579072008-10-14 22:18:38 +000010177 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +000010178 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +000010179 // it can give a more specific diagnostic.
10180 DiagKind = diag::warn_incompatible_qualified_id;
10181 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +000010182 case IncompatibleVectors:
10183 DiagKind = diag::warn_incompatible_vectors;
10184 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +000010185 case Incompatible:
10186 DiagKind = diag::err_typecheck_convert_incompatible;
10187 isInvalid = true;
10188 break;
10189 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000010190
Douglas Gregord4eea832010-04-09 00:35:39 +000010191 QualType FirstType, SecondType;
10192 switch (Action) {
10193 case AA_Assigning:
10194 case AA_Initializing:
10195 // The destination type comes first.
10196 FirstType = DstType;
10197 SecondType = SrcType;
10198 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +000010199
Douglas Gregord4eea832010-04-09 00:35:39 +000010200 case AA_Returning:
10201 case AA_Passing:
10202 case AA_Converting:
10203 case AA_Sending:
10204 case AA_Casting:
10205 // The source type comes first.
10206 FirstType = SrcType;
10207 SecondType = DstType;
10208 break;
10209 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +000010210
Douglas Gregord4eea832010-04-09 00:35:39 +000010211 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +000010212 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor926df6c2011-06-11 01:09:30 +000010213 if (CheckInferredResultType)
10214 EmitRelatedResultTypeNote(SrcExpr);
10215
Douglas Gregora41a8c52010-04-22 00:20:18 +000010216 if (Complained)
10217 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +000010218 return isInvalid;
10219}
Anders Carlssone21555e2008-11-30 19:50:32 +000010220
Chris Lattner3bf68932009-04-25 21:59:05 +000010221bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +000010222 llvm::APSInt ICEResult;
10223 if (E->isIntegerConstantExpr(ICEResult, Context)) {
10224 if (Result)
10225 *Result = ICEResult;
10226 return false;
10227 }
10228
Anders Carlssone21555e2008-11-30 19:50:32 +000010229 Expr::EvalResult EvalResult;
10230
Mike Stumpeed9cac2009-02-19 03:04:26 +000010231 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +000010232 EvalResult.HasSideEffects) {
10233 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
10234
10235 if (EvalResult.Diag) {
10236 // We only show the note if it's not the usual "invalid subexpression"
10237 // or if it's actually in a subexpression.
10238 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
10239 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
10240 Diag(EvalResult.DiagLoc, EvalResult.Diag);
10241 }
Mike Stumpeed9cac2009-02-19 03:04:26 +000010242
Anders Carlssone21555e2008-11-30 19:50:32 +000010243 return true;
10244 }
10245
Eli Friedman3b5ccca2009-04-25 22:26:58 +000010246 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
10247 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +000010248
Eli Friedman3b5ccca2009-04-25 22:26:58 +000010249 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +000010250 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
10251 != Diagnostic::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +000010252 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +000010253
Anders Carlssone21555e2008-11-30 19:50:32 +000010254 if (Result)
10255 *Result = EvalResult.Val.getInt();
10256 return false;
10257}
Douglas Gregore0762c92009-06-19 23:52:42 +000010258
Douglas Gregor2afce722009-11-26 00:44:06 +000010259void
Mike Stump1eb44332009-09-09 15:08:12 +000010260Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +000010261 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +000010262 ExpressionEvaluationContextRecord(NewContext,
10263 ExprTemporaries.size(),
10264 ExprNeedsCleanups));
10265 ExprNeedsCleanups = false;
Douglas Gregorac7610d2009-06-22 20:57:11 +000010266}
10267
Mike Stump1eb44332009-09-09 15:08:12 +000010268void
Douglas Gregor2afce722009-11-26 00:44:06 +000010269Sema::PopExpressionEvaluationContext() {
10270 // Pop the current expression evaluation context off the stack.
10271 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
10272 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010273
Douglas Gregor06d33692009-12-12 07:57:52 +000010274 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
10275 if (Rec.PotentiallyReferenced) {
10276 // Mark any remaining declarations in the current position of the stack
10277 // as "referenced". If they were not meant to be referenced, semantic
10278 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010279 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +000010280 I = Rec.PotentiallyReferenced->begin(),
10281 IEnd = Rec.PotentiallyReferenced->end();
10282 I != IEnd; ++I)
10283 MarkDeclarationReferenced(I->first, I->second);
10284 }
10285
10286 if (Rec.PotentiallyDiagnosed) {
10287 // Emit any pending diagnostics.
10288 for (PotentiallyEmittedDiagnostics::iterator
10289 I = Rec.PotentiallyDiagnosed->begin(),
10290 IEnd = Rec.PotentiallyDiagnosed->end();
10291 I != IEnd; ++I)
10292 Diag(I->first, I->second);
10293 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010294 }
Douglas Gregor2afce722009-11-26 00:44:06 +000010295
10296 // When are coming out of an unevaluated context, clear out any
10297 // temporaries that we may have created as part of the evaluation of
10298 // the expression in that context: they aren't relevant because they
10299 // will never be constructed.
John McCallf85e1932011-06-15 23:02:42 +000010300 if (Rec.Context == Unevaluated) {
Douglas Gregor2afce722009-11-26 00:44:06 +000010301 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
10302 ExprTemporaries.end());
John McCallf85e1932011-06-15 23:02:42 +000010303 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
10304
10305 // Otherwise, merge the contexts together.
10306 } else {
10307 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
10308 }
Douglas Gregor2afce722009-11-26 00:44:06 +000010309
10310 // Destroy the popped expression evaluation record.
10311 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +000010312}
Douglas Gregore0762c92009-06-19 23:52:42 +000010313
John McCallf85e1932011-06-15 23:02:42 +000010314void Sema::DiscardCleanupsInEvaluationContext() {
10315 ExprTemporaries.erase(
10316 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
10317 ExprTemporaries.end());
10318 ExprNeedsCleanups = false;
10319}
10320
Douglas Gregore0762c92009-06-19 23:52:42 +000010321/// \brief Note that the given declaration was referenced in the source code.
10322///
10323/// This routine should be invoke whenever a given declaration is referenced
10324/// in the source code, and where that reference occurred. If this declaration
10325/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
10326/// C99 6.9p3), then the declaration will be marked as used.
10327///
10328/// \param Loc the location where the declaration was referenced.
10329///
10330/// \param D the declaration that has been referenced by the source code.
10331void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
10332 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +000010333
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +000010334 D->setReferenced();
10335
Douglas Gregorc070cc62010-06-17 23:14:26 +000010336 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +000010337 return;
Mike Stump1eb44332009-09-09 15:08:12 +000010338
Douglas Gregorb5352cf2009-10-08 21:35:42 +000010339 // Mark a parameter or variable declaration "used", regardless of whether we're in a
10340 // template or not. The reason for this is that unevaluated expressions
10341 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
10342 // -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010343 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +000010344 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +000010345 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +000010346 return;
10347 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +000010348
Douglas Gregorfc2ca562010-04-07 20:29:57 +000010349 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
10350 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +000010351
Douglas Gregore0762c92009-06-19 23:52:42 +000010352 // Do not mark anything as "used" within a dependent context; wait for
10353 // an instantiation.
10354 if (CurContext->isDependentContext())
10355 return;
Mike Stump1eb44332009-09-09 15:08:12 +000010356
Douglas Gregor2afce722009-11-26 00:44:06 +000010357 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +000010358 case Unevaluated:
10359 // We are in an expression that is not potentially evaluated; do nothing.
10360 return;
Mike Stump1eb44332009-09-09 15:08:12 +000010361
Douglas Gregorac7610d2009-06-22 20:57:11 +000010362 case PotentiallyEvaluated:
10363 // We are in a potentially-evaluated expression, so this declaration is
10364 // "used"; handle this below.
10365 break;
Mike Stump1eb44332009-09-09 15:08:12 +000010366
Douglas Gregorac7610d2009-06-22 20:57:11 +000010367 case PotentiallyPotentiallyEvaluated:
10368 // We are in an expression that may be potentially evaluated; queue this
10369 // declaration reference until we know whether the expression is
10370 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +000010371 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +000010372 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010373
10374 case PotentiallyEvaluatedIfUsed:
10375 // Referenced declarations will only be used if the construct in the
10376 // containing expression is used.
10377 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +000010378 }
Mike Stump1eb44332009-09-09 15:08:12 +000010379
Douglas Gregore0762c92009-06-19 23:52:42 +000010380 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +000010381 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Sean Hunt1e238652011-05-12 03:51:51 +000010382 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor()) {
10383 if (Constructor->isTrivial())
Chandler Carruth4e6fbce2010-08-23 07:55:51 +000010384 return;
10385 if (!Constructor->isUsed(false))
10386 DefineImplicitDefaultConstructor(Loc, Constructor);
Sean Hunt509f0482011-05-14 18:20:50 +000010387 } else if (Constructor->isDefaulted() &&
Sean Hunt49634cf2011-05-13 06:10:58 +000010388 Constructor->isCopyConstructor()) {
Douglas Gregorc070cc62010-06-17 23:14:26 +000010389 if (!Constructor->isUsed(false))
Sean Hunt49634cf2011-05-13 06:10:58 +000010390 DefineImplicitCopyConstructor(Loc, Constructor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010391 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010392
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010393 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010394 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Sean Huntcb45a0f2011-05-12 22:46:25 +000010395 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010396 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010397 if (Destructor->isVirtual())
10398 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010399 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Sean Hunt2b188082011-05-14 05:23:28 +000010400 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010401 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorc070cc62010-06-17 23:14:26 +000010402 if (!MethodDecl->isUsed(false))
Douglas Gregor39957dc2010-05-01 15:04:51 +000010403 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010404 } else if (MethodDecl->isVirtual())
10405 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010406 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +000010407 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall15e310a2011-02-19 02:53:41 +000010408 // Recursive functions should be marked when used from another function.
10409 if (CurContext == Function) return;
10410
Mike Stump1eb44332009-09-09 15:08:12 +000010411 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +000010412 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +000010413 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010414 bool AlreadyInstantiated = false;
10415 if (FunctionTemplateSpecializationInfo *SpecInfo
10416 = Function->getTemplateSpecializationInfo()) {
10417 if (SpecInfo->getPointOfInstantiation().isInvalid())
10418 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010419 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +000010420 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010421 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010422 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010423 = Function->getMemberSpecializationInfo()) {
10424 if (MSInfo->getPointOfInstantiation().isInvalid())
10425 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010426 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +000010427 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010428 AlreadyInstantiated = true;
10429 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010430
Douglas Gregor60406be2010-01-16 22:29:39 +000010431 if (!AlreadyInstantiated) {
10432 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
10433 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
10434 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
10435 Loc));
10436 else
Chandler Carruth62c78d52010-08-25 08:44:16 +000010437 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +000010438 }
John McCall15e310a2011-02-19 02:53:41 +000010439 } else {
10440 // Walk redefinitions, as some of them may be instantiable.
Gabor Greif40181c42010-08-28 00:16:06 +000010441 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
10442 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +000010443 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +000010444 MarkDeclarationReferenced(Loc, *i);
10445 }
John McCall15e310a2011-02-19 02:53:41 +000010446 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010447
John McCall15e310a2011-02-19 02:53:41 +000010448 // Keep track of used but undefined functions.
10449 if (!Function->isPure() && !Function->hasBody() &&
10450 Function->getLinkage() != ExternalLinkage) {
10451 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
10452 if (old.isInvalid()) old = Loc;
10453 }
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +000010454
John McCall15e310a2011-02-19 02:53:41 +000010455 Function->setUsed(true);
Douglas Gregore0762c92009-06-19 23:52:42 +000010456 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +000010457 }
Mike Stump1eb44332009-09-09 15:08:12 +000010458
Douglas Gregore0762c92009-06-19 23:52:42 +000010459 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +000010460 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +000010461 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010462 Var->getInstantiatedFromStaticDataMember()) {
10463 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10464 assert(MSInfo && "Missing member specialization information?");
10465 if (MSInfo->getPointOfInstantiation().isInvalid() &&
10466 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
10467 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redlf79a7192011-04-29 08:19:30 +000010468 // This is a modification of an existing AST node. Notify listeners.
10469 if (ASTMutationListener *L = getASTMutationListener())
10470 L->StaticDataMemberInstantiated(Var);
Chandler Carruth62c78d52010-08-25 08:44:16 +000010471 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010472 }
10473 }
Mike Stump1eb44332009-09-09 15:08:12 +000010474
John McCall77efc682011-02-21 19:25:48 +000010475 // Keep track of used but undefined variables. We make a hole in
10476 // the warning for static const data members with in-line
10477 // initializers.
John McCall15e310a2011-02-19 02:53:41 +000010478 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall77efc682011-02-21 19:25:48 +000010479 && Var->getLinkage() != ExternalLinkage
10480 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall15e310a2011-02-19 02:53:41 +000010481 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
10482 if (old.isInvalid()) old = Loc;
10483 }
Douglas Gregor7caa6822009-07-24 20:34:43 +000010484
Douglas Gregore0762c92009-06-19 23:52:42 +000010485 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +000010486 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +000010487 }
Douglas Gregore0762c92009-06-19 23:52:42 +000010488}
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010489
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010490namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010491 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010492 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010493 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010494 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10495 Sema &S;
10496 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010497
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010498 public:
10499 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010500
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010501 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010502
10503 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10504 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010505 };
10506}
10507
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010508bool MarkReferencedDecls::TraverseTemplateArgument(
10509 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010510 if (Arg.getKind() == TemplateArgument::Declaration) {
10511 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
10512 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010513
10514 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010515}
10516
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010517bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010518 if (ClassTemplateSpecializationDecl *Spec
10519 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10520 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +000010521 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010522 }
10523
Chandler Carruthe3e210c2010-06-10 10:31:57 +000010524 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010525}
10526
10527void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10528 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010529 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010530}
10531
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010532namespace {
10533 /// \brief Helper class that marks all of the declarations referenced by
10534 /// potentially-evaluated subexpressions as "referenced".
10535 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10536 Sema &S;
10537
10538 public:
10539 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10540
10541 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
10542
10543 void VisitDeclRefExpr(DeclRefExpr *E) {
10544 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10545 }
10546
10547 void VisitMemberExpr(MemberExpr *E) {
10548 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010549 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010550 }
10551
10552 void VisitCXXNewExpr(CXXNewExpr *E) {
10553 if (E->getConstructor())
10554 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
10555 if (E->getOperatorNew())
10556 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
10557 if (E->getOperatorDelete())
10558 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010559 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010560 }
10561
10562 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10563 if (E->getOperatorDelete())
10564 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +000010565 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10566 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10567 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10568 S.MarkDeclarationReferenced(E->getLocStart(),
10569 S.LookupDestructor(Record));
10570 }
10571
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010572 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010573 }
10574
10575 void VisitCXXConstructExpr(CXXConstructExpr *E) {
10576 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010577 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010578 }
10579
10580 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
10581 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10582 }
Douglas Gregor102ff972010-10-19 17:17:35 +000010583
10584 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10585 Visit(E->getExpr());
10586 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010587 };
10588}
10589
10590/// \brief Mark any declarations that appear within this expression or any
10591/// potentially-evaluated subexpressions as "referenced".
10592void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
10593 EvaluatedExprMarker(*this).Visit(E);
10594}
10595
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010596/// \brief Emit a diagnostic that describes an effect on the run-time behavior
10597/// of the program being compiled.
10598///
10599/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010600/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010601/// possibility that the code will actually be executable. Code in sizeof()
10602/// expressions, code used only during overload resolution, etc., are not
10603/// potentially evaluated. This routine will suppress such diagnostics or,
10604/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010605/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010606/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010607///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010608/// This routine should be used for all diagnostics that describe the run-time
10609/// behavior of a program, such as passing a non-POD value through an ellipsis.
10610/// Failure to do so will likely result in spurious diagnostics or failures
10611/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek762696f2011-02-23 01:51:43 +000010612bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010613 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +000010614 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010615 case Unevaluated:
10616 // The argument will never be evaluated, so don't complain.
10617 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010618
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010619 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010620 case PotentiallyEvaluatedIfUsed:
Ted Kremenek351ba912011-02-23 01:52:04 +000010621 if (stmt && getCurFunctionOrMethodDecl()) {
10622 FunctionScopes.back()->PossiblyUnreachableDiags.
10623 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
10624 }
10625 else
10626 Diag(Loc, PD);
10627
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010628 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010629
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010630 case PotentiallyPotentiallyEvaluated:
10631 ExprEvalContexts.back().addDiagnostic(Loc, PD);
10632 break;
10633 }
10634
10635 return false;
10636}
10637
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010638bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
10639 CallExpr *CE, FunctionDecl *FD) {
10640 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
10641 return false;
10642
10643 PartialDiagnostic Note =
10644 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
10645 << FD->getDeclName() : PDiag();
10646 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010647
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010648 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010649 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010650 PDiag(diag::err_call_function_incomplete_return)
10651 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010652 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010653 << CE->getSourceRange(),
10654 std::make_pair(NoteLoc, Note)))
10655 return true;
10656
10657 return false;
10658}
10659
Douglas Gregor92c3a042011-01-19 16:50:08 +000010660// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +000010661// will prevent this condition from triggering, which is what we want.
10662void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
10663 SourceLocation Loc;
10664
John McCalla52ef082009-11-11 02:41:58 +000010665 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +000010666 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +000010667
John McCall5a881bb2009-10-12 21:59:07 +000010668 if (isa<BinaryOperator>(E)) {
10669 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +000010670 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +000010671 return;
10672
Douglas Gregor92c3a042011-01-19 16:50:08 +000010673 IsOrAssign = Op->getOpcode() == BO_OrAssign;
10674
John McCallc8d8ac52009-11-12 00:06:05 +000010675 // Greylist some idioms by putting them into a warning subcategory.
10676 if (ObjCMessageExpr *ME
10677 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
10678 Selector Sel = ME->getSelector();
10679
John McCallc8d8ac52009-11-12 00:06:05 +000010680 // self = [<foo> init...]
Douglas Gregor813d8342011-02-18 22:29:55 +000010681 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +000010682 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10683
10684 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +000010685 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +000010686 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10687 }
John McCalla52ef082009-11-11 02:41:58 +000010688
John McCall5a881bb2009-10-12 21:59:07 +000010689 Loc = Op->getOperatorLoc();
10690 } else if (isa<CXXOperatorCallExpr>(E)) {
10691 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +000010692 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +000010693 return;
10694
Douglas Gregor92c3a042011-01-19 16:50:08 +000010695 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +000010696 Loc = Op->getOperatorLoc();
10697 } else {
10698 // Not an assignment.
10699 return;
10700 }
10701
Douglas Gregor55b38842010-04-14 16:09:52 +000010702 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +000010703
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000010704 SourceLocation Open = E->getSourceRange().getBegin();
10705 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
10706 Diag(Loc, diag::note_condition_assign_silence)
10707 << FixItHint::CreateInsertion(Open, "(")
10708 << FixItHint::CreateInsertion(Close, ")");
10709
Douglas Gregor92c3a042011-01-19 16:50:08 +000010710 if (IsOrAssign)
10711 Diag(Loc, diag::note_condition_or_assign_to_comparison)
10712 << FixItHint::CreateReplacement(Loc, "!=");
10713 else
10714 Diag(Loc, diag::note_condition_assign_to_comparison)
10715 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +000010716}
10717
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010718/// \brief Redundant parentheses over an equality comparison can indicate
10719/// that the user intended an assignment used as condition.
10720void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000010721 // Don't warn if the parens came from a macro.
10722 SourceLocation parenLoc = parenE->getLocStart();
10723 if (parenLoc.isInvalid() || parenLoc.isMacroID())
10724 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000010725 // Don't warn for dependent expressions.
10726 if (parenE->isTypeDependent())
10727 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000010728
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010729 Expr *E = parenE->IgnoreParens();
10730
10731 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +000010732 if (opE->getOpcode() == BO_EQ &&
10733 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
10734 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010735 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +000010736
Ted Kremenekf7275cd2011-02-02 02:20:30 +000010737 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +000010738 Diag(Loc, diag::note_equality_comparison_silence)
10739 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
10740 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000010741 Diag(Loc, diag::note_equality_comparison_to_assign)
10742 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010743 }
10744}
10745
John Wiegley429bb272011-04-08 18:41:53 +000010746ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +000010747 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010748 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
10749 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +000010750
John McCall864c0412011-04-26 20:42:42 +000010751 ExprResult result = CheckPlaceholderExpr(E);
10752 if (result.isInvalid()) return ExprError();
10753 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000010754
John McCall864c0412011-04-26 20:42:42 +000010755 if (!E->isTypeDependent()) {
John McCallf6a16482010-12-04 03:47:34 +000010756 if (getLangOptions().CPlusPlus)
10757 return CheckCXXBooleanCondition(E); // C++ 6.4p4
10758
John Wiegley429bb272011-04-08 18:41:53 +000010759 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
10760 if (ERes.isInvalid())
10761 return ExprError();
10762 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +000010763
10764 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +000010765 if (!T->isScalarType()) { // C99 6.8.4.1p1
10766 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
10767 << T << E->getSourceRange();
10768 return ExprError();
10769 }
John McCall5a881bb2009-10-12 21:59:07 +000010770 }
10771
John Wiegley429bb272011-04-08 18:41:53 +000010772 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +000010773}
Douglas Gregor586596f2010-05-06 17:25:47 +000010774
John McCall60d7b3a2010-08-24 06:29:42 +000010775ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
10776 Expr *Sub) {
Douglas Gregoreecf38f2010-05-06 21:39:56 +000010777 if (!Sub)
Douglas Gregor586596f2010-05-06 17:25:47 +000010778 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010779
10780 return CheckBooleanCondition(Sub, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +000010781}
John McCall2a984ca2010-10-12 00:20:44 +000010782
John McCall1de4d4e2011-04-07 08:22:57 +000010783namespace {
John McCall755d8492011-04-12 00:42:48 +000010784 /// A visitor for rebuilding a call to an __unknown_any expression
10785 /// to have an appropriate type.
10786 struct RebuildUnknownAnyFunction
10787 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
10788
10789 Sema &S;
10790
10791 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
10792
10793 ExprResult VisitStmt(Stmt *S) {
10794 llvm_unreachable("unexpected statement!");
10795 return ExprError();
10796 }
10797
10798 ExprResult VisitExpr(Expr *expr) {
10799 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
10800 << expr->getSourceRange();
10801 return ExprError();
10802 }
10803
10804 /// Rebuild an expression which simply semantically wraps another
10805 /// expression which it shares the type and value kind of.
10806 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10807 ExprResult subResult = Visit(expr->getSubExpr());
10808 if (subResult.isInvalid()) return ExprError();
10809
10810 Expr *subExpr = subResult.take();
10811 expr->setSubExpr(subExpr);
10812 expr->setType(subExpr->getType());
10813 expr->setValueKind(subExpr->getValueKind());
10814 assert(expr->getObjectKind() == OK_Ordinary);
10815 return expr;
10816 }
10817
10818 ExprResult VisitParenExpr(ParenExpr *paren) {
10819 return rebuildSugarExpr(paren);
10820 }
10821
10822 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10823 return rebuildSugarExpr(op);
10824 }
10825
10826 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10827 ExprResult subResult = Visit(op->getSubExpr());
10828 if (subResult.isInvalid()) return ExprError();
10829
10830 Expr *subExpr = subResult.take();
10831 op->setSubExpr(subExpr);
10832 op->setType(S.Context.getPointerType(subExpr->getType()));
10833 assert(op->getValueKind() == VK_RValue);
10834 assert(op->getObjectKind() == OK_Ordinary);
10835 return op;
10836 }
10837
10838 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
10839 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
10840
10841 expr->setType(decl->getType());
10842
10843 assert(expr->getValueKind() == VK_RValue);
10844 if (S.getLangOptions().CPlusPlus &&
10845 !(isa<CXXMethodDecl>(decl) &&
10846 cast<CXXMethodDecl>(decl)->isInstance()))
10847 expr->setValueKind(VK_LValue);
10848
10849 return expr;
10850 }
10851
10852 ExprResult VisitMemberExpr(MemberExpr *mem) {
10853 return resolveDecl(mem, mem->getMemberDecl());
10854 }
10855
10856 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
10857 return resolveDecl(ref, ref->getDecl());
10858 }
10859 };
10860}
10861
10862/// Given a function expression of unknown-any type, try to rebuild it
10863/// to have a function type.
10864static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
10865 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
10866 if (result.isInvalid()) return ExprError();
10867 return S.DefaultFunctionArrayConversion(result.take());
10868}
10869
10870namespace {
John McCall379b5152011-04-11 07:02:50 +000010871 /// A visitor for rebuilding an expression of type __unknown_anytype
10872 /// into one which resolves the type directly on the referring
10873 /// expression. Strict preservation of the original source
10874 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +000010875 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +000010876 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +000010877
10878 Sema &S;
10879
10880 /// The current destination type.
10881 QualType DestType;
10882
10883 RebuildUnknownAnyExpr(Sema &S, QualType castType)
10884 : S(S), DestType(castType) {}
10885
John McCalla5fc4722011-04-09 22:50:59 +000010886 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +000010887 llvm_unreachable("unexpected statement!");
John McCalla5fc4722011-04-09 22:50:59 +000010888 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000010889 }
10890
John McCall379b5152011-04-11 07:02:50 +000010891 ExprResult VisitExpr(Expr *expr) {
10892 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10893 << expr->getSourceRange();
10894 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000010895 }
10896
John McCall379b5152011-04-11 07:02:50 +000010897 ExprResult VisitCallExpr(CallExpr *call);
10898 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
10899
John McCalla5fc4722011-04-09 22:50:59 +000010900 /// Rebuild an expression which simply semantically wraps another
10901 /// expression which it shares the type and value kind of.
10902 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10903 ExprResult subResult = Visit(expr->getSubExpr());
John McCall755d8492011-04-12 00:42:48 +000010904 if (subResult.isInvalid()) return ExprError();
John McCalla5fc4722011-04-09 22:50:59 +000010905 Expr *subExpr = subResult.take();
10906 expr->setSubExpr(subExpr);
10907 expr->setType(subExpr->getType());
10908 expr->setValueKind(subExpr->getValueKind());
10909 assert(expr->getObjectKind() == OK_Ordinary);
10910 return expr;
10911 }
John McCall1de4d4e2011-04-07 08:22:57 +000010912
John McCalla5fc4722011-04-09 22:50:59 +000010913 ExprResult VisitParenExpr(ParenExpr *paren) {
10914 return rebuildSugarExpr(paren);
10915 }
10916
10917 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10918 return rebuildSugarExpr(op);
10919 }
10920
John McCall755d8492011-04-12 00:42:48 +000010921 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10922 const PointerType *ptr = DestType->getAs<PointerType>();
10923 if (!ptr) {
10924 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
10925 << op->getSourceRange();
10926 return ExprError();
10927 }
10928 assert(op->getValueKind() == VK_RValue);
10929 assert(op->getObjectKind() == OK_Ordinary);
10930 op->setType(DestType);
10931
10932 // Build the sub-expression as if it were an object of the pointee type.
10933 DestType = ptr->getPointeeType();
10934 ExprResult subResult = Visit(op->getSubExpr());
10935 if (subResult.isInvalid()) return ExprError();
10936 op->setSubExpr(subResult.take());
10937 return op;
10938 }
10939
John McCall379b5152011-04-11 07:02:50 +000010940 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCalla5fc4722011-04-09 22:50:59 +000010941
John McCall755d8492011-04-12 00:42:48 +000010942 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCalla5fc4722011-04-09 22:50:59 +000010943
John McCall755d8492011-04-12 00:42:48 +000010944 ExprResult VisitMemberExpr(MemberExpr *mem) {
10945 return resolveDecl(mem, mem->getMemberDecl());
10946 }
John McCalla5fc4722011-04-09 22:50:59 +000010947
10948 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall379b5152011-04-11 07:02:50 +000010949 return resolveDecl(ref, ref->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +000010950 }
10951 };
10952}
10953
John McCall379b5152011-04-11 07:02:50 +000010954/// Rebuilds a call expression which yielded __unknown_anytype.
10955ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
10956 Expr *callee = call->getCallee();
10957
10958 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +000010959 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +000010960 FK_FunctionPointer,
10961 FK_BlockPointer
10962 };
10963
10964 FnKind kind;
10965 QualType type = callee->getType();
John McCallf5307512011-04-27 00:36:17 +000010966 if (type == S.Context.BoundMemberTy) {
10967 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
10968 kind = FK_MemberFunction;
10969 type = Expr::findBoundMemberType(callee);
John McCall379b5152011-04-11 07:02:50 +000010970 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
10971 type = ptr->getPointeeType();
10972 kind = FK_FunctionPointer;
10973 } else {
10974 type = type->castAs<BlockPointerType>()->getPointeeType();
10975 kind = FK_BlockPointer;
10976 }
10977 const FunctionType *fnType = type->castAs<FunctionType>();
10978
10979 // Verify that this is a legal result type of a function.
10980 if (DestType->isArrayType() || DestType->isFunctionType()) {
10981 unsigned diagID = diag::err_func_returning_array_function;
10982 if (kind == FK_BlockPointer)
10983 diagID = diag::err_block_returning_array_function;
10984
10985 S.Diag(call->getExprLoc(), diagID)
10986 << DestType->isFunctionType() << DestType;
10987 return ExprError();
10988 }
10989
10990 // Otherwise, go ahead and set DestType as the call's result.
10991 call->setType(DestType.getNonLValueExprType(S.Context));
10992 call->setValueKind(Expr::getValueKindForType(DestType));
10993 assert(call->getObjectKind() == OK_Ordinary);
10994
10995 // Rebuild the function type, replacing the result type with DestType.
10996 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
10997 DestType = S.Context.getFunctionType(DestType,
10998 proto->arg_type_begin(),
10999 proto->getNumArgs(),
11000 proto->getExtProtoInfo());
11001 else
11002 DestType = S.Context.getFunctionNoProtoType(DestType,
11003 fnType->getExtInfo());
11004
11005 // Rebuild the appropriate pointer-to-function type.
11006 switch (kind) {
John McCallf5307512011-04-27 00:36:17 +000011007 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +000011008 // Nothing to do.
11009 break;
11010
11011 case FK_FunctionPointer:
11012 DestType = S.Context.getPointerType(DestType);
11013 break;
11014
11015 case FK_BlockPointer:
11016 DestType = S.Context.getBlockPointerType(DestType);
11017 break;
11018 }
11019
11020 // Finally, we can recurse.
11021 ExprResult calleeResult = Visit(callee);
11022 if (!calleeResult.isUsable()) return ExprError();
11023 call->setCallee(calleeResult.take());
11024
11025 // Bind a temporary if necessary.
11026 return S.MaybeBindToTemporary(call);
11027}
11028
11029ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall755d8492011-04-12 00:42:48 +000011030 ObjCMethodDecl *method = msg->getMethodDecl();
11031 assert(method && "__unknown_anytype message without result type?");
John McCall379b5152011-04-11 07:02:50 +000011032
John McCall755d8492011-04-12 00:42:48 +000011033 // Verify that this is a legal result type of a call.
11034 if (DestType->isArrayType() || DestType->isFunctionType()) {
11035 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
11036 << DestType->isFunctionType() << DestType;
11037 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011038 }
11039
John McCall755d8492011-04-12 00:42:48 +000011040 assert(method->getResultType() == S.Context.UnknownAnyTy);
11041 method->setResultType(DestType);
11042
John McCall379b5152011-04-11 07:02:50 +000011043 // Change the type of the message.
John McCall755d8492011-04-12 00:42:48 +000011044 msg->setType(DestType.getNonReferenceType());
11045 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000011046
John McCall755d8492011-04-12 00:42:48 +000011047 return S.MaybeBindToTemporary(msg);
John McCall379b5152011-04-11 07:02:50 +000011048}
11049
11050ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall755d8492011-04-12 00:42:48 +000011051 // The only case we should ever see here is a function-to-pointer decay.
John McCall379b5152011-04-11 07:02:50 +000011052 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall379b5152011-04-11 07:02:50 +000011053 assert(ice->getValueKind() == VK_RValue);
11054 assert(ice->getObjectKind() == OK_Ordinary);
11055
John McCall755d8492011-04-12 00:42:48 +000011056 ice->setType(DestType);
11057
John McCall379b5152011-04-11 07:02:50 +000011058 // Rebuild the sub-expression as the pointee (function) type.
11059 DestType = DestType->castAs<PointerType>()->getPointeeType();
11060
11061 ExprResult result = Visit(ice->getSubExpr());
11062 if (!result.isUsable()) return ExprError();
11063
11064 ice->setSubExpr(result.take());
11065 return S.Owned(ice);
11066}
11067
John McCall755d8492011-04-12 00:42:48 +000011068ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall379b5152011-04-11 07:02:50 +000011069 ExprValueKind valueKind = VK_LValue;
John McCall379b5152011-04-11 07:02:50 +000011070 QualType type = DestType;
11071
11072 // We know how to make this work for certain kinds of decls:
11073
11074 // - functions
John McCall755d8492011-04-12 00:42:48 +000011075 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCall379b5152011-04-11 07:02:50 +000011076 // This is true because FunctionDecls must always have function
11077 // type, so we can't be resolving the entire thing at once.
11078 assert(type->isFunctionType());
11079
John McCallf5307512011-04-27 00:36:17 +000011080 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
11081 if (method->isInstance()) {
11082 valueKind = VK_RValue;
11083 type = S.Context.BoundMemberTy;
11084 }
11085
John McCall379b5152011-04-11 07:02:50 +000011086 // Function references aren't l-values in C.
11087 if (!S.getLangOptions().CPlusPlus)
11088 valueKind = VK_RValue;
11089
11090 // - variables
11091 } else if (isa<VarDecl>(decl)) {
John McCall755d8492011-04-12 00:42:48 +000011092 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
11093 type = refTy->getPointeeType();
John McCall379b5152011-04-11 07:02:50 +000011094 } else if (type->isFunctionType()) {
John McCall755d8492011-04-12 00:42:48 +000011095 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
11096 << decl << expr->getSourceRange();
11097 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000011098 }
11099
11100 // - nothing else
11101 } else {
11102 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11103 << decl << expr->getSourceRange();
11104 return ExprError();
11105 }
11106
John McCall755d8492011-04-12 00:42:48 +000011107 decl->setType(DestType);
11108 expr->setType(type);
11109 expr->setValueKind(valueKind);
11110 return S.Owned(expr);
John McCall379b5152011-04-11 07:02:50 +000011111}
11112
John McCall1de4d4e2011-04-07 08:22:57 +000011113/// Check a cast of an unknown-any type. We intentionally only
11114/// trigger this for C-style casts.
John Wiegley429bb272011-04-08 18:41:53 +000011115ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
11116 Expr *castExpr, CastKind &castKind,
11117 ExprValueKind &VK, CXXCastPath &path) {
John McCall1de4d4e2011-04-07 08:22:57 +000011118 // Rewrite the casted expression from scratch.
John McCalla5fc4722011-04-09 22:50:59 +000011119 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
11120 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000011121
John McCalla5fc4722011-04-09 22:50:59 +000011122 castExpr = result.take();
11123 VK = castExpr->getValueKind();
11124 castKind = CK_NoOp;
11125
11126 return castExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000011127}
11128
11129static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
11130 Expr *orig = e;
John McCall379b5152011-04-11 07:02:50 +000011131 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000011132 while (true) {
11133 e = e->IgnoreParenImpCasts();
John McCall379b5152011-04-11 07:02:50 +000011134 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall1de4d4e2011-04-07 08:22:57 +000011135 e = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000011136 diagID = diag::err_uncasted_call_of_unknown_any;
11137 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000011138 break;
John McCall379b5152011-04-11 07:02:50 +000011139 }
John McCall1de4d4e2011-04-07 08:22:57 +000011140 }
11141
John McCall379b5152011-04-11 07:02:50 +000011142 SourceLocation loc;
11143 NamedDecl *d;
11144 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11145 loc = ref->getLocation();
11146 d = ref->getDecl();
11147 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
11148 loc = mem->getMemberLoc();
11149 d = mem->getMemberDecl();
11150 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
11151 diagID = diag::err_uncasted_call_of_unknown_any;
11152 loc = msg->getSelectorLoc();
11153 d = msg->getMethodDecl();
11154 assert(d && "unknown method returning __unknown_any?");
11155 } else {
11156 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11157 << e->getSourceRange();
11158 return ExprError();
11159 }
11160
11161 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000011162
11163 // Never recoverable.
11164 return ExprError();
11165}
11166
John McCall2a984ca2010-10-12 00:20:44 +000011167/// Check for operands with placeholder types and complain if found.
11168/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000011169ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall1de4d4e2011-04-07 08:22:57 +000011170 // Placeholder types are always *exactly* the appropriate builtin type.
11171 QualType type = E->getType();
John McCall2a984ca2010-10-12 00:20:44 +000011172
John McCall1de4d4e2011-04-07 08:22:57 +000011173 // Overloaded expressions.
11174 if (type == Context.OverloadTy)
11175 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregordb2eae62011-03-16 19:16:25 +000011176 E->getSourceRange(),
John McCall1de4d4e2011-04-07 08:22:57 +000011177 QualType(),
11178 diag::err_ovl_unresolvable);
11179
John McCall864c0412011-04-26 20:42:42 +000011180 // Bound member functions.
11181 if (type == Context.BoundMemberTy) {
11182 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
11183 << E->getSourceRange();
11184 return ExprError();
11185 }
11186
John McCall1de4d4e2011-04-07 08:22:57 +000011187 // Expressions of unknown type.
11188 if (type == Context.UnknownAnyTy)
11189 return diagnoseUnknownAnyExpr(*this, E);
11190
11191 assert(!type->isPlaceholderType());
11192 return Owned(E);
John McCall2a984ca2010-10-12 00:20:44 +000011193}
Richard Trieubb9b80c2011-04-21 21:44:26 +000011194
11195bool Sema::CheckCaseExpression(Expr *expr) {
11196 if (expr->isTypeDependent())
11197 return true;
11198 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
11199 return expr->getType()->isIntegralOrEnumerationType();
11200 return false;
11201}