blob: 20b92b84203f5d3f3fc51e5b7284f0e1820e14f5 [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);
90 Diag(D->getLocation(), diag::note_unavailable_here) << true;
91 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;
117 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
118 break;
119 }
120
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000121 // Warn if this is used but marked unused.
122 if (D->hasAttr<UnusedAttr>())
123 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
124
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000125 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000126}
127
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000128/// \brief Retrieve the message suffix that should be added to a
129/// diagnostic complaining about the given function being deleted or
130/// unavailable.
131std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
132 // FIXME: C++0x implicitly-deleted special member functions could be
133 // detected here so that we could improve diagnostics to say, e.g.,
134 // "base class 'A' had a deleted copy constructor".
135 if (FD->isDeleted())
136 return std::string();
137
138 std::string Message;
139 if (FD->getAvailability(&Message))
140 return ": " + Message;
141
142 return std::string();
143}
144
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000145/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +0000146/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000147/// attribute. It warns if call does not have the sentinel argument.
148///
149void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000150 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000151 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000152 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000153 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000154
155 // FIXME: In C++0x, if any of the arguments are parameter pack
156 // expansions, we can't check for the sentinel now.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000157 int sentinelPos = attr->getSentinel();
158 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +0000159
Mike Stump390b4cc2009-05-16 07:39:55 +0000160 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
161 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000162 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000163 bool warnNotEnoughArgs = false;
164 int isMethod = 0;
165 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
166 // skip over named parameters.
167 ObjCMethodDecl::param_iterator P, E = MD->param_end();
168 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
169 if (nullPos)
170 --nullPos;
171 else
172 ++i;
173 }
174 warnNotEnoughArgs = (P != E || i >= NumArgs);
175 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000176 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000177 // skip over named parameters.
178 ObjCMethodDecl::param_iterator P, E = FD->param_end();
179 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
180 if (nullPos)
181 --nullPos;
182 else
183 ++i;
184 }
185 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000186 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000187 // block or function pointer call.
188 QualType Ty = V->getType();
189 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000190 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000191 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
192 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000193 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
194 unsigned NumArgsInProto = Proto->getNumArgs();
195 unsigned k;
196 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
197 if (nullPos)
198 --nullPos;
199 else
200 ++i;
201 }
202 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
203 }
204 if (Ty->isBlockPointerType())
205 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000206 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000207 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000208 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000209 return;
210
211 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000212 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000213 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000214 return;
215 }
216 int sentinel = i;
217 while (sentinelPos > 0 && i < NumArgs-1) {
218 --sentinelPos;
219 ++i;
220 }
221 if (sentinelPos > 0) {
222 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000223 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000224 return;
225 }
226 while (i < NumArgs-1) {
227 ++i;
228 ++sentinel;
229 }
230 Expr *sentinelExpr = Args[sentinel];
John McCall8eb662e2010-05-06 23:53:00 +0000231 if (!sentinelExpr) return;
232 if (sentinelExpr->isTypeDependent()) return;
233 if (sentinelExpr->isValueDependent()) return;
Anders Carlsson343e6ff2010-11-05 15:21:33 +0000234
235 // nullptr_t is always treated as null.
236 if (sentinelExpr->getType()->isNullPtrType()) return;
237
Fariborz Jahanian9ccd7252010-07-14 16:37:51 +0000238 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall8eb662e2010-05-06 23:53:00 +0000239 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
240 Expr::NPC_ValueDependentIsNull))
241 return;
242
243 // Unfortunately, __null has type 'int'.
244 if (isa<GNUNullExpr>(sentinelExpr)) return;
245
246 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
247 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000248}
249
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000250SourceRange Sema::getExprRange(ExprTy *E) const {
251 Expr *Ex = (Expr *)E;
252 return Ex? Ex->getSourceRange() : SourceRange();
253}
254
Chris Lattnere7a2e912008-07-25 21:10:04 +0000255//===----------------------------------------------------------------------===//
256// Standard Promotions and Conversions
257//===----------------------------------------------------------------------===//
258
Chris Lattnere7a2e912008-07-25 21:10:04 +0000259/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000260ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000261 QualType Ty = E->getType();
262 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
263
Chris Lattnere7a2e912008-07-25 21:10:04 +0000264 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000265 E = ImpCastExprToType(E, Context.getPointerType(Ty),
266 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000267 else if (Ty->isArrayType()) {
268 // In C90 mode, arrays only promote to pointers if the array expression is
269 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
270 // type 'array of type' is converted to an expression that has type 'pointer
271 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
272 // that has type 'array of type' ...". The relevant change is "an lvalue"
273 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000274 //
275 // C++ 4.2p1:
276 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
277 // T" can be converted to an rvalue of type "pointer to T".
278 //
John McCall7eb0a9e2010-11-24 05:12:34 +0000279 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000280 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
281 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000282 }
John Wiegley429bb272011-04-08 18:41:53 +0000283 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000284}
285
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000286static void CheckForNullPointerDereference(Sema &S, Expr *E) {
287 // Check to see if we are dereferencing a null pointer. If so,
288 // and if not volatile-qualified, this is undefined behavior that the
289 // optimizer will delete, so warn about it. People sometimes try to use this
290 // to get a deterministic trap and are surprised by clang's behavior. This
291 // only handles the pattern "*null", which is a very syntactic check.
292 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
293 if (UO->getOpcode() == UO_Deref &&
294 UO->getSubExpr()->IgnoreParenCasts()->
295 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
296 !UO->getType().isVolatileQualified()) {
297 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
298 S.PDiag(diag::warn_indirection_through_null)
299 << UO->getSubExpr()->getSourceRange());
300 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
301 S.PDiag(diag::note_indirection_through_null));
302 }
303}
304
John Wiegley429bb272011-04-08 18:41:53 +0000305ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000306 // C++ [conv.lval]p1:
307 // A glvalue of a non-function, non-array type T can be
308 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000309 if (!E->isGLValue()) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +0000310
John McCall409fa9a2010-12-06 20:48:59 +0000311 QualType T = E->getType();
312 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000313
John McCall409fa9a2010-12-06 20:48:59 +0000314 // Create a load out of an ObjCProperty l-value, if necessary.
315 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley429bb272011-04-08 18:41:53 +0000316 ExprResult Res = ConvertPropertyForRValue(E);
317 if (Res.isInvalid())
318 return Owned(E);
319 E = Res.take();
John McCall409fa9a2010-12-06 20:48:59 +0000320 if (!E->isGLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000321 return Owned(E);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000322 }
John McCall409fa9a2010-12-06 20:48:59 +0000323
324 // We don't want to throw lvalue-to-rvalue casts on top of
325 // expressions of certain types in C++.
326 if (getLangOptions().CPlusPlus &&
327 (E->getType() == Context.OverloadTy ||
328 T->isDependentType() ||
329 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000330 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000331
332 // The C standard is actually really unclear on this point, and
333 // DR106 tells us what the result should be but not why. It's
334 // generally best to say that void types just doesn't undergo
335 // lvalue-to-rvalue at all. Note that expressions of unqualified
336 // 'void' type are never l-values, but qualified void can be.
337 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000338 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000339
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000340 CheckForNullPointerDereference(*this, E);
341
John McCall409fa9a2010-12-06 20:48:59 +0000342 // C++ [conv.lval]p1:
343 // [...] If T is a non-class type, the type of the prvalue is the
344 // cv-unqualified version of T. Otherwise, the type of the
345 // rvalue is T.
346 //
347 // C99 6.3.2.1p2:
348 // If the lvalue has qualified type, the value has the unqualified
349 // version of the type of the lvalue; otherwise, the value has the
350 // type of the lvalue.
351 if (T.hasQualifiers())
352 T = T.getUnqualifiedType();
353
Ted Kremenek3aea4da2011-03-01 18:41:00 +0000354 CheckArrayAccess(E);
Ted Kremeneka0125d82011-02-16 01:57:07 +0000355
John Wiegley429bb272011-04-08 18:41:53 +0000356 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
357 E, 0, VK_RValue));
John McCall409fa9a2010-12-06 20:48:59 +0000358}
359
John Wiegley429bb272011-04-08 18:41:53 +0000360ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
361 ExprResult Res = DefaultFunctionArrayConversion(E);
362 if (Res.isInvalid())
363 return ExprError();
364 Res = DefaultLvalueConversion(Res.take());
365 if (Res.isInvalid())
366 return ExprError();
367 return move(Res);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000368}
369
370
Chris Lattnere7a2e912008-07-25 21:10:04 +0000371/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000372/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000373/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000374/// apply if the array is an argument to the sizeof or address (&) operators.
375/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000376ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000377 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000378 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
379 if (Res.isInvalid())
380 return Owned(E);
381 E = Res.take();
John McCall0ae287a2010-12-01 04:43:34 +0000382
383 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000384 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCall0ae287a2010-12-01 04:43:34 +0000385
386 // Try to perform integral promotions if the object has a theoretically
387 // promotable type.
388 if (Ty->isIntegralOrUnscopedEnumerationType()) {
389 // C99 6.3.1.1p2:
390 //
391 // The following may be used in an expression wherever an int or
392 // unsigned int may be used:
393 // - an object or expression with an integer type whose integer
394 // conversion rank is less than or equal to the rank of int
395 // and unsigned int.
396 // - A bit-field of type _Bool, int, signed int, or unsigned int.
397 //
398 // If an int can represent all values of the original type, the
399 // value is converted to an int; otherwise, it is converted to an
400 // unsigned int. These are called the integer promotions. All
401 // other types are unchanged by the integer promotions.
402
403 QualType PTy = Context.isPromotableBitField(E);
404 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000405 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
406 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000407 }
408 if (Ty->isPromotableIntegerType()) {
409 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000410 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
411 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000412 }
Eli Friedman04e83572009-08-20 04:21:42 +0000413 }
John Wiegley429bb272011-04-08 18:41:53 +0000414 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000415}
416
Chris Lattner05faf172008-07-25 22:25:12 +0000417/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000418/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000419/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000420ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
421 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000422 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000423
John Wiegley429bb272011-04-08 18:41:53 +0000424 ExprResult Res = UsualUnaryConversions(E);
425 if (Res.isInvalid())
426 return Owned(E);
427 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000428
Chris Lattner05faf172008-07-25 22:25:12 +0000429 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000430 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000431 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
432
433 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000434}
435
Chris Lattner312531a2009-04-12 08:11:20 +0000436/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
437/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley429bb272011-04-08 18:41:53 +0000438/// interfaces passed by value.
439ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
Chris Lattner40378332010-05-16 04:01:30 +0000440 FunctionDecl *FDecl) {
John Wiegley429bb272011-04-08 18:41:53 +0000441 ExprResult ExprRes = DefaultArgumentPromotion(E);
442 if (ExprRes.isInvalid())
443 return ExprError();
444 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Chris Lattner40378332010-05-16 04:01:30 +0000446 // __builtin_va_start takes the second argument as a "varargs" argument, but
447 // it doesn't actually do anything with it. It doesn't need to be non-pod
448 // etc.
449 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
John Wiegley429bb272011-04-08 18:41:53 +0000450 return Owned(E);
Chris Lattner40378332010-05-16 04:01:30 +0000451
John Wiegley429bb272011-04-08 18:41:53 +0000452 if (E->getType()->isObjCObjectType() &&
453 DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000454 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
John Wiegley429bb272011-04-08 18:41:53 +0000455 << E->getType() << CT))
456 return ExprError();
Douglas Gregor75b699a2009-12-12 07:25:49 +0000457
John Wiegley429bb272011-04-08 18:41:53 +0000458 if (!E->getType()->isPODType() &&
459 DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000460 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
John Wiegley429bb272011-04-08 18:41:53 +0000461 << E->getType() << CT))
462 return ExprError();
Chris Lattner312531a2009-04-12 08:11:20 +0000463
John Wiegley429bb272011-04-08 18:41:53 +0000464 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000465}
466
Chris Lattnere7a2e912008-07-25 21:10:04 +0000467/// UsualArithmeticConversions - Performs various conversions that are common to
468/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000469/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000470/// responsible for emitting appropriate error diagnostics.
471/// FIXME: verify the conversion rules for "complex int" are consistent with
472/// GCC.
John Wiegley429bb272011-04-08 18:41:53 +0000473QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr, ExprResult &rhsExpr,
Chris Lattnere7a2e912008-07-25 21:10:04 +0000474 bool isCompAssign) {
John Wiegley429bb272011-04-08 18:41:53 +0000475 if (!isCompAssign) {
476 lhsExpr = UsualUnaryConversions(lhsExpr.take());
477 if (lhsExpr.isInvalid())
478 return QualType();
479 }
Eli Friedmanab3a8522009-03-28 01:22:36 +0000480
John Wiegley429bb272011-04-08 18:41:53 +0000481 rhsExpr = UsualUnaryConversions(rhsExpr.take());
482 if (rhsExpr.isInvalid())
483 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000484
Mike Stump1eb44332009-09-09 15:08:12 +0000485 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000486 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000487 QualType lhs =
John Wiegley429bb272011-04-08 18:41:53 +0000488 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000489 QualType rhs =
John Wiegley429bb272011-04-08 18:41:53 +0000490 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000491
492 // If both types are identical, no conversion is needed.
493 if (lhs == rhs)
494 return lhs;
495
496 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
497 // The caller can deal with this (e.g. pointer + int).
498 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
499 return lhs;
500
John McCallcf33b242010-11-13 08:17:45 +0000501 // Apply unary and bitfield promotions to the LHS's type.
502 QualType lhs_unpromoted = lhs;
503 if (lhs->isPromotableIntegerType())
504 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley429bb272011-04-08 18:41:53 +0000505 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +0000506 if (!LHSBitfieldPromoteTy.isNull())
507 lhs = LHSBitfieldPromoteTy;
John McCallcf33b242010-11-13 08:17:45 +0000508 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000509 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000510
John McCallcf33b242010-11-13 08:17:45 +0000511 // If both types are identical, no conversion is needed.
512 if (lhs == rhs)
513 return lhs;
514
515 // At this point, we have two different arithmetic types.
516
517 // Handle complex types first (C99 6.3.1.8p1).
518 bool LHSComplexFloat = lhs->isComplexType();
519 bool RHSComplexFloat = rhs->isComplexType();
520 if (LHSComplexFloat || RHSComplexFloat) {
521 // if we have an integer operand, the result is the complex type.
522
John McCall2bb5d002010-11-13 09:02:35 +0000523 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
524 if (rhs->isIntegerType()) {
525 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000526 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
527 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000528 } else {
529 assert(rhs->isComplexIntegerType());
John Wiegley429bb272011-04-08 18:41:53 +0000530 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000531 }
John McCallcf33b242010-11-13 08:17:45 +0000532 return lhs;
533 }
534
John McCall2bb5d002010-11-13 09:02:35 +0000535 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
536 if (!isCompAssign) {
537 // int -> float -> _Complex float
538 if (lhs->isIntegerType()) {
539 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000540 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_IntegralToFloating);
541 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000542 } else {
543 assert(lhs->isComplexIntegerType());
John Wiegley429bb272011-04-08 18:41:53 +0000544 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000545 }
546 }
John McCallcf33b242010-11-13 08:17:45 +0000547 return rhs;
548 }
549
550 // This handles complex/complex, complex/float, or float/complex.
551 // When both operands are complex, the shorter operand is converted to the
552 // type of the longer, and that is the type of the result. This corresponds
553 // to what is done when combining two real floating-point operands.
554 // The fun begins when size promotion occur across type domains.
555 // From H&S 6.3.4: When one operand is complex and the other is a real
556 // floating-point type, the less precise type is converted, within it's
557 // real or complex domain, to the precision of the other type. For example,
558 // when combining a "long double" with a "double _Complex", the
559 // "double _Complex" is promoted to "long double _Complex".
560 int order = Context.getFloatingTypeOrder(lhs, rhs);
561
562 // If both are complex, just cast to the more precise type.
563 if (LHSComplexFloat && RHSComplexFloat) {
564 if (order > 0) {
565 // _Complex float -> _Complex double
John Wiegley429bb272011-04-08 18:41:53 +0000566 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000567 return lhs;
568
569 } else if (order < 0) {
570 // _Complex float -> _Complex double
571 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000572 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000573 return rhs;
574 }
575 return lhs;
576 }
577
578 // If just the LHS is complex, the RHS needs to be converted,
579 // and the LHS might need to be promoted.
580 if (LHSComplexFloat) {
581 if (order > 0) { // LHS is wider
582 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000583 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000584 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
585 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000586 return lhs;
587 }
588
589 // RHS is at least as wide. Find its corresponding complex type.
590 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
591
592 // double -> _Complex double
John Wiegley429bb272011-04-08 18:41:53 +0000593 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000594
595 // _Complex float -> _Complex double
596 if (!isCompAssign && order < 0)
John Wiegley429bb272011-04-08 18:41:53 +0000597 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000598
599 return result;
600 }
601
602 // Just the RHS is complex, so the LHS needs to be converted
603 // and the RHS might need to be promoted.
604 assert(RHSComplexFloat);
605
606 if (order < 0) { // RHS is wider
607 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000608 if (!isCompAssign) {
Argyrios Kyrtzidise1889332011-01-18 18:49:33 +0000609 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000610 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
611 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000612 }
John McCallcf33b242010-11-13 08:17:45 +0000613 return rhs;
614 }
615
616 // LHS is at least as wide. Find its corresponding complex type.
617 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
618
619 // double -> _Complex double
620 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000621 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000622
623 // _Complex float -> _Complex double
624 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +0000625 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000626
627 return result;
628 }
629
630 // Now handle "real" floating types (i.e. float, double, long double).
631 bool LHSFloat = lhs->isRealFloatingType();
632 bool RHSFloat = rhs->isRealFloatingType();
633 if (LHSFloat || RHSFloat) {
634 // If we have two real floating types, convert the smaller operand
635 // to the bigger result.
636 if (LHSFloat && RHSFloat) {
637 int order = Context.getFloatingTypeOrder(lhs, rhs);
638 if (order > 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000639 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCallcf33b242010-11-13 08:17:45 +0000640 return lhs;
641 }
642
643 assert(order < 0 && "illegal float comparison");
644 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000645 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCallcf33b242010-11-13 08:17:45 +0000646 return rhs;
647 }
648
649 // If we have an integer operand, the result is the real floating type.
650 if (LHSFloat) {
651 if (rhs->isIntegerType()) {
652 // Convert rhs to the lhs floating point type.
John Wiegley429bb272011-04-08 18:41:53 +0000653 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCallcf33b242010-11-13 08:17:45 +0000654 return lhs;
655 }
656
657 // Convert both sides to the appropriate complex float.
658 assert(rhs->isComplexIntegerType());
659 QualType result = Context.getComplexType(lhs);
660
661 // _Complex int -> _Complex float
John Wiegley429bb272011-04-08 18:41:53 +0000662 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000663
664 // float -> _Complex float
665 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000666 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000667
668 return result;
669 }
670
671 assert(RHSFloat);
672 if (lhs->isIntegerType()) {
673 // Convert lhs to the rhs floating point type.
674 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000675 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCallcf33b242010-11-13 08:17:45 +0000676 return rhs;
677 }
678
679 // Convert both sides to the appropriate complex float.
680 assert(lhs->isComplexIntegerType());
681 QualType result = Context.getComplexType(rhs);
682
683 // _Complex int -> _Complex float
684 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000685 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000686
687 // float -> _Complex float
John Wiegley429bb272011-04-08 18:41:53 +0000688 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000689
690 return result;
691 }
692
693 // Handle GCC complex int extension.
694 // FIXME: if the operands are (int, _Complex long), we currently
695 // don't promote the complex. Also, signedness?
696 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
697 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
698 if (lhsComplexInt && rhsComplexInt) {
699 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
700 rhsComplexInt->getElementType());
701 assert(order && "inequal types with equal element ordering");
702 if (order > 0) {
703 // _Complex int -> _Complex long
John Wiegley429bb272011-04-08 18:41:53 +0000704 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000705 return lhs;
706 }
707
708 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000709 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000710 return rhs;
711 } else if (lhsComplexInt) {
712 // int -> _Complex int
John Wiegley429bb272011-04-08 18:41:53 +0000713 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000714 return lhs;
715 } else if (rhsComplexInt) {
716 // int -> _Complex int
717 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000718 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000719 return rhs;
720 }
721
722 // Finally, we have two differing integer types.
723 // The rules for this case are in C99 6.3.1.8
724 int compare = Context.getIntegerTypeOrder(lhs, rhs);
725 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
726 rhsSigned = rhs->hasSignedIntegerRepresentation();
727 if (lhsSigned == rhsSigned) {
728 // Same signedness; use the higher-ranked type
729 if (compare >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000730 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000731 return lhs;
732 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000733 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000734 return rhs;
735 } else if (compare != (lhsSigned ? 1 : -1)) {
736 // The unsigned type has greater than or equal rank to the
737 // signed type, so use the unsigned type
738 if (rhsSigned) {
John Wiegley429bb272011-04-08 18:41:53 +0000739 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000740 return lhs;
741 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000742 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000743 return rhs;
744 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
745 // The two types are different widths; if we are here, that
746 // means the signed type is larger than the unsigned type, so
747 // use the signed type.
748 if (lhsSigned) {
John Wiegley429bb272011-04-08 18:41:53 +0000749 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000750 return lhs;
751 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000752 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000753 return rhs;
754 } else {
755 // The signed type is higher-ranked than the unsigned type,
756 // but isn't actually any bigger (like unsigned int and long
757 // on most 32-bit systems). Use the unsigned type corresponding
758 // to the signed type.
759 QualType result =
760 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley429bb272011-04-08 18:41:53 +0000761 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000762 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000763 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000764 return result;
765 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000766}
767
Chris Lattnere7a2e912008-07-25 21:10:04 +0000768//===----------------------------------------------------------------------===//
769// Semantic Analysis for various Expression Types
770//===----------------------------------------------------------------------===//
771
772
Peter Collingbournef111d932011-04-15 00:35:48 +0000773ExprResult
774Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
775 SourceLocation DefaultLoc,
776 SourceLocation RParenLoc,
777 Expr *ControllingExpr,
778 MultiTypeArg types,
779 MultiExprArg exprs) {
780 unsigned NumAssocs = types.size();
781 assert(NumAssocs == exprs.size());
782
783 ParsedType *ParsedTypes = types.release();
784 Expr **Exprs = exprs.release();
785
786 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
787 for (unsigned i = 0; i < NumAssocs; ++i) {
788 if (ParsedTypes[i])
789 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
790 else
791 Types[i] = 0;
792 }
793
794 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
795 ControllingExpr, Types, Exprs,
796 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +0000797 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +0000798 return ER;
799}
800
801ExprResult
802Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
803 SourceLocation DefaultLoc,
804 SourceLocation RParenLoc,
805 Expr *ControllingExpr,
806 TypeSourceInfo **Types,
807 Expr **Exprs,
808 unsigned NumAssocs) {
809 bool TypeErrorFound = false,
810 IsResultDependent = ControllingExpr->isTypeDependent(),
811 ContainsUnexpandedParameterPack
812 = ControllingExpr->containsUnexpandedParameterPack();
813
814 for (unsigned i = 0; i < NumAssocs; ++i) {
815 if (Exprs[i]->containsUnexpandedParameterPack())
816 ContainsUnexpandedParameterPack = true;
817
818 if (Types[i]) {
819 if (Types[i]->getType()->containsUnexpandedParameterPack())
820 ContainsUnexpandedParameterPack = true;
821
822 if (Types[i]->getType()->isDependentType()) {
823 IsResultDependent = true;
824 } else {
825 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
826 // complete object type other than a variably modified type."
827 unsigned D = 0;
828 if (Types[i]->getType()->isIncompleteType())
829 D = diag::err_assoc_type_incomplete;
830 else if (!Types[i]->getType()->isObjectType())
831 D = diag::err_assoc_type_nonobject;
832 else if (Types[i]->getType()->isVariablyModifiedType())
833 D = diag::err_assoc_type_variably_modified;
834
835 if (D != 0) {
836 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
837 << Types[i]->getTypeLoc().getSourceRange()
838 << Types[i]->getType();
839 TypeErrorFound = true;
840 }
841
842 // C1X 6.5.1.1p2 "No two generic associations in the same generic
843 // selection shall specify compatible types."
844 for (unsigned j = i+1; j < NumAssocs; ++j)
845 if (Types[j] && !Types[j]->getType()->isDependentType() &&
846 Context.typesAreCompatible(Types[i]->getType(),
847 Types[j]->getType())) {
848 Diag(Types[j]->getTypeLoc().getBeginLoc(),
849 diag::err_assoc_compatible_types)
850 << Types[j]->getTypeLoc().getSourceRange()
851 << Types[j]->getType()
852 << Types[i]->getType();
853 Diag(Types[i]->getTypeLoc().getBeginLoc(),
854 diag::note_compat_assoc)
855 << Types[i]->getTypeLoc().getSourceRange()
856 << Types[i]->getType();
857 TypeErrorFound = true;
858 }
859 }
860 }
861 }
862 if (TypeErrorFound)
863 return ExprError();
864
865 // If we determined that the generic selection is result-dependent, don't
866 // try to compute the result expression.
867 if (IsResultDependent)
868 return Owned(new (Context) GenericSelectionExpr(
869 Context, KeyLoc, ControllingExpr,
870 Types, Exprs, NumAssocs, DefaultLoc,
871 RParenLoc, ContainsUnexpandedParameterPack));
872
873 llvm::SmallVector<unsigned, 1> CompatIndices;
874 unsigned DefaultIndex = -1U;
875 for (unsigned i = 0; i < NumAssocs; ++i) {
876 if (!Types[i])
877 DefaultIndex = i;
878 else if (Context.typesAreCompatible(ControllingExpr->getType(),
879 Types[i]->getType()))
880 CompatIndices.push_back(i);
881 }
882
883 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
884 // type compatible with at most one of the types named in its generic
885 // association list."
886 if (CompatIndices.size() > 1) {
887 // We strip parens here because the controlling expression is typically
888 // parenthesized in macro definitions.
889 ControllingExpr = ControllingExpr->IgnoreParens();
890 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
891 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
892 << (unsigned) CompatIndices.size();
893 for (llvm::SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
894 E = CompatIndices.end(); I != E; ++I) {
895 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
896 diag::note_compat_assoc)
897 << Types[*I]->getTypeLoc().getSourceRange()
898 << Types[*I]->getType();
899 }
900 return ExprError();
901 }
902
903 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
904 // its controlling expression shall have type compatible with exactly one of
905 // the types named in its generic association list."
906 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
907 // We strip parens here because the controlling expression is typically
908 // parenthesized in macro definitions.
909 ControllingExpr = ControllingExpr->IgnoreParens();
910 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
911 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
912 return ExprError();
913 }
914
915 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
916 // type name that is compatible with the type of the controlling expression,
917 // then the result expression of the generic selection is the expression
918 // in that generic association. Otherwise, the result expression of the
919 // generic selection is the expression in the default generic association."
920 unsigned ResultIndex =
921 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
922
923 return Owned(new (Context) GenericSelectionExpr(
924 Context, KeyLoc, ControllingExpr,
925 Types, Exprs, NumAssocs, DefaultLoc,
926 RParenLoc, ContainsUnexpandedParameterPack,
927 ResultIndex));
928}
929
Steve Narofff69936d2007-09-16 03:34:24 +0000930/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000931/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
932/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
933/// multiple tokens. However, the common case is that StringToks points to one
934/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000935///
John McCall60d7b3a2010-08-24 06:29:42 +0000936ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +0000937Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000938 assert(NumStringToks && "Must have at least one string!");
939
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000940 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000941 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000942 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000943
944 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
945 for (unsigned i = 0; i != NumStringToks; ++i)
946 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000947
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000948 QualType StrTy = Context.CharTy;
Anders Carlsson96b4adc2011-04-06 18:42:48 +0000949 if (Literal.AnyWide)
950 StrTy = Context.getWCharType();
951 else if (Literal.Pascal)
952 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000953
954 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +0000955 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +0000956 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000957
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000958 // Get an array type for the string, according to C99 6.4.5. This includes
959 // the nul terminator character as well as the string length for pascal
960 // strings.
961 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000962 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000963 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000964
Reid Spencer5f016e22007-07-11 17:01:13 +0000965 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +0000966 return Owned(StringLiteral::Create(Context, Literal.GetString(),
967 Literal.GetStringLength(),
Anders Carlsson3e2193c2011-04-14 00:40:03 +0000968 Literal.AnyWide, Literal.Pascal, StrTy,
Sean Hunt6cf75022010-08-30 17:47:05 +0000969 &StringTokLocs[0],
970 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000971}
972
John McCall469a1eb2011-02-02 13:00:07 +0000973enum CaptureResult {
974 /// No capture is required.
975 CR_NoCapture,
976
977 /// A capture is required.
978 CR_Capture,
979
John McCall6b5a61b2011-02-07 10:33:21 +0000980 /// A by-ref capture is required.
981 CR_CaptureByRef,
982
John McCall469a1eb2011-02-02 13:00:07 +0000983 /// An error occurred when trying to capture the given variable.
984 CR_Error
985};
986
987/// Diagnose an uncapturable value reference.
Chris Lattner639e2d32008-10-20 05:16:36 +0000988///
John McCall469a1eb2011-02-02 13:00:07 +0000989/// \param var - the variable referenced
990/// \param DC - the context which we couldn't capture through
991static CaptureResult
John McCall6b5a61b2011-02-07 10:33:21 +0000992diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +0000993 VarDecl *var, DeclContext *DC) {
994 switch (S.ExprEvalContexts.back().Context) {
995 case Sema::Unevaluated:
996 // The argument will never be evaluated, so don't complain.
997 return CR_NoCapture;
Mike Stump1eb44332009-09-09 15:08:12 +0000998
John McCall469a1eb2011-02-02 13:00:07 +0000999 case Sema::PotentiallyEvaluated:
1000 case Sema::PotentiallyEvaluatedIfUsed:
1001 break;
Chris Lattner639e2d32008-10-20 05:16:36 +00001002
John McCall469a1eb2011-02-02 13:00:07 +00001003 case Sema::PotentiallyPotentiallyEvaluated:
1004 // FIXME: delay these!
1005 break;
Chris Lattner17f3a6d2009-04-21 22:26:47 +00001006 }
Mike Stump1eb44332009-09-09 15:08:12 +00001007
John McCall469a1eb2011-02-02 13:00:07 +00001008 // Don't diagnose about capture if we're not actually in code right
1009 // now; in general, there are more appropriate places that will
1010 // diagnose this.
1011 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1012
John McCall4f38f412011-03-22 23:15:50 +00001013 // Certain madnesses can happen with parameter declarations, which
1014 // we want to ignore.
1015 if (isa<ParmVarDecl>(var)) {
1016 // - If the parameter still belongs to the translation unit, then
1017 // we're actually just using one parameter in the declaration of
1018 // the next. This is useful in e.g. VLAs.
1019 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1020 return CR_NoCapture;
1021
1022 // - This particular madness can happen in ill-formed default
1023 // arguments; claim it's okay and let downstream code handle it.
1024 if (S.CurContext == var->getDeclContext()->getParent())
1025 return CR_NoCapture;
1026 }
John McCall469a1eb2011-02-02 13:00:07 +00001027
1028 DeclarationName functionName;
1029 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1030 functionName = fn->getDeclName();
1031 // FIXME: variable from enclosing block that we couldn't capture from!
1032
1033 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1034 << var->getIdentifier() << functionName;
1035 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1036 << var->getIdentifier();
1037
1038 return CR_Error;
Mike Stump1eb44332009-09-09 15:08:12 +00001039}
1040
John McCall6b5a61b2011-02-07 10:33:21 +00001041/// There is a well-formed capture at a particular scope level;
1042/// propagate it through all the nested blocks.
1043static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1044 const BlockDecl::Capture &capture) {
1045 VarDecl *var = capture.getVariable();
1046
1047 // Update all the inner blocks with the capture information.
1048 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1049 i != e; ++i) {
1050 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1051 innerBlock->Captures.push_back(
1052 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1053 /*nested*/ true, capture.getCopyExpr()));
1054 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1055 }
1056
1057 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1058}
1059
1060/// shouldCaptureValueReference - Determine if a reference to the
John McCall469a1eb2011-02-02 13:00:07 +00001061/// given value in the current context requires a variable capture.
1062///
1063/// This also keeps the captures set in the BlockScopeInfo records
1064/// up-to-date.
John McCall6b5a61b2011-02-07 10:33:21 +00001065static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001066 ValueDecl *value) {
1067 // Only variables ever require capture.
1068 VarDecl *var = dyn_cast<VarDecl>(value);
John McCall76a40212011-02-09 01:13:10 +00001069 if (!var) return CR_NoCapture;
John McCall469a1eb2011-02-02 13:00:07 +00001070
1071 // Fast path: variables from the current context never require capture.
1072 DeclContext *DC = S.CurContext;
1073 if (var->getDeclContext() == DC) return CR_NoCapture;
1074
1075 // Only variables with local storage require capture.
1076 // FIXME: What about 'const' variables in C++?
1077 if (!var->hasLocalStorage()) return CR_NoCapture;
1078
1079 // Otherwise, we need to capture.
1080
1081 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCall469a1eb2011-02-02 13:00:07 +00001082 do {
1083 // Only blocks (and eventually C++0x closures) can capture; other
1084 // scopes don't work.
1085 if (!isa<BlockDecl>(DC))
John McCall6b5a61b2011-02-07 10:33:21 +00001086 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCall469a1eb2011-02-02 13:00:07 +00001087
1088 BlockScopeInfo *blockScope =
1089 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1090 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1091
John McCall6b5a61b2011-02-07 10:33:21 +00001092 // Check whether we've already captured it in this block. If so,
1093 // we're done.
1094 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1095 return propagateCapture(S, functionScopesIndex,
1096 blockScope->Captures[indexPlus1 - 1]);
John McCall469a1eb2011-02-02 13:00:07 +00001097
1098 functionScopesIndex--;
1099 DC = cast<BlockDecl>(DC)->getDeclContext();
1100 } while (var->getDeclContext() != DC);
1101
John McCall6b5a61b2011-02-07 10:33:21 +00001102 // Okay, we descended all the way to the block that defines the variable.
1103 // Actually try to capture it.
1104 QualType type = var->getType();
1105
1106 // Prohibit variably-modified types.
1107 if (type->isVariablyModifiedType()) {
1108 S.Diag(loc, diag::err_ref_vm_type);
1109 S.Diag(var->getLocation(), diag::note_declared_at);
1110 return CR_Error;
1111 }
1112
1113 // Prohibit arrays, even in __block variables, but not references to
1114 // them.
1115 if (type->isArrayType()) {
1116 S.Diag(loc, diag::err_ref_array_type);
1117 S.Diag(var->getLocation(), diag::note_declared_at);
1118 return CR_Error;
1119 }
1120
1121 S.MarkDeclarationReferenced(loc, var);
1122
1123 // The BlocksAttr indicates the variable is bound by-reference.
1124 bool byRef = var->hasAttr<BlocksAttr>();
1125
1126 // Build a copy expression.
1127 Expr *copyExpr = 0;
John McCall642a75f2011-04-28 02:15:35 +00001128 const RecordType *rtype;
1129 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1130 (rtype = type->getAs<RecordType>())) {
1131
1132 // The capture logic needs the destructor, so make sure we mark it.
1133 // Usually this is unnecessary because most local variables have
1134 // their destructors marked at declaration time, but parameters are
1135 // an exception because it's technically only the call site that
1136 // actually requires the destructor.
1137 if (isa<ParmVarDecl>(var))
1138 S.FinalizeVarWithDestructor(var, rtype);
1139
John McCall6b5a61b2011-02-07 10:33:21 +00001140 // According to the blocks spec, the capture of a variable from
1141 // the stack requires a const copy constructor. This is not true
1142 // of the copy/move done to move a __block variable to the heap.
1143 type.addConst();
1144
1145 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1146 ExprResult result =
1147 S.PerformCopyInitialization(
1148 InitializedEntity::InitializeBlock(var->getLocation(),
1149 type, false),
1150 loc, S.Owned(declRef));
1151
1152 // Build a full-expression copy expression if initialization
1153 // succeeded and used a non-trivial constructor. Recover from
1154 // errors by pretending that the copy isn't necessary.
1155 if (!result.isInvalid() &&
1156 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1157 result = S.MaybeCreateExprWithCleanups(result);
1158 copyExpr = result.take();
1159 }
1160 }
1161
1162 // We're currently at the declarer; go back to the closure.
1163 functionScopesIndex++;
1164 BlockScopeInfo *blockScope =
1165 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1166
1167 // Build a valid capture in this scope.
1168 blockScope->Captures.push_back(
1169 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1170 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1171
1172 // Propagate that to inner captures if necessary.
1173 return propagateCapture(S, functionScopesIndex,
1174 blockScope->Captures.back());
1175}
1176
1177static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1178 const DeclarationNameInfo &NameInfo,
1179 bool byRef) {
1180 assert(isa<VarDecl>(vd) && "capturing non-variable");
1181
1182 VarDecl *var = cast<VarDecl>(vd);
1183 assert(var->hasLocalStorage() && "capturing non-local");
1184 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1185
1186 QualType exprType = var->getType().getNonReferenceType();
1187
1188 BlockDeclRefExpr *BDRE;
1189 if (!byRef) {
1190 // The variable will be bound by copy; make it const within the
1191 // closure, but record that this was done in the expression.
1192 bool constAdded = !exprType.isConstQualified();
1193 exprType.addConst();
1194
1195 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1196 NameInfo.getLoc(), false,
1197 constAdded);
1198 } else {
1199 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1200 NameInfo.getLoc(), true);
1201 }
1202
1203 return S.Owned(BDRE);
John McCall469a1eb2011-02-02 13:00:07 +00001204}
Chris Lattner639e2d32008-10-20 05:16:36 +00001205
John McCall60d7b3a2010-08-24 06:29:42 +00001206ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001207Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001208 SourceLocation Loc,
1209 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001210 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001211 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001212}
1213
John McCall76a40212011-02-09 01:13:10 +00001214/// BuildDeclRefExpr - Build an expression that references a
1215/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001216ExprResult
John McCall76a40212011-02-09 01:13:10 +00001217Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001218 const DeclarationNameInfo &NameInfo,
1219 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001220 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +00001221
John McCall7eb0a9e2010-11-24 05:12:34 +00001222 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +00001223 SS? SS->getWithLocInContext(Context)
1224 : NestedNameSpecifierLoc(),
John McCall7eb0a9e2010-11-24 05:12:34 +00001225 D, NameInfo, Ty, VK);
1226
1227 // Just in case we're building an illegal pointer-to-member.
1228 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1229 E->setObjectKind(OK_BitField);
1230
1231 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001232}
1233
John McCalldfa1edb2010-11-23 20:48:44 +00001234static ExprResult
1235BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1236 const CXXScopeSpec &SS, FieldDecl *Field,
1237 DeclAccessPair FoundDecl,
1238 const DeclarationNameInfo &MemberNameInfo);
1239
John McCall60d7b3a2010-08-24 06:29:42 +00001240ExprResult
John McCall5808ce42011-02-03 08:15:49 +00001241Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
1242 SourceLocation loc,
1243 IndirectFieldDecl *indirectField,
1244 Expr *baseObjectExpr,
1245 SourceLocation opLoc) {
1246 // First, build the expression that refers to the base object.
1247
1248 bool baseObjectIsPointer = false;
1249 Qualifiers baseQuals;
1250
1251 // Case 1: the base of the indirect field is not a field.
1252 VarDecl *baseVariable = indirectField->getVarDecl();
Douglas Gregorf5848322011-02-18 02:44:58 +00001253 CXXScopeSpec EmptySS;
John McCall5808ce42011-02-03 08:15:49 +00001254 if (baseVariable) {
1255 assert(baseVariable->getType()->isRecordType());
1256
1257 // In principle we could have a member access expression that
1258 // accesses an anonymous struct/union that's a static member of
1259 // the base object's class. However, under the current standard,
1260 // static data members cannot be anonymous structs or unions.
1261 // Supporting this is as easy as building a MemberExpr here.
1262 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1263
1264 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1265
1266 ExprResult result =
Douglas Gregorf5848322011-02-18 02:44:58 +00001267 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
John McCall5808ce42011-02-03 08:15:49 +00001268 if (result.isInvalid()) return ExprError();
1269
1270 baseObjectExpr = result.take();
1271 baseObjectIsPointer = false;
1272 baseQuals = baseObjectExpr->getType().getQualifiers();
1273
1274 // Case 2: the base of the indirect field is a field and the user
1275 // wrote a member expression.
1276 } else if (baseObjectExpr) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001277 // The caller provided the base object expression. Determine
1278 // whether its a pointer and whether it adds any qualifiers to the
1279 // anonymous struct/union fields we're looking into.
John McCall5808ce42011-02-03 08:15:49 +00001280 QualType objectType = baseObjectExpr->getType();
1281
1282 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1283 baseObjectIsPointer = true;
1284 objectType = ptr->getPointeeType();
1285 } else {
1286 baseObjectIsPointer = false;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001287 }
John McCall5808ce42011-02-03 08:15:49 +00001288 baseQuals = objectType.getQualifiers();
1289
1290 // Case 3: the base of the indirect field is a field and we should
1291 // build an implicit member access.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001292 } else {
1293 // We've found a member of an anonymous struct/union that is
1294 // inside a non-anonymous struct/union, so in a well-formed
1295 // program our base object expression is "this".
John McCall5808ce42011-02-03 08:15:49 +00001296 CXXMethodDecl *method = tryCaptureCXXThis();
1297 if (!method) {
1298 Diag(loc, diag::err_invalid_member_use_in_static_method)
1299 << indirectField->getDeclName();
1300 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001301 }
1302
John McCall5808ce42011-02-03 08:15:49 +00001303 // Our base object expression is "this".
1304 baseObjectExpr =
1305 new (Context) CXXThisExpr(loc, method->getThisType(Context),
1306 /*isImplicit=*/ true);
1307 baseObjectIsPointer = true;
1308 baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001309 }
1310
1311 // Build the implicit member references to the field of the
1312 // anonymous struct/union.
John McCall5808ce42011-02-03 08:15:49 +00001313 Expr *result = baseObjectExpr;
1314 IndirectFieldDecl::chain_iterator
1315 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCalldfa1edb2010-11-23 20:48:44 +00001316
John McCall5808ce42011-02-03 08:15:49 +00001317 // Build the first member access in the chain with full information.
1318 if (!baseVariable) {
1319 FieldDecl *field = cast<FieldDecl>(*FI);
John McCalldfa1edb2010-11-23 20:48:44 +00001320
John McCall5808ce42011-02-03 08:15:49 +00001321 // FIXME: use the real found-decl info!
1322 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall0953e762009-09-24 19:53:00 +00001323
John McCall5808ce42011-02-03 08:15:49 +00001324 // Make a nameInfo that properly uses the anonymous name.
1325 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall0953e762009-09-24 19:53:00 +00001326
John McCall5808ce42011-02-03 08:15:49 +00001327 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Douglas Gregorf5848322011-02-18 02:44:58 +00001328 EmptySS, field, foundDecl,
John McCall5808ce42011-02-03 08:15:49 +00001329 memberNameInfo).take();
1330 baseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +00001331
John McCall5808ce42011-02-03 08:15:49 +00001332 // FIXME: check qualified member access
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001333 }
1334
John McCall5808ce42011-02-03 08:15:49 +00001335 // In all cases, we should now skip the first declaration in the chain.
1336 ++FI;
1337
Douglas Gregorf5848322011-02-18 02:44:58 +00001338 while (FI != FEnd) {
1339 FieldDecl *field = cast<FieldDecl>(*FI++);
John McCall5808ce42011-02-03 08:15:49 +00001340
1341 // FIXME: these are somewhat meaningless
1342 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1343 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall5808ce42011-02-03 08:15:49 +00001344
1345 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Douglas Gregorf5848322011-02-18 02:44:58 +00001346 (FI == FEnd? SS : EmptySS), field,
1347 foundDecl, memberNameInfo)
John McCall5808ce42011-02-03 08:15:49 +00001348 .take();
1349 }
1350
1351 return Owned(result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001352}
1353
Abramo Bagnara25777432010-08-11 22:01:17 +00001354/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001355/// possibly a list of template arguments.
1356///
1357/// If this produces template arguments, it is permitted to call
1358/// DecomposeTemplateName.
1359///
1360/// This actually loses a lot of source location information for
1361/// non-standard name kinds; we should consider preserving that in
1362/// some way.
1363static void DecomposeUnqualifiedId(Sema &SemaRef,
1364 const UnqualifiedId &Id,
1365 TemplateArgumentListInfo &Buffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00001366 DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00001367 const TemplateArgumentListInfo *&TemplateArgs) {
1368 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1369 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1370 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1371
1372 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1373 Id.TemplateId->getTemplateArgs(),
1374 Id.TemplateId->NumArgs);
1375 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1376 TemplateArgsPtr.release();
1377
John McCall2b5289b2010-08-23 07:28:44 +00001378 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001379 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1380 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001381 TemplateArgs = &Buffer;
1382 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001383 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001384 TemplateArgs = 0;
1385 }
1386}
1387
John McCallaa81e162009-12-01 22:10:20 +00001388/// Determines if the given class is provably not derived from all of
1389/// the prospective base classes.
1390static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1391 CXXRecordDecl *Record,
1392 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +00001393 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +00001394 return false;
1395
Douglas Gregor952b0172010-02-11 01:04:33 +00001396 RecordDecl *RD = Record->getDefinition();
John McCallb1b42562009-12-01 22:28:41 +00001397 if (!RD) return false;
1398 Record = cast<CXXRecordDecl>(RD);
1399
John McCallaa81e162009-12-01 22:10:20 +00001400 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1401 E = Record->bases_end(); I != E; ++I) {
1402 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1403 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1404 if (!BaseRT) return false;
1405
1406 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +00001407 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1408 return false;
1409 }
1410
1411 return true;
1412}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001413
John McCallaa81e162009-12-01 22:10:20 +00001414enum IMAKind {
1415 /// The reference is definitely not an instance member access.
1416 IMA_Static,
1417
1418 /// The reference may be an implicit instance member access.
1419 IMA_Mixed,
1420
1421 /// The reference may be to an instance member, but it is invalid if
1422 /// so, because the context is not an instance method.
1423 IMA_Mixed_StaticContext,
1424
1425 /// The reference may be to an instance member, but it is invalid if
1426 /// so, because the context is from an unrelated class.
1427 IMA_Mixed_Unrelated,
1428
1429 /// The reference is definitely an implicit instance member access.
1430 IMA_Instance,
1431
1432 /// The reference may be to an unresolved using declaration.
1433 IMA_Unresolved,
1434
1435 /// The reference may be to an unresolved using declaration and the
1436 /// context is not an instance method.
1437 IMA_Unresolved_StaticContext,
1438
John McCallaa81e162009-12-01 22:10:20 +00001439 /// All possible referrents are instance members and the current
1440 /// context is not an instance method.
1441 IMA_Error_StaticContext,
1442
1443 /// All possible referrents are instance members of an unrelated
1444 /// class.
1445 IMA_Error_Unrelated
1446};
1447
1448/// The given lookup names class member(s) and is not being used for
1449/// an address-of-member expression. Classify the type of access
1450/// according to whether it's possible that this reference names an
1451/// instance member. This is best-effort; it is okay to
1452/// conservatively answer "yes", in which case some errors will simply
1453/// not be caught until template-instantiation.
1454static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1455 const LookupResult &R) {
John McCall3b4294e2009-12-16 12:17:52 +00001456 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCallaa81e162009-12-01 22:10:20 +00001457
John McCallea1471e2010-05-20 01:18:31 +00001458 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCallaa81e162009-12-01 22:10:20 +00001459 bool isStaticContext =
John McCallea1471e2010-05-20 01:18:31 +00001460 (!isa<CXXMethodDecl>(DC) ||
1461 cast<CXXMethodDecl>(DC)->isStatic());
John McCallaa81e162009-12-01 22:10:20 +00001462
1463 if (R.isUnresolvableResult())
1464 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1465
1466 // Collect all the declaring classes of instance members we find.
1467 bool hasNonInstance = false;
Sebastian Redlf9780002010-11-26 16:28:07 +00001468 bool hasField = false;
John McCallaa81e162009-12-01 22:10:20 +00001469 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1470 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall161755a2010-04-06 21:38:20 +00001471 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00001472
John McCall161755a2010-04-06 21:38:20 +00001473 if (D->isCXXInstanceMember()) {
Sebastian Redlf9780002010-11-26 16:28:07 +00001474 if (dyn_cast<FieldDecl>(D))
1475 hasField = true;
1476
John McCallaa81e162009-12-01 22:10:20 +00001477 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCallaa81e162009-12-01 22:10:20 +00001478 Classes.insert(R->getCanonicalDecl());
1479 }
1480 else
1481 hasNonInstance = true;
1482 }
1483
1484 // If we didn't find any instance members, it can't be an implicit
1485 // member reference.
1486 if (Classes.empty())
1487 return IMA_Static;
1488
1489 // If the current context is not an instance method, it can't be
1490 // an implicit member reference.
Sebastian Redlf9780002010-11-26 16:28:07 +00001491 if (isStaticContext) {
1492 if (hasNonInstance)
1493 return IMA_Mixed_StaticContext;
1494
1495 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1496 // C++0x [expr.prim.general]p10:
1497 // An id-expression that denotes a non-static data member or non-static
1498 // member function of a class can only be used:
1499 // (...)
1500 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1501 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1502 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1503 if (isUnevaluatedExpression)
1504 return IMA_Mixed_StaticContext;
1505 }
1506
1507 return IMA_Error_StaticContext;
1508 }
John McCallaa81e162009-12-01 22:10:20 +00001509
Argyrios Kyrtzidis0d8dc462011-04-14 00:46:47 +00001510 CXXRecordDecl *
1511 contextClass = cast<CXXMethodDecl>(DC)->getParent()->getCanonicalDecl();
1512
1513 // [class.mfct.non-static]p3:
1514 // ...is used in the body of a non-static member function of class X,
1515 // if name lookup (3.4.1) resolves the name in the id-expression to a
1516 // non-static non-type member of some class C [...]
1517 // ...if C is not X or a base class of X, the class member access expression
1518 // is ill-formed.
1519 if (R.getNamingClass() &&
1520 contextClass != R.getNamingClass()->getCanonicalDecl() &&
1521 contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
1522 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1523
John McCallaa81e162009-12-01 22:10:20 +00001524 // If we can prove that the current context is unrelated to all the
1525 // declaring classes, it can't be an implicit member reference (in
1526 // which case it's an error if any of those members are selected).
Argyrios Kyrtzidis0d8dc462011-04-14 00:46:47 +00001527 if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
John McCallaa81e162009-12-01 22:10:20 +00001528 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1529
1530 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1531}
1532
1533/// Diagnose a reference to a field with no object available.
1534static void DiagnoseInstanceReference(Sema &SemaRef,
1535 const CXXScopeSpec &SS,
John McCall5808ce42011-02-03 08:15:49 +00001536 NamedDecl *rep,
1537 const DeclarationNameInfo &nameInfo) {
1538 SourceLocation Loc = nameInfo.getLoc();
John McCallaa81e162009-12-01 22:10:20 +00001539 SourceRange Range(Loc);
1540 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1541
John McCall5808ce42011-02-03 08:15:49 +00001542 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCallaa81e162009-12-01 22:10:20 +00001543 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1544 if (MD->isStatic()) {
1545 // "invalid use of member 'x' in static member function"
1546 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCall5808ce42011-02-03 08:15:49 +00001547 << Range << nameInfo.getName();
John McCallaa81e162009-12-01 22:10:20 +00001548 return;
1549 }
1550 }
1551
1552 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCall5808ce42011-02-03 08:15:49 +00001553 << nameInfo.getName() << Range;
John McCallaa81e162009-12-01 22:10:20 +00001554 return;
1555 }
1556
1557 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +00001558}
1559
John McCall578b69b2009-12-16 08:11:27 +00001560/// Diagnose an empty lookup.
1561///
1562/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001563bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1564 CorrectTypoContext CTC) {
John McCall578b69b2009-12-16 08:11:27 +00001565 DeclarationName Name = R.getLookupName();
1566
John McCall578b69b2009-12-16 08:11:27 +00001567 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001568 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001569 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1570 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001571 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001572 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001573 diagnostic_suggest = diag::err_undeclared_use_suggest;
1574 }
John McCall578b69b2009-12-16 08:11:27 +00001575
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001576 // If the original lookup was an unqualified lookup, fake an
1577 // unqualified lookup. This is useful when (for example) the
1578 // original lookup would not have found something because it was a
1579 // dependent name.
Nick Lewycky03d98c52010-07-06 19:51:49 +00001580 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001581 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +00001582 if (isa<CXXRecordDecl>(DC)) {
1583 LookupQualifiedName(R, DC);
1584
1585 if (!R.empty()) {
1586 // Don't give errors about ambiguities in this lookup.
1587 R.suppressDiagnostics();
1588
1589 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1590 bool isInstance = CurMethod &&
1591 CurMethod->isInstance() &&
1592 DC == CurMethod->getParent();
1593
1594 // Give a code modification hint to insert 'this->'.
1595 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1596 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +00001597 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001598 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1599 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001600 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001601 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001602 if (DepMethod) {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001603 Diag(R.getNameLoc(), diagnostic) << Name
1604 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1605 QualType DepThisType = DepMethod->getThisType(Context);
1606 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1607 R.getNameLoc(), DepThisType, false);
1608 TemplateArgumentListInfo TList;
1609 if (ULE->hasExplicitTemplateArgs())
1610 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001611
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001612 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00001613 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001614 CXXDependentScopeMemberExpr *DepExpr =
1615 CXXDependentScopeMemberExpr::Create(
1616 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001617 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001618 R.getLookupNameInfo(), &TList);
1619 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001620 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001621 // FIXME: we should be able to handle this case too. It is correct
1622 // to add this-> here. This is a workaround for PR7947.
1623 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001624 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001625 } else {
John McCall578b69b2009-12-16 08:11:27 +00001626 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001627 }
John McCall578b69b2009-12-16 08:11:27 +00001628
1629 // Do we really want to note all of these?
1630 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1631 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1632
1633 // Tell the callee to try to recover.
1634 return false;
1635 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001636
1637 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001638 }
1639 }
1640
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001641 // We didn't find anything, so try to correct for a typo.
Douglas Gregoraaf87162010-04-14 20:04:41 +00001642 DeclarationName Corrected;
Daniel Dunbardc32cdf2010-06-02 15:46:52 +00001643 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001644 if (!R.empty()) {
1645 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1646 if (SS.isEmpty())
1647 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1648 << FixItHint::CreateReplacement(R.getNameLoc(),
1649 R.getLookupName().getAsString());
1650 else
1651 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1652 << Name << computeDeclContext(SS, false) << R.getLookupName()
1653 << SS.getRange()
1654 << FixItHint::CreateReplacement(R.getNameLoc(),
1655 R.getLookupName().getAsString());
1656 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1657 Diag(ND->getLocation(), diag::note_previous_decl)
1658 << ND->getDeclName();
1659
1660 // Tell the callee to try to recover.
1661 return false;
1662 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001663
Douglas Gregoraaf87162010-04-14 20:04:41 +00001664 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1665 // FIXME: If we ended up with a typo for a type name or
1666 // Objective-C class name, we're in trouble because the parser
1667 // is in the wrong place to recover. Suggest the typo
1668 // correction, but don't make it a fix-it since we're not going
1669 // to recover well anyway.
1670 if (SS.isEmpty())
1671 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1672 else
1673 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1674 << Name << computeDeclContext(SS, false) << R.getLookupName()
1675 << SS.getRange();
1676
1677 // Don't try to recover; it won't work.
1678 return true;
1679 }
1680 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001681 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001682 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001683 if (SS.isEmpty())
Douglas Gregoraaf87162010-04-14 20:04:41 +00001684 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001685 else
Douglas Gregord203a162010-01-01 00:15:04 +00001686 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001687 << Name << computeDeclContext(SS, false) << Corrected
1688 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001689 return true;
1690 }
Douglas Gregord203a162010-01-01 00:15:04 +00001691 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001692 }
1693
1694 // Emit a special diagnostic for failed member lookups.
1695 // FIXME: computing the declaration context might fail here (?)
1696 if (!SS.isEmpty()) {
1697 Diag(R.getNameLoc(), diag::err_no_member)
1698 << Name << computeDeclContext(SS, false)
1699 << SS.getRange();
1700 return true;
1701 }
1702
John McCall578b69b2009-12-16 08:11:27 +00001703 // Give up, we can't recover.
1704 Diag(R.getNameLoc(), diagnostic) << Name;
1705 return true;
1706}
1707
Douglas Gregorca45da02010-11-02 20:36:02 +00001708ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1709 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001710 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1711 if (!IDecl)
1712 return 0;
1713 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1714 if (!ClassImpDecl)
1715 return 0;
Douglas Gregorca45da02010-11-02 20:36:02 +00001716 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001717 if (!property)
1718 return 0;
1719 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregorca45da02010-11-02 20:36:02 +00001720 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1721 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001722 return 0;
1723 return property;
1724}
1725
Douglas Gregorca45da02010-11-02 20:36:02 +00001726bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1727 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1728 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1729 if (!IDecl)
1730 return false;
1731 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1732 if (!ClassImpDecl)
1733 return false;
1734 if (ObjCPropertyImplDecl *PIDecl
1735 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1736 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1737 PIDecl->getPropertyIvarDecl())
1738 return false;
1739
1740 return true;
1741}
1742
Douglas Gregor312eadb2011-04-24 05:37:28 +00001743ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1744 IdentifierInfo *II,
1745 SourceLocation NameLoc) {
1746 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001747 bool LookForIvars;
1748 if (Lookup.empty())
1749 LookForIvars = true;
1750 else if (CurMeth->isClassMethod())
1751 LookForIvars = false;
1752 else
1753 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahaniand0fbadd2011-01-26 00:57:01 +00001754 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1755 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001756 if (!LookForIvars)
1757 return 0;
1758
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001759 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1760 if (!IDecl)
1761 return 0;
1762 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001763 if (!ClassImpDecl)
1764 return 0;
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001765 bool DynamicImplSeen = false;
Douglas Gregor312eadb2011-04-24 05:37:28 +00001766 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001767 if (!property)
1768 return 0;
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001769 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001770 DynamicImplSeen =
1771 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001772 // property implementation has a designated ivar. No need to assume a new
1773 // one.
1774 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1775 return 0;
1776 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001777 if (!DynamicImplSeen) {
Douglas Gregor312eadb2011-04-24 05:37:28 +00001778 QualType PropType = Context.getCanonicalType(property->getType());
1779 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001780 NameLoc, NameLoc,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001781 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian75049662010-12-15 23:29:04 +00001782 ObjCIvarDecl::Private,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001783 (Expr *)0, true);
1784 ClassImpDecl->addDecl(Ivar);
1785 IDecl->makeDeclVisibleInContext(Ivar, false);
1786 property->setPropertyIvarDecl(Ivar);
1787 return Ivar;
1788 }
1789 return 0;
1790}
1791
John McCall60d7b3a2010-08-24 06:29:42 +00001792ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001793 CXXScopeSpec &SS,
1794 UnqualifiedId &Id,
1795 bool HasTrailingLParen,
1796 bool isAddressOfOperand) {
John McCallf7a1a742009-11-24 19:00:30 +00001797 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1798 "cannot be direct & operand and have a trailing lparen");
1799
1800 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001801 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001802
John McCall129e2df2009-11-30 22:42:35 +00001803 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001804
1805 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001806 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001807 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnara25777432010-08-11 22:01:17 +00001808 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001809
Abramo Bagnara25777432010-08-11 22:01:17 +00001810 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001811 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001812 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001813
John McCallf7a1a742009-11-24 19:00:30 +00001814 // C++ [temp.dep.expr]p3:
1815 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001816 // -- an identifier that was declared with a dependent type,
1817 // (note: handled after lookup)
1818 // -- a template-id that is dependent,
1819 // (note: handled in BuildTemplateIdExpr)
1820 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001821 // -- a nested-name-specifier that contains a class-name that
1822 // names a dependent type.
1823 // Determine whether this is a member of an unknown specialization;
1824 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001825 bool DependentID = false;
1826 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1827 Name.getCXXNameType()->isDependentType()) {
1828 DependentID = true;
1829 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001830 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001831 if (RequireCompleteDeclContext(SS, DC))
1832 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001833 } else {
1834 DependentID = true;
1835 }
1836 }
1837
Chris Lattner337e5502011-02-18 01:27:55 +00001838 if (DependentID)
Abramo Bagnara25777432010-08-11 22:01:17 +00001839 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001840 TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001841
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001842 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001843 // Perform the required lookup.
Abramo Bagnara25777432010-08-11 22:01:17 +00001844 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001845 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001846 // Lookup the template name again to correctly establish the context in
1847 // which it was found. This is really unfortunate as we already did the
1848 // lookup to determine that it was a template name in the first place. If
1849 // this becomes a performance hit, we can work harder to preserve those
1850 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001851 bool MemberOfUnknownSpecialization;
1852 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1853 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001854
1855 if (MemberOfUnknownSpecialization ||
1856 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1857 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1858 TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001859 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001860 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001861 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001863 // If the result might be in a dependent base class, this is a dependent
1864 // id-expression.
1865 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1866 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1867 TemplateArgs);
1868
John McCallf7a1a742009-11-24 19:00:30 +00001869 // If this reference is in an Objective-C method, then we need to do
1870 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001871 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001872 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001873 if (E.isInvalid())
1874 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001875
Chris Lattner337e5502011-02-18 01:27:55 +00001876 if (Expr *Ex = E.takeAs<Expr>())
1877 return Owned(Ex);
1878
1879 // Synthesize ivars lazily.
Fariborz Jahaniane776f882011-01-03 18:08:02 +00001880 if (getLangOptions().ObjCDefaultSynthProperties &&
1881 getLangOptions().ObjCNonFragileABI2) {
Douglas Gregor312eadb2011-04-24 05:37:28 +00001882 if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
Fariborz Jahaniande267602010-11-17 19:41:23 +00001883 if (const ObjCPropertyDecl *Property =
1884 canSynthesizeProvisionalIvar(II)) {
1885 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1886 Diag(Property->getLocation(), diag::note_property_declare);
1887 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001888 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1889 isAddressOfOperand);
Fariborz Jahaniande267602010-11-17 19:41:23 +00001890 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001891 }
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001892 // for further use, this must be set to false if in class method.
1893 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001894 }
Chris Lattner8a934232008-03-31 00:36:02 +00001895 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001896
John McCallf7a1a742009-11-24 19:00:30 +00001897 if (R.isAmbiguous())
1898 return ExprError();
1899
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001900 // Determine whether this name might be a candidate for
1901 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001902 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001903
John McCallf7a1a742009-11-24 19:00:30 +00001904 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001905 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001906 // in C90, extension in C99, forbidden in C++).
1907 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1908 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1909 if (D) R.addDecl(D);
1910 }
1911
1912 // If this name wasn't predeclared and if this is not a function
1913 // call, diagnose the problem.
1914 if (R.empty()) {
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001915 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001916 return ExprError();
1917
1918 assert(!R.empty() &&
1919 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001920
1921 // If we found an Objective-C instance variable, let
1922 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001923 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001924 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1925 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001926 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001927 assert(E.isInvalid() || E.get());
1928 return move(E);
1929 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001930 }
1931 }
Mike Stump1eb44332009-09-09 15:08:12 +00001932
John McCallf7a1a742009-11-24 19:00:30 +00001933 // This is guaranteed from this point on.
1934 assert(!R.empty() || ADL);
1935
John McCallaa81e162009-12-01 22:10:20 +00001936 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001937 // C++ [class.mfct.non-static]p3:
1938 // When an id-expression that is not part of a class member access
1939 // syntax and not used to form a pointer to member is used in the
1940 // body of a non-static member function of class X, if name lookup
1941 // resolves the name in the id-expression to a non-static non-type
1942 // member of some class C, the id-expression is transformed into a
1943 // class member access expression using (*this) as the
1944 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001945 //
1946 // But we don't actually need to do this for '&' operands if R
1947 // resolved to a function or overloaded function set, because the
1948 // expression is ill-formed if it actually works out to be a
1949 // non-static member function:
1950 //
1951 // C++ [expr.ref]p4:
1952 // Otherwise, if E1.E2 refers to a non-static member function. . .
1953 // [t]he expression can be used only as the left-hand operand of a
1954 // member function call.
1955 //
1956 // There are other safeguards against such uses, but it's important
1957 // to get this right here so that we don't end up making a
1958 // spuriously dependent expression if we're inside a dependent
1959 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001960 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001961 bool MightBeImplicitMember;
1962 if (!isAddressOfOperand)
1963 MightBeImplicitMember = true;
1964 else if (!SS.isEmpty())
1965 MightBeImplicitMember = false;
1966 else if (R.isOverloadedResult())
1967 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001968 else if (R.isUnresolvableResult())
1969 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001970 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001971 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1972 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001973
1974 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00001975 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001976 }
1977
John McCallf7a1a742009-11-24 19:00:30 +00001978 if (TemplateArgs)
1979 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001980
John McCallf7a1a742009-11-24 19:00:30 +00001981 return BuildDeclarationNameExpr(SS, R, ADL);
1982}
1983
John McCall3b4294e2009-12-16 12:17:52 +00001984/// Builds an expression which might be an implicit member expression.
John McCall60d7b3a2010-08-24 06:29:42 +00001985ExprResult
John McCall3b4294e2009-12-16 12:17:52 +00001986Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1987 LookupResult &R,
1988 const TemplateArgumentListInfo *TemplateArgs) {
1989 switch (ClassifyImplicitMemberAccess(*this, R)) {
1990 case IMA_Instance:
1991 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1992
John McCall3b4294e2009-12-16 12:17:52 +00001993 case IMA_Mixed:
1994 case IMA_Mixed_Unrelated:
1995 case IMA_Unresolved:
1996 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1997
1998 case IMA_Static:
1999 case IMA_Mixed_StaticContext:
2000 case IMA_Unresolved_StaticContext:
2001 if (TemplateArgs)
2002 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
2003 return BuildDeclarationNameExpr(SS, R, false);
2004
2005 case IMA_Error_StaticContext:
2006 case IMA_Error_Unrelated:
John McCall5808ce42011-02-03 08:15:49 +00002007 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
2008 R.getLookupNameInfo());
John McCall3b4294e2009-12-16 12:17:52 +00002009 return ExprError();
2010 }
2011
2012 llvm_unreachable("unexpected instance member access kind");
2013 return ExprError();
2014}
2015
John McCall129e2df2009-11-30 22:42:35 +00002016/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2017/// declaration name, generally during template instantiation.
2018/// There's a large number of things which don't need to be done along
2019/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00002020ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002021Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002022 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00002023 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00002024 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00002025 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00002026
John McCall77bb1aa2010-05-01 00:40:08 +00002027 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00002028 return ExprError();
2029
Abramo Bagnara25777432010-08-11 22:01:17 +00002030 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00002031 LookupQualifiedName(R, DC);
2032
2033 if (R.isAmbiguous())
2034 return ExprError();
2035
2036 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002037 Diag(NameInfo.getLoc(), diag::err_no_member)
2038 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00002039 return ExprError();
2040 }
2041
2042 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
2043}
2044
2045/// LookupInObjCMethod - The parser has read a name in, and Sema has
2046/// detected that we're currently inside an ObjC method. Perform some
2047/// additional lookup.
2048///
2049/// Ideally, most of this would be done by lookup, but there's
2050/// actually quite a lot of extra work involved.
2051///
2052/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00002053ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002054Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00002055 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00002056 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00002057 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002058
John McCallf7a1a742009-11-24 19:00:30 +00002059 // There are two cases to handle here. 1) scoped lookup could have failed,
2060 // in which case we should look for an ivar. 2) scoped lookup could have
2061 // found a decl, but that decl is outside the current instance method (i.e.
2062 // a global variable). In these two cases, we do a lookup for an ivar with
2063 // this name, if the lookup sucedes, we replace it our current decl.
2064
2065 // If we're in a class method, we don't normally want to look for
2066 // ivars. But if we don't find anything else, and there's an
2067 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00002068 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00002069
2070 bool LookForIvars;
2071 if (Lookup.empty())
2072 LookForIvars = true;
2073 else if (IsClassMethod)
2074 LookForIvars = false;
2075 else
2076 LookForIvars = (Lookup.isSingleResult() &&
2077 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00002078 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00002079 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00002080 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00002081 ObjCInterfaceDecl *ClassDeclared;
2082 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2083 // Diagnose using an ivar in a class method.
2084 if (IsClassMethod)
2085 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2086 << IV->getDeclName());
2087
2088 // If we're referencing an invalid decl, just return this as a silent
2089 // error node. The error diagnostic was already emitted on the decl.
2090 if (IV->isInvalidDecl())
2091 return ExprError();
2092
2093 // Check if referencing a field with __attribute__((deprecated)).
2094 if (DiagnoseUseOfDecl(IV, Loc))
2095 return ExprError();
2096
2097 // Diagnose the use of an ivar outside of the declaring class.
2098 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2099 ClassDeclared != IFace)
2100 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2101
2102 // FIXME: This should use a new expr for a direct reference, don't
2103 // turn this into Self->ivar, just return a BareIVarExpr or something.
2104 IdentifierInfo &II = Context.Idents.get("self");
2105 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002106 SelfName.setIdentifier(&II, SourceLocation());
John McCallf7a1a742009-11-24 19:00:30 +00002107 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00002108 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00002109 SelfName, false, false);
2110 if (SelfExpr.isInvalid())
2111 return ExprError();
2112
John Wiegley429bb272011-04-08 18:41:53 +00002113 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2114 if (SelfExpr.isInvalid())
2115 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00002116
John McCallf7a1a742009-11-24 19:00:30 +00002117 MarkDeclarationReferenced(Loc, IV);
Fariborz Jahanianb8f17ab2011-04-12 23:39:33 +00002118 Expr *base = SelfExpr.take();
2119 base = base->IgnoreParenImpCasts();
2120 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(base)) {
2121 const NamedDecl *ND = DE->getDecl();
2122 if (!isa<ImplicitParamDecl>(ND)) {
Fariborz Jahanianeefa76e2011-04-15 17:04:42 +00002123 // relax the rule such that it is allowed to have a shadow 'self'
2124 // where stand-alone ivar can be found in this 'self' object.
2125 // This is to match gcc's behavior.
2126 ObjCInterfaceDecl *selfIFace = 0;
2127 if (const ObjCObjectPointerType *OPT =
2128 base->getType()->getAsObjCInterfacePointerType())
2129 selfIFace = OPT->getInterfaceDecl();
2130 if (!selfIFace ||
2131 !selfIFace->lookupInstanceVariable(IV->getIdentifier())) {
Fariborz Jahanianb8f17ab2011-04-12 23:39:33 +00002132 Diag(Loc, diag::error_implicit_ivar_access)
2133 << IV->getDeclName();
2134 Diag(ND->getLocation(), diag::note_declared_at);
2135 return ExprError();
2136 }
Fariborz Jahanianeefa76e2011-04-15 17:04:42 +00002137 }
Fariborz Jahanianb8f17ab2011-04-12 23:39:33 +00002138 }
John McCallf7a1a742009-11-24 19:00:30 +00002139 return Owned(new (Context)
2140 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley429bb272011-04-08 18:41:53 +00002141 SelfExpr.take(), true, true));
John McCallf7a1a742009-11-24 19:00:30 +00002142 }
Chris Lattneraec43db2010-04-12 05:10:17 +00002143 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00002144 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00002145 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00002146 ObjCInterfaceDecl *ClassDeclared;
2147 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2148 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2149 IFace == ClassDeclared)
2150 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2151 }
2152 }
2153
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00002154 if (Lookup.empty() && II && AllowBuiltinCreation) {
2155 // FIXME. Consolidate this with similar code in LookupName.
2156 if (unsigned BuiltinID = II->getBuiltinID()) {
2157 if (!(getLangOptions().CPlusPlus &&
2158 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2159 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2160 S, Lookup.isForRedeclaration(),
2161 Lookup.getNameLoc());
2162 if (D) Lookup.addDecl(D);
2163 }
2164 }
2165 }
John McCallf7a1a742009-11-24 19:00:30 +00002166 // Sentinel value saying that we didn't do anything special.
2167 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00002168}
John McCallba135432009-11-21 08:51:07 +00002169
John McCall6bb80172010-03-30 21:47:33 +00002170/// \brief Cast a base object to a member's actual type.
2171///
2172/// Logically this happens in three phases:
2173///
2174/// * First we cast from the base type to the naming class.
2175/// The naming class is the class into which we were looking
2176/// when we found the member; it's the qualifier type if a
2177/// qualifier was provided, and otherwise it's the base type.
2178///
2179/// * Next we cast from the naming class to the declaring class.
2180/// If the member we found was brought into a class's scope by
2181/// a using declaration, this is that class; otherwise it's
2182/// the class declaring the member.
2183///
2184/// * Finally we cast from the declaring class to the "true"
2185/// declaring class of the member. This conversion does not
2186/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00002187ExprResult
2188Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002189 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002190 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002191 NamedDecl *Member) {
2192 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2193 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00002194 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002195
Douglas Gregor5fccd362010-03-03 23:55:11 +00002196 QualType DestRecordType;
2197 QualType DestType;
2198 QualType FromRecordType;
2199 QualType FromType = From->getType();
2200 bool PointerConversions = false;
2201 if (isa<FieldDecl>(Member)) {
2202 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002203
Douglas Gregor5fccd362010-03-03 23:55:11 +00002204 if (FromType->getAs<PointerType>()) {
2205 DestType = Context.getPointerType(DestRecordType);
2206 FromRecordType = FromType->getPointeeType();
2207 PointerConversions = true;
2208 } else {
2209 DestType = DestRecordType;
2210 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002211 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002212 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2213 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00002214 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002215
Douglas Gregor5fccd362010-03-03 23:55:11 +00002216 DestType = Method->getThisType(Context);
2217 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002218
Douglas Gregor5fccd362010-03-03 23:55:11 +00002219 if (FromType->getAs<PointerType>()) {
2220 FromRecordType = FromType->getPointeeType();
2221 PointerConversions = true;
2222 } else {
2223 FromRecordType = FromType;
2224 DestType = DestRecordType;
2225 }
2226 } else {
2227 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002228 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002229 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002230
Douglas Gregor5fccd362010-03-03 23:55:11 +00002231 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002232 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002233
Douglas Gregor5fccd362010-03-03 23:55:11 +00002234 // If the unqualified types are the same, no conversion is necessary.
2235 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002236 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002237
John McCall6bb80172010-03-30 21:47:33 +00002238 SourceRange FromRange = From->getSourceRange();
2239 SourceLocation FromLoc = FromRange.getBegin();
2240
John McCall5baba9d2010-08-25 10:28:54 +00002241 ExprValueKind VK = CastCategory(From);
Sebastian Redl906082e2010-07-20 04:20:21 +00002242
Douglas Gregor5fccd362010-03-03 23:55:11 +00002243 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002244 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002245 // class name.
2246 //
2247 // If the member was a qualified name and the qualified referred to a
2248 // specific base subobject type, we'll cast to that intermediate type
2249 // first and then to the object in which the member is declared. That allows
2250 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2251 //
2252 // class Base { public: int x; };
2253 // class Derived1 : public Base { };
2254 // class Derived2 : public Base { };
2255 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2256 //
2257 // void VeryDerived::f() {
2258 // x = 17; // error: ambiguous base subobjects
2259 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2260 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002261 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002262 QualType QType = QualType(Qualifier->getAsType(), 0);
2263 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2264 assert(QType->isRecordType() && "lookup done with non-record type");
2265
2266 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2267
2268 // In C++98, the qualifier type doesn't actually have to be a base
2269 // type of the object type, in which case we just ignore it.
2270 // Otherwise build the appropriate casts.
2271 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002272 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002273 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002274 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002275 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002276
Douglas Gregor5fccd362010-03-03 23:55:11 +00002277 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002278 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002279 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2280 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002281
2282 FromType = QType;
2283 FromRecordType = QRecordType;
2284
2285 // If the qualifier type was the same as the destination type,
2286 // we're done.
2287 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002288 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002289 }
2290 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002291
John McCall6bb80172010-03-30 21:47:33 +00002292 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002293
John McCall6bb80172010-03-30 21:47:33 +00002294 // If we actually found the member through a using declaration, cast
2295 // down to the using declaration's type.
2296 //
2297 // Pointer equality is fine here because only one declaration of a
2298 // class ever has member declarations.
2299 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2300 assert(isa<UsingShadowDecl>(FoundDecl));
2301 QualType URecordType = Context.getTypeDeclType(
2302 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2303
2304 // We only need to do this if the naming-class to declaring-class
2305 // conversion is non-trivial.
2306 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2307 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002308 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002309 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002310 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002311 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002312
John McCall6bb80172010-03-30 21:47:33 +00002313 QualType UType = URecordType;
2314 if (PointerConversions)
2315 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002316 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2317 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002318 FromType = UType;
2319 FromRecordType = URecordType;
2320 }
2321
2322 // We don't do access control for the conversion from the
2323 // declaring class to the true declaring class.
2324 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002325 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002326
John McCallf871d0c2010-08-07 06:22:56 +00002327 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002328 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2329 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002330 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002331 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002332
John Wiegley429bb272011-04-08 18:41:53 +00002333 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2334 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002335}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002336
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002337/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00002338static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00002339 const CXXScopeSpec &SS, ValueDecl *Member,
John McCall161755a2010-04-06 21:38:20 +00002340 DeclAccessPair FoundDecl,
Abramo Bagnara25777432010-08-11 22:01:17 +00002341 const DeclarationNameInfo &MemberNameInfo,
2342 QualType Ty,
John McCallf89e55a2010-11-18 06:31:45 +00002343 ExprValueKind VK, ExprObjectKind OK,
John McCallf7a1a742009-11-24 19:00:30 +00002344 const TemplateArgumentListInfo *TemplateArgs = 0) {
Douglas Gregor40d96a62011-02-28 21:54:11 +00002345 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
Abramo Bagnara25777432010-08-11 22:01:17 +00002346 Member, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002347 TemplateArgs, Ty, VK, OK);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002348}
2349
John McCalldfa1edb2010-11-23 20:48:44 +00002350static ExprResult
2351BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2352 const CXXScopeSpec &SS, FieldDecl *Field,
2353 DeclAccessPair FoundDecl,
2354 const DeclarationNameInfo &MemberNameInfo) {
2355 // x.a is an l-value if 'a' has a reference type. Otherwise:
2356 // x.a is an l-value/x-value/pr-value if the base is (and note
2357 // that *x is always an l-value), except that if the base isn't
2358 // an ordinary object then we must have an rvalue.
2359 ExprValueKind VK = VK_LValue;
2360 ExprObjectKind OK = OK_Ordinary;
2361 if (!IsArrow) {
2362 if (BaseExpr->getObjectKind() == OK_Ordinary)
2363 VK = BaseExpr->getValueKind();
2364 else
2365 VK = VK_RValue;
2366 }
2367 if (VK != VK_RValue && Field->isBitField())
2368 OK = OK_BitField;
2369
2370 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2371 QualType MemberType = Field->getType();
2372 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2373 MemberType = Ref->getPointeeType();
2374 VK = VK_LValue;
2375 } else {
2376 QualType BaseType = BaseExpr->getType();
2377 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2378
2379 Qualifiers BaseQuals = BaseType.getQualifiers();
2380
2381 // GC attributes are never picked up by members.
2382 BaseQuals.removeObjCGCAttr();
2383
2384 // CVR attributes from the base are picked up by members,
2385 // except that 'mutable' members don't pick up 'const'.
2386 if (Field->isMutable()) BaseQuals.removeConst();
2387
2388 Qualifiers MemberQuals
2389 = S.Context.getCanonicalType(MemberType).getQualifiers();
2390
2391 // TR 18037 does not allow fields to be declared with address spaces.
2392 assert(!MemberQuals.hasAddressSpace());
2393
2394 Qualifiers Combined = BaseQuals + MemberQuals;
2395 if (Combined != MemberQuals)
2396 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2397 }
2398
2399 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
John Wiegley429bb272011-04-08 18:41:53 +00002400 ExprResult Base =
2401 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2402 FoundDecl, Field);
2403 if (Base.isInvalid())
John McCalldfa1edb2010-11-23 20:48:44 +00002404 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00002405 return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
John McCalldfa1edb2010-11-23 20:48:44 +00002406 Field, FoundDecl, MemberNameInfo,
2407 MemberType, VK, OK));
2408}
2409
John McCallaa81e162009-12-01 22:10:20 +00002410/// Builds an implicit member access expression. The current context
2411/// is known to be an instance method, and the given unqualified lookup
2412/// set is known to contain only instance members, at least one of which
2413/// is from an appropriate type.
John McCall60d7b3a2010-08-24 06:29:42 +00002414ExprResult
John McCallaa81e162009-12-01 22:10:20 +00002415Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2416 LookupResult &R,
2417 const TemplateArgumentListInfo *TemplateArgs,
2418 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00002419 assert(!R.empty() && !R.isAmbiguous());
2420
John McCall5808ce42011-02-03 08:15:49 +00002421 SourceLocation loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00002422
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002423 // We may have found a field within an anonymous union or struct
2424 // (C++ [class.union]).
John McCallf7a1a742009-11-24 19:00:30 +00002425 // FIXME: template-ids inside anonymous structs?
Francois Pichet87c2e122010-11-21 06:08:52 +00002426 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCall5808ce42011-02-03 08:15:49 +00002427 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet87c2e122010-11-21 06:08:52 +00002428
John McCall5808ce42011-02-03 08:15:49 +00002429 // If this is known to be an instance access, go ahead and build an
2430 // implicit 'this' expression now.
John McCallaa81e162009-12-01 22:10:20 +00002431 // 'this' expression now.
John McCall5808ce42011-02-03 08:15:49 +00002432 CXXMethodDecl *method = tryCaptureCXXThis();
2433 assert(method && "didn't correctly pre-flight capture of 'this'");
2434
2435 QualType thisType = method->getThisType(Context);
2436 Expr *baseExpr = 0; // null signifies implicit access
John McCallaa81e162009-12-01 22:10:20 +00002437 if (IsKnownInstance) {
Douglas Gregor828a1972010-01-07 23:12:05 +00002438 SourceLocation Loc = R.getNameLoc();
2439 if (SS.getRange().isValid())
2440 Loc = SS.getRange().getBegin();
John McCall5808ce42011-02-03 08:15:49 +00002441 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
Douglas Gregor88a35142008-12-22 05:46:06 +00002442 }
2443
John McCall5808ce42011-02-03 08:15:49 +00002444 return BuildMemberReferenceExpr(baseExpr, thisType,
John McCallaa81e162009-12-01 22:10:20 +00002445 /*OpLoc*/ SourceLocation(),
2446 /*IsArrow*/ true,
John McCallc2233c52010-01-15 08:34:02 +00002447 SS,
2448 /*FirstQualifierInScope*/ 0,
2449 R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00002450}
2451
John McCallf7a1a742009-11-24 19:00:30 +00002452bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002453 const LookupResult &R,
2454 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002455 // Only when used directly as the postfix-expression of a call.
2456 if (!HasTrailingLParen)
2457 return false;
2458
2459 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002460 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002461 return false;
2462
2463 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002464 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002465 return false;
2466
2467 // Turn off ADL when we find certain kinds of declarations during
2468 // normal lookup:
2469 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2470 NamedDecl *D = *I;
2471
2472 // C++0x [basic.lookup.argdep]p3:
2473 // -- a declaration of a class member
2474 // Since using decls preserve this property, we check this on the
2475 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002476 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002477 return false;
2478
2479 // C++0x [basic.lookup.argdep]p3:
2480 // -- a block-scope function declaration that is not a
2481 // using-declaration
2482 // NOTE: we also trigger this for function templates (in fact, we
2483 // don't check the decl type at all, since all other decl types
2484 // turn off ADL anyway).
2485 if (isa<UsingShadowDecl>(D))
2486 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2487 else if (D->getDeclContext()->isFunctionOrMethod())
2488 return false;
2489
2490 // C++0x [basic.lookup.argdep]p3:
2491 // -- a declaration that is neither a function or a function
2492 // template
2493 // And also for builtin functions.
2494 if (isa<FunctionDecl>(D)) {
2495 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2496
2497 // But also builtin functions.
2498 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2499 return false;
2500 } else if (!isa<FunctionTemplateDecl>(D))
2501 return false;
2502 }
2503
2504 return true;
2505}
2506
2507
John McCallba135432009-11-21 08:51:07 +00002508/// Diagnoses obvious problems with the use of the given declaration
2509/// as an expression. This is only actually called for lookups that
2510/// were not overloaded, and it doesn't promise that the declaration
2511/// will in fact be used.
2512static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002513 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002514 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2515 return true;
2516 }
2517
2518 if (isa<ObjCInterfaceDecl>(D)) {
2519 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2520 return true;
2521 }
2522
2523 if (isa<NamespaceDecl>(D)) {
2524 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2525 return true;
2526 }
2527
2528 return false;
2529}
2530
John McCall60d7b3a2010-08-24 06:29:42 +00002531ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002532Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002533 LookupResult &R,
2534 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002535 // If this is a single, fully-resolved result and we don't need ADL,
2536 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002537 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002538 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2539 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002540
2541 // We only need to check the declaration if there's exactly one
2542 // result, because in the overloaded case the results can only be
2543 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002544 if (R.isSingleResult() &&
2545 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002546 return ExprError();
2547
John McCallc373d482010-01-27 01:50:18 +00002548 // Otherwise, just build an unresolved lookup expression. Suppress
2549 // any lookup-related diagnostics; we'll hash these out later, when
2550 // we've picked a target.
2551 R.suppressDiagnostics();
2552
John McCallba135432009-11-21 08:51:07 +00002553 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002554 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002555 SS.getWithLocInContext(Context),
2556 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002557 NeedsADL, R.isOverloadedResult(),
2558 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002559
2560 return Owned(ULE);
2561}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002562
John McCallba135432009-11-21 08:51:07 +00002563/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002564ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002565Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002566 const DeclarationNameInfo &NameInfo,
2567 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002568 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002569 assert(!isa<FunctionTemplateDecl>(D) &&
2570 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002571
Abramo Bagnara25777432010-08-11 22:01:17 +00002572 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002573 if (CheckDeclInExpr(*this, Loc, D))
2574 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002575
Douglas Gregor9af2f522009-12-01 16:58:18 +00002576 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2577 // Specifically diagnose references to class templates that are missing
2578 // a template argument list.
2579 Diag(Loc, diag::err_template_decl_ref)
2580 << Template << SS.getRange();
2581 Diag(Template->getLocation(), diag::note_template_decl_here);
2582 return ExprError();
2583 }
2584
2585 // Make sure that we're referring to a value.
2586 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2587 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002588 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002589 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002590 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002591 return ExprError();
2592 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002593
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002594 // Check whether this declaration can be used. Note that we suppress
2595 // this check when we're going to perform argument-dependent lookup
2596 // on this function name, because this might not be the function
2597 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002598 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002599 return ExprError();
2600
Steve Naroffdd972f22008-09-05 22:11:13 +00002601 // Only create DeclRefExpr's for valid Decl's.
2602 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002603 return ExprError();
2604
John McCall5808ce42011-02-03 08:15:49 +00002605 // Handle members of anonymous structs and unions. If we got here,
2606 // and the reference is to a class member indirect field, then this
2607 // must be the subject of a pointer-to-member expression.
2608 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2609 if (!indirectField->isCXXClassMember())
2610 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2611 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002612
Chris Lattner639e2d32008-10-20 05:16:36 +00002613 // If the identifier reference is inside a block, and it refers to a value
2614 // that is outside the block, create a BlockDeclRefExpr instead of a
2615 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2616 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002617 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002618 // We do not do this for things like enum constants, global variables, etc,
2619 // as they do not get snapshotted.
2620 //
John McCall6b5a61b2011-02-07 10:33:21 +00002621 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCall469a1eb2011-02-02 13:00:07 +00002622 case CR_Error:
2623 return ExprError();
Mike Stump0d6fd572010-01-05 02:56:35 +00002624
John McCall469a1eb2011-02-02 13:00:07 +00002625 case CR_Capture:
John McCall6b5a61b2011-02-07 10:33:21 +00002626 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2627 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2628
2629 case CR_CaptureByRef:
2630 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2631 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCall76a40212011-02-09 01:13:10 +00002632
2633 case CR_NoCapture: {
2634 // If this reference is not in a block or if the referenced
2635 // variable is within the block, create a normal DeclRefExpr.
2636
2637 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002638 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002639
2640 switch (D->getKind()) {
2641 // Ignore all the non-ValueDecl kinds.
2642#define ABSTRACT_DECL(kind)
2643#define VALUE(type, base)
2644#define DECL(type, base) \
2645 case Decl::type:
2646#include "clang/AST/DeclNodes.inc"
2647 llvm_unreachable("invalid value decl kind");
2648 return ExprError();
2649
2650 // These shouldn't make it here.
2651 case Decl::ObjCAtDefsField:
2652 case Decl::ObjCIvar:
2653 llvm_unreachable("forming non-member reference to ivar?");
2654 return ExprError();
2655
2656 // Enum constants are always r-values and never references.
2657 // Unresolved using declarations are dependent.
2658 case Decl::EnumConstant:
2659 case Decl::UnresolvedUsingValue:
2660 valueKind = VK_RValue;
2661 break;
2662
2663 // Fields and indirect fields that got here must be for
2664 // pointer-to-member expressions; we just call them l-values for
2665 // internal consistency, because this subexpression doesn't really
2666 // exist in the high-level semantics.
2667 case Decl::Field:
2668 case Decl::IndirectField:
2669 assert(getLangOptions().CPlusPlus &&
2670 "building reference to field in C?");
2671
2672 // These can't have reference type in well-formed programs, but
2673 // for internal consistency we do this anyway.
2674 type = type.getNonReferenceType();
2675 valueKind = VK_LValue;
2676 break;
2677
2678 // Non-type template parameters are either l-values or r-values
2679 // depending on the type.
2680 case Decl::NonTypeTemplateParm: {
2681 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2682 type = reftype->getPointeeType();
2683 valueKind = VK_LValue; // even if the parameter is an r-value reference
2684 break;
2685 }
2686
2687 // For non-references, we need to strip qualifiers just in case
2688 // the template parameter was declared as 'const int' or whatever.
2689 valueKind = VK_RValue;
2690 type = type.getUnqualifiedType();
2691 break;
2692 }
2693
2694 case Decl::Var:
2695 // In C, "extern void blah;" is valid and is an r-value.
2696 if (!getLangOptions().CPlusPlus &&
2697 !type.hasQualifiers() &&
2698 type->isVoidType()) {
2699 valueKind = VK_RValue;
2700 break;
2701 }
2702 // fallthrough
2703
2704 case Decl::ImplicitParam:
2705 case Decl::ParmVar:
2706 // These are always l-values.
2707 valueKind = VK_LValue;
2708 type = type.getNonReferenceType();
2709 break;
2710
2711 case Decl::Function: {
John McCall755d8492011-04-12 00:42:48 +00002712 const FunctionType *fty = type->castAs<FunctionType>();
2713
2714 // If we're referring to a function with an __unknown_anytype
2715 // result type, make the entire expression __unknown_anytype.
2716 if (fty->getResultType() == Context.UnknownAnyTy) {
2717 type = Context.UnknownAnyTy;
2718 valueKind = VK_RValue;
2719 break;
2720 }
2721
John McCall76a40212011-02-09 01:13:10 +00002722 // Functions are l-values in C++.
2723 if (getLangOptions().CPlusPlus) {
2724 valueKind = VK_LValue;
2725 break;
2726 }
2727
2728 // C99 DR 316 says that, if a function type comes from a
2729 // function definition (without a prototype), that type is only
2730 // used for checking compatibility. Therefore, when referencing
2731 // the function, we pretend that we don't have the full function
2732 // type.
John McCall755d8492011-04-12 00:42:48 +00002733 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2734 isa<FunctionProtoType>(fty))
2735 type = Context.getFunctionNoProtoType(fty->getResultType(),
2736 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002737
2738 // Functions are r-values in C.
2739 valueKind = VK_RValue;
2740 break;
2741 }
2742
2743 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002744 // If we're referring to a method with an __unknown_anytype
2745 // result type, make the entire expression __unknown_anytype.
2746 // This should only be possible with a type written directly.
2747 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(VD->getType()))
2748 if (proto->getResultType() == Context.UnknownAnyTy) {
2749 type = Context.UnknownAnyTy;
2750 valueKind = VK_RValue;
2751 break;
2752 }
2753
John McCall76a40212011-02-09 01:13:10 +00002754 // C++ methods are l-values if static, r-values if non-static.
2755 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2756 valueKind = VK_LValue;
2757 break;
2758 }
2759 // fallthrough
2760
2761 case Decl::CXXConversion:
2762 case Decl::CXXDestructor:
2763 case Decl::CXXConstructor:
2764 valueKind = VK_RValue;
2765 break;
2766 }
2767
2768 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2769 }
2770
John McCall469a1eb2011-02-02 13:00:07 +00002771 }
John McCallf89e55a2010-11-18 06:31:45 +00002772
John McCall6b5a61b2011-02-07 10:33:21 +00002773 llvm_unreachable("unknown capture result");
2774 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002775}
2776
John McCall755d8492011-04-12 00:42:48 +00002777ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002778 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002779
Reid Spencer5f016e22007-07-11 17:01:13 +00002780 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00002781 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002782 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2783 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2784 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002785 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002786
Chris Lattnerfa28b302008-01-12 08:14:25 +00002787 // Pre-defined identifiers are of type char[x], where x is the length of the
2788 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002789
Anders Carlsson3a082d82009-09-08 18:24:21 +00002790 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002791 if (!currentDecl && getCurBlock())
2792 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002793 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002794 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002795 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002796 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002797
Anders Carlsson773f3972009-09-11 01:22:35 +00002798 QualType ResTy;
2799 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2800 ResTy = Context.DependentTy;
2801 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002802 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002803
Anders Carlsson773f3972009-09-11 01:22:35 +00002804 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002805 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002806 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2807 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002808 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002809}
2810
John McCall60d7b3a2010-08-24 06:29:42 +00002811ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002812 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002813 bool Invalid = false;
2814 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2815 if (Invalid)
2816 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002817
Benjamin Kramerddeea562010-02-27 13:44:12 +00002818 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2819 PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00002820 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002821 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002822
Chris Lattnere8337df2009-12-30 21:19:39 +00002823 QualType Ty;
2824 if (!getLangOptions().CPlusPlus)
2825 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2826 else if (Literal.isWide())
2827 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002828 else if (Literal.isMultiChar())
2829 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002830 else
2831 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002832
Sebastian Redle91b3bc2009-01-20 22:23:13 +00002833 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2834 Literal.isWide(),
Chris Lattnere8337df2009-12-30 21:19:39 +00002835 Ty, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002836}
2837
John McCall60d7b3a2010-08-24 06:29:42 +00002838ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002839 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002840 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2841 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002842 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00002843 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002844 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002845 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002846 }
Ted Kremenek28396602009-01-13 23:19:12 +00002847
Reid Spencer5f016e22007-07-11 17:01:13 +00002848 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002849 // Add padding so that NumericLiteralParser can overread by one character.
2850 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002851 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002852
Reid Spencer5f016e22007-07-11 17:01:13 +00002853 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002854 bool Invalid = false;
2855 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2856 if (Invalid)
2857 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002858
Mike Stump1eb44332009-09-09 15:08:12 +00002859 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002860 Tok.getLocation(), PP);
2861 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002862 return ExprError();
2863
Chris Lattner5d661452007-08-26 03:42:43 +00002864 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002865
Chris Lattner5d661452007-08-26 03:42:43 +00002866 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002867 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002868 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002869 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002870 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002871 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002872 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002873 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002874
2875 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2876
John McCall94c939d2009-12-24 09:08:04 +00002877 using llvm::APFloat;
2878 APFloat Val(Format);
2879
2880 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002881
2882 // Overflow is always an error, but underflow is only an error if
2883 // we underflowed to zero (APFloat reports denormals as underflow).
2884 if ((result & APFloat::opOverflow) ||
2885 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002886 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002887 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002888 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002889 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002890 APFloat::getLargest(Format).toString(buffer);
2891 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002892 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002893 APFloat::getSmallest(Format).toString(buffer);
2894 }
2895
2896 Diag(Tok.getLocation(), diagnostic)
2897 << Ty
2898 << llvm::StringRef(buffer.data(), buffer.size());
2899 }
2900
2901 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002902 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002903
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002904 if (Ty == Context.DoubleTy) {
2905 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002906 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002907 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2908 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002909 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002910 }
2911 }
Chris Lattner5d661452007-08-26 03:42:43 +00002912 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002913 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002914 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002915 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002916
Neil Boothb9449512007-08-29 22:00:19 +00002917 // long long is a C99 feature.
2918 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00002919 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00002920 Diag(Tok.getLocation(), diag::ext_longlong);
2921
Reid Spencer5f016e22007-07-11 17:01:13 +00002922 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00002923 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002924
Reid Spencer5f016e22007-07-11 17:01:13 +00002925 if (Literal.GetIntegerValue(ResultVal)) {
2926 // If this value didn't fit into uintmax_t, warn and force to ull.
2927 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002928 Ty = Context.UnsignedLongLongTy;
2929 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002930 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002931 } else {
2932 // If this value fits into a ULL, try to figure out what else it fits into
2933 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002934
Reid Spencer5f016e22007-07-11 17:01:13 +00002935 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2936 // be an unsigned int.
2937 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2938
2939 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002940 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002941 if (!Literal.isLong && !Literal.isLongLong) {
2942 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002943 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002944
Reid Spencer5f016e22007-07-11 17:01:13 +00002945 // Does it fit in a unsigned int?
2946 if (ResultVal.isIntN(IntSize)) {
2947 // Does it fit in a signed int?
2948 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002949 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002950 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002951 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002952 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002953 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002954 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002955
Reid Spencer5f016e22007-07-11 17:01:13 +00002956 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002957 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002958 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002959
Reid Spencer5f016e22007-07-11 17:01:13 +00002960 // Does it fit in a unsigned long?
2961 if (ResultVal.isIntN(LongSize)) {
2962 // Does it fit in a signed long?
2963 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002964 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002965 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002966 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002967 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002968 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002969 }
2970
Reid Spencer5f016e22007-07-11 17:01:13 +00002971 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002972 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002973 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002974
Reid Spencer5f016e22007-07-11 17:01:13 +00002975 // Does it fit in a unsigned long long?
2976 if (ResultVal.isIntN(LongLongSize)) {
2977 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002978 // To be compatible with MSVC, hex integer literals ending with the
2979 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002980 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2981 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002982 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002983 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002984 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002985 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002986 }
2987 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002988
Reid Spencer5f016e22007-07-11 17:01:13 +00002989 // If we still couldn't decide a type, we probably have something that
2990 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002991 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002992 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002993 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002994 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002995 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002996
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002997 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002998 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002999 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003000 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00003001 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00003002
Chris Lattner5d661452007-08-26 03:42:43 +00003003 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3004 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00003005 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003006 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00003007
3008 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00003009}
3010
John McCall60d7b3a2010-08-24 06:29:42 +00003011ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCall9ae2f072010-08-23 23:25:46 +00003012 SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00003013 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00003014 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00003015}
3016
3017/// The UsualUnaryConversions() function is *not* called by this routine.
3018/// See C99 6.3.2.1p[2-4] for more details.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003019bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
3020 SourceLocation OpLoc,
3021 SourceRange ExprRange,
3022 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl28507842009-02-26 14:39:58 +00003023 if (exprType->isDependentType())
3024 return false;
3025
Sebastian Redl5d484e82009-11-23 17:18:46 +00003026 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3027 // the result is the size of the referenced type."
3028 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3029 // result shall be the alignment of the referenced type."
3030 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
3031 exprType = Ref->getPointeeType();
3032
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003033 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3034 // scalar or vector data type argument..."
3035 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3036 // type (C99 6.2.5p18) or void.
3037 if (ExprKind == UETT_VecStep) {
3038 if (!(exprType->isArithmeticType() || exprType->isVoidType() ||
3039 exprType->isVectorType())) {
3040 Diag(OpLoc, diag::err_vecstep_non_scalar_vector_type)
3041 << exprType << ExprRange;
3042 return true;
3043 }
3044 }
3045
Reid Spencer5f016e22007-07-11 17:01:13 +00003046 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00003047 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003048 // alignof(function) is allowed as an extension.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003049 if (ExprKind == UETT_SizeOf)
3050 Diag(OpLoc, diag::ext_sizeof_function_type)
3051 << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00003052 return false;
3053 }
Mike Stump1eb44332009-09-09 15:08:12 +00003054
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003055 // Allow sizeof(void)/alignof(void) as an extension. vec_step(void) is not
3056 // an extension, as void is a built-in scalar type (OpenCL 1.1 6.1.1).
Chris Lattner01072922009-01-24 19:46:37 +00003057 if (exprType->isVoidType()) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003058 if (ExprKind != UETT_VecStep)
3059 Diag(OpLoc, diag::ext_sizeof_void_type)
3060 << ExprKind << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00003061 return false;
3062 }
Mike Stump1eb44332009-09-09 15:08:12 +00003063
Chris Lattner1efaa952009-04-24 00:30:45 +00003064 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00003065 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003066 << ExprKind << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00003067 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003068
Chris Lattner1efaa952009-04-24 00:30:45 +00003069 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCallc12c5bb2010-05-15 11:32:37 +00003070 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003071 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003072 << exprType << (ExprKind == UETT_SizeOf)
3073 << ExprRange;
Chris Lattner5cb10d32009-04-24 22:30:50 +00003074 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00003075 }
Mike Stump1eb44332009-09-09 15:08:12 +00003076
Chris Lattner1efaa952009-04-24 00:30:45 +00003077 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00003078}
3079
John McCall2a984ca2010-10-12 00:20:44 +00003080static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
3081 SourceRange ExprRange) {
Chris Lattner31e21e02009-01-24 20:17:12 +00003082 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00003083
Mike Stump1eb44332009-09-09 15:08:12 +00003084 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00003085 if (isa<DeclRefExpr>(E))
3086 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00003087
3088 // Cannot know anything else if the expression is dependent.
3089 if (E->isTypeDependent())
3090 return false;
3091
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003092 if (E->getBitField()) {
John McCall2a984ca2010-10-12 00:20:44 +00003093 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003094 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00003095 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003096
3097 // Alignment of a field access is always okay, so long as it isn't a
3098 // bit-field.
3099 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00003100 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003101 return false;
3102
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003103 return S.CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
3104 UETT_AlignOf);
3105}
3106
3107bool Sema::CheckVecStepExpr(Expr *E, SourceLocation OpLoc,
3108 SourceRange ExprRange) {
3109 E = E->IgnoreParens();
3110
3111 // Cannot know anything else if the expression is dependent.
3112 if (E->isTypeDependent())
3113 return false;
3114
3115 return CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
3116 UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00003117}
3118
Douglas Gregorba498172009-03-13 21:01:28 +00003119/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003120ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003121Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3122 SourceLocation OpLoc,
3123 UnaryExprOrTypeTrait ExprKind,
3124 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00003125 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00003126 return ExprError();
3127
John McCalla93c9342009-12-07 02:54:59 +00003128 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00003129
Douglas Gregorba498172009-03-13 21:01:28 +00003130 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003131 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00003132 return ExprError();
3133
3134 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003135 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3136 Context.getSizeType(),
3137 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003138}
3139
3140/// \brief Build a sizeof or alignof expression given an expression
3141/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00003142ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003143Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3144 UnaryExprOrTypeTrait ExprKind,
3145 SourceRange R) {
Douglas Gregorba498172009-03-13 21:01:28 +00003146 // Verify that the operand is valid.
3147 bool isInvalid = false;
3148 if (E->isTypeDependent()) {
3149 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003150 } else if (ExprKind == UETT_AlignOf) {
John McCall2a984ca2010-10-12 00:20:44 +00003151 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003152 } else if (ExprKind == UETT_VecStep) {
3153 isInvalid = CheckVecStepExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003154 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00003155 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
3156 isInvalid = true;
John McCall2cd11fe2010-10-12 02:09:17 +00003157 } else if (E->getType()->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00003158 ExprResult PE = CheckPlaceholderExpr(E);
John McCall2cd11fe2010-10-12 02:09:17 +00003159 if (PE.isInvalid()) return ExprError();
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003160 return CreateUnaryExprOrTypeTraitExpr(PE.take(), OpLoc, ExprKind, R);
Douglas Gregorba498172009-03-13 21:01:28 +00003161 } else {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003162 isInvalid = CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, R,
3163 UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00003164 }
3165
3166 if (isInvalid)
3167 return ExprError();
3168
3169 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003170 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, E,
3171 Context.getSizeType(),
3172 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00003173}
3174
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003175/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3176/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00003177/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00003178ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003179Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3180 UnaryExprOrTypeTrait ExprKind, bool isType,
3181 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003182 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003183 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003184
Sebastian Redl05189992008-11-11 17:56:53 +00003185 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00003186 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00003187 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003188 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00003189 }
Sebastian Redl05189992008-11-11 17:56:53 +00003190
Douglas Gregorba498172009-03-13 21:01:28 +00003191 Expr *ArgEx = (Expr *)TyOrEx;
John McCall60d7b3a2010-08-24 06:29:42 +00003192 ExprResult Result
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003193 = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind,
3194 ArgEx->getSourceRange());
Douglas Gregorba498172009-03-13 21:01:28 +00003195
Douglas Gregorba498172009-03-13 21:01:28 +00003196 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00003197}
3198
John Wiegley429bb272011-04-08 18:41:53 +00003199static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall09431682010-11-18 19:01:18 +00003200 bool isReal) {
John Wiegley429bb272011-04-08 18:41:53 +00003201 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00003202 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003203
John McCallf6a16482010-12-04 03:47:34 +00003204 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00003205 if (V.get()->getObjectKind() != OK_Ordinary) {
3206 V = S.DefaultLvalueConversion(V.take());
3207 if (V.isInvalid())
3208 return QualType();
3209 }
John McCallf6a16482010-12-04 03:47:34 +00003210
Chris Lattnercc26ed72007-08-26 05:39:26 +00003211 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00003212 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00003213 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00003214
Chris Lattnercc26ed72007-08-26 05:39:26 +00003215 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00003216 if (V.get()->getType()->isArithmeticType())
3217 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003218
John McCall2cd11fe2010-10-12 02:09:17 +00003219 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00003220 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00003221 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00003222 if (PR.get() != V.get()) {
3223 V = move(PR);
John McCall09431682010-11-18 19:01:18 +00003224 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall2cd11fe2010-10-12 02:09:17 +00003225 }
3226
Chris Lattnercc26ed72007-08-26 05:39:26 +00003227 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00003228 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattnerba27e2a2009-02-17 08:12:06 +00003229 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00003230 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003231}
3232
3233
Reid Spencer5f016e22007-07-11 17:01:13 +00003234
John McCall60d7b3a2010-08-24 06:29:42 +00003235ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003236Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003237 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003238 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003239 switch (Kind) {
3240 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003241 case tok::plusplus: Opc = UO_PostInc; break;
3242 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003243 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003244
John McCall9ae2f072010-08-23 23:25:46 +00003245 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003246}
3247
John McCall09431682010-11-18 19:01:18 +00003248/// Expressions of certain arbitrary types are forbidden by C from
3249/// having l-value type. These are:
3250/// - 'void', but not qualified void
3251/// - function types
3252///
3253/// The exact rule here is C99 6.3.2.1:
3254/// An lvalue is an expression with an object type or an incomplete
3255/// type other than void.
3256static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
3257 return ((T->isVoidType() && !T.hasQualifiers()) ||
3258 T->isFunctionType());
3259}
3260
John McCall60d7b3a2010-08-24 06:29:42 +00003261ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003262Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3263 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003264 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003265 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003266 if (Result.isInvalid()) return ExprError();
3267 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003268
John McCall9ae2f072010-08-23 23:25:46 +00003269 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003270
Douglas Gregor337c6b92008-11-19 17:17:41 +00003271 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003272 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003273 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003274 Context.DependentTy,
3275 VK_LValue, OK_Ordinary,
3276 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003277 }
3278
Mike Stump1eb44332009-09-09 15:08:12 +00003279 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003280 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003281 LHSExp->getType()->isEnumeralType() ||
3282 RHSExp->getType()->isRecordType() ||
3283 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00003284 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003285 }
3286
John McCall9ae2f072010-08-23 23:25:46 +00003287 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003288}
3289
3290
John McCall60d7b3a2010-08-24 06:29:42 +00003291ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003292Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3293 Expr *Idx, SourceLocation RLoc) {
3294 Expr *LHSExp = Base;
3295 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003296
Chris Lattner12d9ff62007-07-16 00:14:47 +00003297 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003298 if (!LHSExp->getType()->getAs<VectorType>()) {
3299 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3300 if (Result.isInvalid())
3301 return ExprError();
3302 LHSExp = Result.take();
3303 }
3304 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3305 if (Result.isInvalid())
3306 return ExprError();
3307 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003308
Chris Lattner12d9ff62007-07-16 00:14:47 +00003309 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003310 ExprValueKind VK = VK_LValue;
3311 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003312
Reid Spencer5f016e22007-07-11 17:01:13 +00003313 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003314 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003315 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003316 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003317 Expr *BaseExpr, *IndexExpr;
3318 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003319 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3320 BaseExpr = LHSExp;
3321 IndexExpr = RHSExp;
3322 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003323 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003324 BaseExpr = LHSExp;
3325 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003326 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003327 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00003328 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00003329 BaseExpr = RHSExp;
3330 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003331 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003332 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003333 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003334 BaseExpr = LHSExp;
3335 IndexExpr = RHSExp;
3336 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003337 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003338 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003339 // Handle the uncommon case of "123[Ptr]".
3340 BaseExpr = RHSExp;
3341 IndexExpr = LHSExp;
3342 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003343 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003344 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003345 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003346 VK = LHSExp->getValueKind();
3347 if (VK != VK_RValue)
3348 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003349
Chris Lattner12d9ff62007-07-16 00:14:47 +00003350 // FIXME: need to deal with const...
3351 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003352 } else if (LHSTy->isArrayType()) {
3353 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003354 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003355 // wasn't promoted because of the C90 rule that doesn't
3356 // allow promoting non-lvalue arrays. Warn, then
3357 // force the promotion here.
3358 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3359 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003360 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3361 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003362 LHSTy = LHSExp->getType();
3363
3364 BaseExpr = LHSExp;
3365 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003366 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003367 } else if (RHSTy->isArrayType()) {
3368 // Same as previous, except for 123[f().a] case
3369 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3370 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003371 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3372 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003373 RHSTy = RHSExp->getType();
3374
3375 BaseExpr = RHSExp;
3376 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003377 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003378 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003379 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3380 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003381 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003382 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003383 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003384 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3385 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003386
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003387 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003388 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3389 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003390 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3391
Douglas Gregore7450f52009-03-24 19:52:54 +00003392 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003393 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3394 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003395 // incomplete types are not object types.
3396 if (ResultType->isFunctionType()) {
3397 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3398 << ResultType << BaseExpr->getSourceRange();
3399 return ExprError();
3400 }
Mike Stump1eb44332009-09-09 15:08:12 +00003401
Abramo Bagnara46358452010-09-13 06:50:07 +00003402 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3403 // GNU extension: subscripting on pointer to void
3404 Diag(LLoc, diag::ext_gnu_void_ptr)
3405 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003406
3407 // C forbids expressions of unqualified void type from being l-values.
3408 // See IsCForbiddenLValueType.
3409 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003410 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003411 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003412 PDiag(diag::err_subscript_incomplete_type)
3413 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003414 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003415
Chris Lattner1efaa952009-04-24 00:30:45 +00003416 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003417 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003418 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3419 << ResultType << BaseExpr->getSourceRange();
3420 return ExprError();
3421 }
Mike Stump1eb44332009-09-09 15:08:12 +00003422
John McCall09431682010-11-18 19:01:18 +00003423 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3424 !IsCForbiddenLValueType(Context, ResultType));
3425
Mike Stumpeed9cac2009-02-19 03:04:26 +00003426 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003427 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003428}
3429
John McCall09431682010-11-18 19:01:18 +00003430/// Check an ext-vector component access expression.
3431///
3432/// VK should be set in advance to the value kind of the base
3433/// expression.
3434static QualType
3435CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3436 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003437 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00003438 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3439 // see FIXME there.
3440 //
3441 // FIXME: This logic can be greatly simplified by splitting it along
3442 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00003443 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00003444
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003445 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00003446 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003447
Mike Stumpeed9cac2009-02-19 03:04:26 +00003448 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00003449 // special names that indicate a subset of exactly half the elements are
3450 // to be selected.
3451 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003452
Nate Begeman353417a2009-01-18 01:47:54 +00003453 // This flag determines whether or not CompName has an 's' char prefix,
3454 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00003455 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00003456
John McCall09431682010-11-18 19:01:18 +00003457 bool HasRepeated = false;
3458 bool HasIndex[16] = {};
3459
3460 int Idx;
3461
Nate Begeman8a997642008-05-09 06:41:27 +00003462 // Check that we've found one of the special components, or that the component
3463 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003464 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00003465 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3466 HalvingSwizzle = true;
John McCall09431682010-11-18 19:01:18 +00003467 } else if (!HexSwizzle &&
3468 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3469 do {
3470 if (HasIndex[Idx]) HasRepeated = true;
3471 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003472 compStr++;
John McCall09431682010-11-18 19:01:18 +00003473 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3474 } else {
3475 if (HexSwizzle) compStr++;
3476 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3477 if (HasIndex[Idx]) HasRepeated = true;
3478 HasIndex[Idx] = true;
Chris Lattner88dca042007-08-02 22:33:49 +00003479 compStr++;
John McCall09431682010-11-18 19:01:18 +00003480 }
Chris Lattner88dca042007-08-02 22:33:49 +00003481 }
Nate Begeman353417a2009-01-18 01:47:54 +00003482
Mike Stumpeed9cac2009-02-19 03:04:26 +00003483 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003484 // We didn't get to the end of the string. This means the component names
3485 // didn't come from the same set *or* we encountered an illegal name.
John McCall09431682010-11-18 19:01:18 +00003486 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00003487 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003488 return QualType();
3489 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003490
Nate Begeman353417a2009-01-18 01:47:54 +00003491 // Ensure no component accessor exceeds the width of the vector type it
3492 // operates on.
3493 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00003494 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00003495
3496 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003497 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00003498
3499 while (*compStr) {
3500 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall09431682010-11-18 19:01:18 +00003501 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begeman353417a2009-01-18 01:47:54 +00003502 << baseType << SourceRange(CompLoc);
3503 return QualType();
3504 }
3505 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003506 }
Nate Begeman8a997642008-05-09 06:41:27 +00003507
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003508 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003509 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003510 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00003511 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00003512 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00003513 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00003514 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00003515 if (HexSwizzle)
3516 CompSize--;
3517
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003518 if (CompSize == 1)
3519 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003520
John McCall09431682010-11-18 19:01:18 +00003521 if (HasRepeated) VK = VK_RValue;
3522
3523 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003524 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00003525 // diagostics look bad. We want extended vector types to appear built-in.
John McCall09431682010-11-18 19:01:18 +00003526 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3527 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3528 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00003529 }
3530 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00003531}
3532
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003533static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00003534 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003535 const Selector &Sel,
3536 ASTContext &Context) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003537 if (Member)
3538 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3539 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003540 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003541 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00003542
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003543 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3544 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003545 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3546 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003547 return D;
3548 }
3549 return 0;
3550}
3551
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003552static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3553 IdentifierInfo *Member,
3554 const Selector &Sel,
3555 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003556 // Check protocols on qualified interfaces.
3557 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003558 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003559 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003560 if (Member)
3561 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3562 GDecl = PD;
3563 break;
3564 }
3565 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003566 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003567 GDecl = OMD;
3568 break;
3569 }
3570 }
3571 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003572 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003573 E = QIdTy->qual_end(); I != E; ++I) {
3574 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003575 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3576 Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00003577 if (GDecl)
3578 return GDecl;
3579 }
3580 }
3581 return GDecl;
3582}
Chris Lattner76a642f2009-02-15 22:43:40 +00003583
John McCall60d7b3a2010-08-24 06:29:42 +00003584ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003585Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCallaa81e162009-12-01 22:10:20 +00003586 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00003587 const CXXScopeSpec &SS,
3588 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003589 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003590 const TemplateArgumentListInfo *TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00003591 // Even in dependent contexts, try to diagnose base expressions with
3592 // obviously wrong types, e.g.:
3593 //
3594 // T* t;
3595 // t.f;
3596 //
3597 // In Obj-C++, however, the above expression is valid, since it could be
3598 // accessing the 'f' property if T is an Obj-C interface. The extra check
3599 // allows this, while still reporting an error if T is a struct pointer.
3600 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00003601 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00003602 if (PT && (!getLangOptions().ObjC1 ||
3603 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00003604 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnara25777432010-08-11 22:01:17 +00003605 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00003606 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00003607 return ExprError();
3608 }
3609 }
3610
Abramo Bagnara25777432010-08-11 22:01:17 +00003611 assert(BaseType->isDependentType() ||
3612 NameInfo.getName().isDependentName() ||
Douglas Gregor01e56ae2010-04-12 20:54:26 +00003613 isDependentScopeSpecifier(SS));
John McCall129e2df2009-11-30 22:42:35 +00003614
3615 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3616 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00003617 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003618 IsArrow, OpLoc,
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003619 SS.getWithLocInContext(Context),
John McCall129e2df2009-11-30 22:42:35 +00003620 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003621 NameInfo, TemplateArgs));
John McCall129e2df2009-11-30 22:42:35 +00003622}
3623
3624/// We know that the given qualified member reference points only to
3625/// declarations which do not belong to the static type of the base
3626/// expression. Diagnose the problem.
3627static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3628 Expr *BaseExpr,
3629 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003630 const CXXScopeSpec &SS,
John McCall5808ce42011-02-03 08:15:49 +00003631 NamedDecl *rep,
3632 const DeclarationNameInfo &nameInfo) {
John McCall2f841ba2009-12-02 03:53:29 +00003633 // If this is an implicit member access, use a different set of
3634 // diagnostics.
3635 if (!BaseExpr)
John McCall5808ce42011-02-03 08:15:49 +00003636 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall129e2df2009-11-30 22:42:35 +00003637
John McCall5808ce42011-02-03 08:15:49 +00003638 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3639 << SS.getRange() << rep << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00003640}
3641
3642// Check whether the declarations we found through a nested-name
3643// specifier in a member expression are actually members of the base
3644// type. The restriction here is:
3645//
3646// C++ [expr.ref]p2:
3647// ... In these cases, the id-expression shall name a
3648// member of the class or of one of its base classes.
3649//
3650// So it's perfectly legitimate for the nested-name specifier to name
3651// an unrelated class, and for us to find an overload set including
3652// decls from classes which are not superclasses, as long as the decl
3653// we actually pick through overload resolution is from a superclass.
3654bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3655 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00003656 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003657 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00003658 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3659 if (!BaseRT) {
3660 // We can't check this yet because the base type is still
3661 // dependent.
3662 assert(BaseType->isDependentType());
3663 return false;
3664 }
3665 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00003666
3667 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00003668 // If this is an implicit member reference and we find a
3669 // non-instance member, it's not an error.
John McCall161755a2010-04-06 21:38:20 +00003670 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCallaa81e162009-12-01 22:10:20 +00003671 return false;
John McCall129e2df2009-11-30 22:42:35 +00003672
John McCallaa81e162009-12-01 22:10:20 +00003673 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman02463762010-07-27 20:51:02 +00003674 DeclContext *DC = (*I)->getDeclContext();
3675 while (DC->isTransparentContext())
3676 DC = DC->getParent();
John McCallaa81e162009-12-01 22:10:20 +00003677
Douglas Gregor9d4bb942010-07-28 22:27:52 +00003678 if (!DC->isRecord())
3679 continue;
3680
John McCallaa81e162009-12-01 22:10:20 +00003681 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman02463762010-07-27 20:51:02 +00003682 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCallaa81e162009-12-01 22:10:20 +00003683
3684 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3685 return false;
3686 }
3687
John McCall5808ce42011-02-03 08:15:49 +00003688 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3689 R.getRepresentativeDecl(),
3690 R.getLookupNameInfo());
John McCallaa81e162009-12-01 22:10:20 +00003691 return true;
3692}
3693
3694static bool
3695LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3696 SourceRange BaseRange, const RecordType *RTy,
John McCallad00b772010-06-16 08:42:20 +00003697 SourceLocation OpLoc, CXXScopeSpec &SS,
3698 bool HasTemplateArgs) {
John McCallaa81e162009-12-01 22:10:20 +00003699 RecordDecl *RDecl = RTy->getDecl();
3700 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003701 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCallaa81e162009-12-01 22:10:20 +00003702 << BaseRange))
3703 return true;
3704
John McCallad00b772010-06-16 08:42:20 +00003705 if (HasTemplateArgs) {
3706 // LookupTemplateName doesn't expect these both to exist simultaneously.
3707 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3708
3709 bool MOUS;
3710 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3711 return false;
3712 }
3713
John McCallaa81e162009-12-01 22:10:20 +00003714 DeclContext *DC = RDecl;
3715 if (SS.isSet()) {
3716 // If the member name was a qualified-id, look into the
3717 // nested-name-specifier.
3718 DC = SemaRef.computeDeclContext(SS, false);
3719
John McCall77bb1aa2010-05-01 00:40:08 +00003720 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCall2f841ba2009-12-02 03:53:29 +00003721 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3722 << SS.getRange() << DC;
3723 return true;
3724 }
3725
John McCallaa81e162009-12-01 22:10:20 +00003726 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003727
John McCallaa81e162009-12-01 22:10:20 +00003728 if (!isa<TypeDecl>(DC)) {
3729 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3730 << DC << SS.getRange();
3731 return true;
John McCall129e2df2009-11-30 22:42:35 +00003732 }
3733 }
3734
John McCallaa81e162009-12-01 22:10:20 +00003735 // The record definition is complete, now look up the member.
3736 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00003737
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003738 if (!R.empty())
3739 return false;
3740
3741 // We didn't find anything with the given name, so try to correct
3742 // for typos.
3743 DeclarationName Name = R.getLookupName();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003744 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00003745 !R.empty() &&
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003746 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3747 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3748 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00003749 << FixItHint::CreateReplacement(R.getNameLoc(),
3750 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003751 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3752 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3753 << ND->getDeclName();
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003754 return false;
3755 } else {
3756 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003757 R.setLookupName(Name);
Douglas Gregor2dcc0112009-12-31 07:42:17 +00003758 }
3759
John McCall129e2df2009-11-30 22:42:35 +00003760 return false;
3761}
3762
John McCall60d7b3a2010-08-24 06:29:42 +00003763ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003764Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003765 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003766 CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00003767 NamedDecl *FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003768 const DeclarationNameInfo &NameInfo,
John McCall129e2df2009-11-30 22:42:35 +00003769 const TemplateArgumentListInfo *TemplateArgs) {
John McCall2f841ba2009-12-02 03:53:29 +00003770 if (BaseType->isDependentType() ||
3771 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall9ae2f072010-08-23 23:25:46 +00003772 return ActOnDependentMemberExpr(Base, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00003773 IsArrow, OpLoc,
3774 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00003775 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003776
Abramo Bagnara25777432010-08-11 22:01:17 +00003777 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00003778
John McCallaa81e162009-12-01 22:10:20 +00003779 // Implicit member accesses.
3780 if (!Base) {
3781 QualType RecordTy = BaseType;
3782 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3783 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3784 RecordTy->getAs<RecordType>(),
John McCallad00b772010-06-16 08:42:20 +00003785 OpLoc, SS, TemplateArgs != 0))
John McCallaa81e162009-12-01 22:10:20 +00003786 return ExprError();
3787
3788 // Explicit member accesses.
3789 } else {
John Wiegley429bb272011-04-08 18:41:53 +00003790 ExprResult BaseResult = Owned(Base);
John McCall60d7b3a2010-08-24 06:29:42 +00003791 ExprResult Result =
John Wiegley429bb272011-04-08 18:41:53 +00003792 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCalld226f652010-08-21 09:40:31 +00003793 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCallaa81e162009-12-01 22:10:20 +00003794
John Wiegley429bb272011-04-08 18:41:53 +00003795 if (BaseResult.isInvalid())
3796 return ExprError();
3797 Base = BaseResult.take();
3798
John McCallaa81e162009-12-01 22:10:20 +00003799 if (Result.isInvalid()) {
3800 Owned(Base);
3801 return ExprError();
3802 }
3803
3804 if (Result.get())
3805 return move(Result);
Sebastian Redlf3e63372010-05-07 09:25:11 +00003806
3807 // LookupMemberExpr can modify Base, and thus change BaseType
3808 BaseType = Base->getType();
John McCall129e2df2009-11-30 22:42:35 +00003809 }
3810
John McCall9ae2f072010-08-23 23:25:46 +00003811 return BuildMemberReferenceExpr(Base, BaseType,
John McCallc2233c52010-01-15 08:34:02 +00003812 OpLoc, IsArrow, SS, FirstQualifierInScope,
3813 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003814}
3815
John McCall60d7b3a2010-08-24 06:29:42 +00003816ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003817Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCallaa81e162009-12-01 22:10:20 +00003818 SourceLocation OpLoc, bool IsArrow,
3819 const CXXScopeSpec &SS,
John McCallc2233c52010-01-15 08:34:02 +00003820 NamedDecl *FirstQualifierInScope,
John McCall129e2df2009-11-30 22:42:35 +00003821 LookupResult &R,
Douglas Gregor06a9f362010-05-01 20:49:11 +00003822 const TemplateArgumentListInfo *TemplateArgs,
3823 bool SuppressQualifierCheck) {
John McCallaa81e162009-12-01 22:10:20 +00003824 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00003825 if (IsArrow) {
3826 assert(BaseType->isPointerType());
3827 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3828 }
John McCall161755a2010-04-06 21:38:20 +00003829 R.setBaseObjectType(BaseType);
John McCall129e2df2009-11-30 22:42:35 +00003830
Abramo Bagnara25777432010-08-11 22:01:17 +00003831 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3832 DeclarationName MemberName = MemberNameInfo.getName();
3833 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall129e2df2009-11-30 22:42:35 +00003834
3835 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00003836 return ExprError();
3837
John McCall129e2df2009-11-30 22:42:35 +00003838 if (R.empty()) {
3839 // Rederive where we looked up.
3840 DeclContext *DC = (SS.isSet()
3841 ? computeDeclContext(SS, false)
3842 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00003843
John McCall129e2df2009-11-30 22:42:35 +00003844 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00003845 << MemberName << DC
3846 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00003847 return ExprError();
3848 }
3849
John McCallc2233c52010-01-15 08:34:02 +00003850 // Diagnose lookups that find only declarations from a non-base
3851 // type. This is possible for either qualified lookups (which may
3852 // have been qualified with an unrelated type) or implicit member
3853 // expressions (which were found with unqualified lookup and thus
3854 // may have come from an enclosing scope). Note that it's okay for
3855 // lookup to find declarations from a non-base type as long as those
3856 // aren't the ones picked by overload resolution.
3857 if ((SS.isSet() || !BaseExpr ||
3858 (isa<CXXThisExpr>(BaseExpr) &&
3859 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00003860 !SuppressQualifierCheck &&
John McCallc2233c52010-01-15 08:34:02 +00003861 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00003862 return ExprError();
3863
3864 // Construct an unresolved result if we in fact got an unresolved
3865 // result.
3866 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallc373d482010-01-27 01:50:18 +00003867 // Suppress any lookup-related diagnostics; we'll do these when we
3868 // pick a member.
3869 R.suppressDiagnostics();
3870
John McCall129e2df2009-11-30 22:42:35 +00003871 UnresolvedMemberExpr *MemExpr
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00003872 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00003873 BaseExpr, BaseExprType,
3874 IsArrow, OpLoc,
Douglas Gregor4c9be892011-02-28 20:01:57 +00003875 SS.getWithLocInContext(Context),
Abramo Bagnara25777432010-08-11 22:01:17 +00003876 MemberNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00003877 TemplateArgs, R.begin(), R.end());
John McCall129e2df2009-11-30 22:42:35 +00003878
3879 return Owned(MemExpr);
3880 }
3881
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003882 assert(R.isSingleResult());
John McCall161755a2010-04-06 21:38:20 +00003883 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall129e2df2009-11-30 22:42:35 +00003884 NamedDecl *MemberDecl = R.getFoundDecl();
3885
3886 // FIXME: diagnose the presence of template arguments now.
3887
3888 // If the decl being referenced had an error, return an error for this
3889 // sub-expr without emitting another error, in order to avoid cascading
3890 // error cases.
3891 if (MemberDecl->isInvalidDecl())
3892 return ExprError();
3893
John McCallaa81e162009-12-01 22:10:20 +00003894 // Handle the implicit-member-access case.
3895 if (!BaseExpr) {
3896 // If this is not an instance member, convert to a non-member access.
John McCall161755a2010-04-06 21:38:20 +00003897 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnara25777432010-08-11 22:01:17 +00003898 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCallaa81e162009-12-01 22:10:20 +00003899
Douglas Gregor828a1972010-01-07 23:12:05 +00003900 SourceLocation Loc = R.getNameLoc();
3901 if (SS.getRange().isValid())
3902 Loc = SS.getRange().getBegin();
3903 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCallaa81e162009-12-01 22:10:20 +00003904 }
3905
John McCall129e2df2009-11-30 22:42:35 +00003906 bool ShouldCheckUse = true;
3907 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3908 // Don't diagnose the use of a virtual member function unless it's
3909 // explicitly qualified.
3910 if (MD->isVirtual() && !SS.isSet())
3911 ShouldCheckUse = false;
3912 }
3913
3914 // Check the use of this member.
3915 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3916 Owned(BaseExpr);
3917 return ExprError();
3918 }
3919
John McCallf6a16482010-12-04 03:47:34 +00003920 // Perform a property load on the base regardless of whether we
3921 // actually need it for the declaration.
John Wiegley429bb272011-04-08 18:41:53 +00003922 if (BaseExpr->getObjectKind() == OK_ObjCProperty) {
3923 ExprResult Result = ConvertPropertyForRValue(BaseExpr);
3924 if (Result.isInvalid())
3925 return ExprError();
3926 BaseExpr = Result.take();
3927 }
John McCallf6a16482010-12-04 03:47:34 +00003928
John McCalldfa1edb2010-11-23 20:48:44 +00003929 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3930 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3931 SS, FD, FoundDecl, MemberNameInfo);
John McCall129e2df2009-11-30 22:42:35 +00003932
Francois Pichet87c2e122010-11-21 06:08:52 +00003933 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3934 // We may have found a field within an anonymous union or struct
3935 // (C++ [class.union]).
John McCall5808ce42011-02-03 08:15:49 +00003936 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCallf6a16482010-12-04 03:47:34 +00003937 BaseExpr, OpLoc);
Francois Pichet87c2e122010-11-21 06:08:52 +00003938
John McCall129e2df2009-11-30 22:42:35 +00003939 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3940 MarkDeclarationReferenced(MemberLoc, Var);
3941 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003942 Var, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003943 Var->getType().getNonReferenceType(),
John McCall09431682010-11-18 19:01:18 +00003944 VK_LValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003945 }
3946
John McCallf89e55a2010-11-18 06:31:45 +00003947 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall864c0412011-04-26 20:42:42 +00003948 ExprValueKind valueKind;
3949 QualType type;
3950 if (MemberFn->isInstance()) {
3951 valueKind = VK_RValue;
3952 type = Context.BoundMemberTy;
3953 } else {
3954 valueKind = VK_LValue;
3955 type = MemberFn->getType();
3956 }
3957
John McCall129e2df2009-11-30 22:42:35 +00003958 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3959 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003960 MemberFn, FoundDecl, MemberNameInfo,
John McCall864c0412011-04-26 20:42:42 +00003961 type, valueKind, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003962 }
John McCallf89e55a2010-11-18 06:31:45 +00003963 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall129e2df2009-11-30 22:42:35 +00003964
3965 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3966 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3967 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00003968 Enum, FoundDecl, MemberNameInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003969 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall129e2df2009-11-30 22:42:35 +00003970 }
3971
3972 Owned(BaseExpr);
3973
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003974 // We found something that we didn't expect. Complain.
John McCall129e2df2009-11-30 22:42:35 +00003975 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnara25777432010-08-11 22:01:17 +00003976 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003977 << MemberName << BaseType << int(IsArrow);
3978 else
3979 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3980 << MemberName << BaseType << int(IsArrow);
John McCall129e2df2009-11-30 22:42:35 +00003981
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003982 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3983 << MemberName;
Douglas Gregor2b147f02010-04-25 21:15:30 +00003984 R.suppressDiagnostics();
Douglas Gregorb0fd4832010-04-25 20:55:08 +00003985 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00003986}
3987
John McCall028d3972010-12-15 16:46:44 +00003988/// Given that normal member access failed on the given expression,
3989/// and given that the expression's type involves builtin-id or
3990/// builtin-Class, decide whether substituting in the redefinition
3991/// types would be profitable. The redefinition type is whatever
3992/// this translation unit tried to typedef to id/Class; we store
3993/// it to the side and then re-use it in places like this.
John Wiegley429bb272011-04-08 18:41:53 +00003994static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
John McCall028d3972010-12-15 16:46:44 +00003995 const ObjCObjectPointerType *opty
John Wiegley429bb272011-04-08 18:41:53 +00003996 = base.get()->getType()->getAs<ObjCObjectPointerType>();
John McCall028d3972010-12-15 16:46:44 +00003997 if (!opty) return false;
3998
3999 const ObjCObjectType *ty = opty->getObjectType();
4000
4001 QualType redef;
4002 if (ty->isObjCId()) {
4003 redef = S.Context.ObjCIdRedefinitionType;
4004 } else if (ty->isObjCClass()) {
4005 redef = S.Context.ObjCClassRedefinitionType;
4006 } else {
4007 return false;
4008 }
4009
4010 // Do the substitution as long as the redefinition type isn't just a
4011 // possibly-qualified pointer to builtin-id or builtin-Class again.
4012 opty = redef->getAs<ObjCObjectPointerType>();
4013 if (opty && !opty->getObjectType()->getInterface() != 0)
4014 return false;
4015
John Wiegley429bb272011-04-08 18:41:53 +00004016 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
John McCall028d3972010-12-15 16:46:44 +00004017 return true;
4018}
4019
John McCall129e2df2009-11-30 22:42:35 +00004020/// Look up the given member of the given non-type-dependent
4021/// expression. This can return in one of two ways:
4022/// * If it returns a sentinel null-but-valid result, the caller will
4023/// assume that lookup was performed and the results written into
4024/// the provided structure. It will take over from there.
4025/// * Otherwise, the returned expression will be produced in place of
4026/// an ordinary member expression.
4027///
4028/// The ObjCImpDecl bit is a gross hack that will need to be properly
4029/// fixed for ObjC++.
John McCall60d7b3a2010-08-24 06:29:42 +00004030ExprResult
John Wiegley429bb272011-04-08 18:41:53 +00004031Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00004032 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004033 CXXScopeSpec &SS,
John McCalld226f652010-08-21 09:40:31 +00004034 Decl *ObjCImpDecl, bool HasTemplateArgs) {
John Wiegley429bb272011-04-08 18:41:53 +00004035 assert(BaseExpr.get() && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00004036
Steve Naroff3cc4af82007-12-16 21:42:28 +00004037 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00004038 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
Sebastian Redl0eb23302009-01-19 00:08:26 +00004039
John Wiegley429bb272011-04-08 18:41:53 +00004040 if (IsArrow) {
4041 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4042 if (BaseExpr.isInvalid())
4043 return ExprError();
4044 }
4045
4046 QualType BaseType = BaseExpr.get()->getType();
John McCall129e2df2009-11-30 22:42:35 +00004047 assert(!BaseType->isDependentType());
4048
4049 DeclarationName MemberName = R.getLookupName();
4050 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00004051
John McCall028d3972010-12-15 16:46:44 +00004052 // For later type-checking purposes, turn arrow accesses into dot
4053 // accesses. The only access type we support that doesn't follow
4054 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
4055 // and those never use arrows, so this is unaffected.
4056 if (IsArrow) {
4057 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4058 BaseType = Ptr->getPointeeType();
4059 else if (const ObjCObjectPointerType *Ptr
4060 = BaseType->getAs<ObjCObjectPointerType>())
4061 BaseType = Ptr->getPointeeType();
4062 else if (BaseType->isRecordType()) {
4063 // Recover from arrow accesses to records, e.g.:
4064 // struct MyRecord foo;
4065 // foo->bar
4066 // This is actually well-formed in C++ if MyRecord has an
4067 // overloaded operator->, but that should have been dealt with
4068 // by now.
4069 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley429bb272011-04-08 18:41:53 +00004070 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
John McCall028d3972010-12-15 16:46:44 +00004071 << FixItHint::CreateReplacement(OpLoc, ".");
4072 IsArrow = false;
John McCall864c0412011-04-26 20:42:42 +00004073 } else if (BaseType == Context.BoundMemberTy) {
4074 goto fail;
John McCall028d3972010-12-15 16:46:44 +00004075 } else {
4076 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
John Wiegley429bb272011-04-08 18:41:53 +00004077 << BaseType << BaseExpr.get()->getSourceRange();
John McCall028d3972010-12-15 16:46:44 +00004078 return ExprError();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00004079 }
4080 }
4081
John McCall028d3972010-12-15 16:46:44 +00004082 // Handle field access to simple records.
4083 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John Wiegley429bb272011-04-08 18:41:53 +00004084 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
John McCall028d3972010-12-15 16:46:44 +00004085 RTy, OpLoc, SS, HasTemplateArgs))
4086 return ExprError();
4087
4088 // Returning valid-but-null is how we indicate to the caller that
4089 // the lookup result was filled in.
4090 return Owned((Expr*) 0);
David Chisnall0f436562009-08-17 16:35:33 +00004091 }
John McCall129e2df2009-11-30 22:42:35 +00004092
John McCall028d3972010-12-15 16:46:44 +00004093 // Handle ivar access to Objective-C objects.
4094 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004095 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall028d3972010-12-15 16:46:44 +00004096
4097 // There are three cases for the base type:
4098 // - builtin id (qualified or unqualified)
4099 // - builtin Class (qualified or unqualified)
4100 // - an interface
4101 ObjCInterfaceDecl *IDecl = OTy->getInterface();
4102 if (!IDecl) {
4103 // There's an implicit 'isa' ivar on all objects.
4104 // But we only actually find it this way on objects of type 'id',
4105 // apparently.
4106 if (OTy->isObjCId() && Member->isStr("isa"))
John Wiegley429bb272011-04-08 18:41:53 +00004107 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
John McCall028d3972010-12-15 16:46:44 +00004108 Context.getObjCClassType()));
4109
4110 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4111 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4112 ObjCImpDecl, HasTemplateArgs);
4113 goto fail;
4114 }
4115
4116 ObjCInterfaceDecl *ClassDeclared;
4117 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
4118
4119 if (!IV) {
4120 // Attempt to correct for typos in ivar names.
4121 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
4122 LookupMemberName);
4123 if (CorrectTypo(Res, 0, 0, IDecl, false,
4124 IsArrow ? CTC_ObjCIvarLookup
4125 : CTC_ObjCPropertyLookup) &&
4126 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
4127 Diag(R.getNameLoc(),
4128 diag::err_typecheck_member_reference_ivar_suggest)
4129 << IDecl->getDeclName() << MemberName << IV->getDeclName()
4130 << FixItHint::CreateReplacement(R.getNameLoc(),
4131 IV->getNameAsString());
4132 Diag(IV->getLocation(), diag::note_previous_decl)
4133 << IV->getDeclName();
4134 } else {
4135 Res.clear();
4136 Res.setLookupName(Member);
4137
4138 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
4139 << IDecl->getDeclName() << MemberName
John Wiegley429bb272011-04-08 18:41:53 +00004140 << BaseExpr.get()->getSourceRange();
John McCall028d3972010-12-15 16:46:44 +00004141 return ExprError();
4142 }
4143 }
4144
4145 // If the decl being referenced had an error, return an error for this
4146 // sub-expr without emitting another error, in order to avoid cascading
4147 // error cases.
4148 if (IV->isInvalidDecl())
4149 return ExprError();
4150
4151 // Check whether we can reference this field.
4152 if (DiagnoseUseOfDecl(IV, MemberLoc))
4153 return ExprError();
4154 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
4155 IV->getAccessControl() != ObjCIvarDecl::Package) {
4156 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
4157 if (ObjCMethodDecl *MD = getCurMethodDecl())
4158 ClassOfMethodDecl = MD->getClassInterface();
4159 else if (ObjCImpDecl && getCurFunctionDecl()) {
4160 // Case of a c-function declared inside an objc implementation.
4161 // FIXME: For a c-style function nested inside an objc implementation
4162 // class, there is no implementation context available, so we pass
4163 // down the context as argument to this routine. Ideally, this context
4164 // need be passed down in the AST node and somehow calculated from the
4165 // AST for a function decl.
4166 if (ObjCImplementationDecl *IMPD =
4167 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
4168 ClassOfMethodDecl = IMPD->getClassInterface();
4169 else if (ObjCCategoryImplDecl* CatImplClass =
4170 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
4171 ClassOfMethodDecl = CatImplClass->getClassInterface();
4172 }
4173
4174 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
4175 if (ClassDeclared != IDecl ||
4176 ClassOfMethodDecl != ClassDeclared)
4177 Diag(MemberLoc, diag::error_private_ivar_access)
4178 << IV->getDeclName();
4179 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
4180 // @protected
4181 Diag(MemberLoc, diag::error_protected_ivar_access)
4182 << IV->getDeclName();
4183 }
4184
4185 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
John Wiegley429bb272011-04-08 18:41:53 +00004186 MemberLoc, BaseExpr.take(),
John McCall028d3972010-12-15 16:46:44 +00004187 IsArrow));
4188 }
4189
4190 // Objective-C property access.
4191 const ObjCObjectPointerType *OPT;
4192 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
4193 // This actually uses the base as an r-value.
John Wiegley429bb272011-04-08 18:41:53 +00004194 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4195 if (BaseExpr.isInvalid())
4196 return ExprError();
4197
4198 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
John McCall028d3972010-12-15 16:46:44 +00004199
4200 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
4201
4202 const ObjCObjectType *OT = OPT->getObjectType();
4203
4204 // id, with and without qualifiers.
4205 if (OT->isObjCId()) {
4206 // Check protocols on qualified interfaces.
4207 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
4208 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
4209 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
4210 // Check the use of this declaration
4211 if (DiagnoseUseOfDecl(PD, MemberLoc))
4212 return ExprError();
4213
4214 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
4215 VK_LValue,
4216 OK_ObjCProperty,
4217 MemberLoc,
John Wiegley429bb272011-04-08 18:41:53 +00004218 BaseExpr.take()));
John McCall028d3972010-12-15 16:46:44 +00004219 }
4220
4221 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
4222 // Check the use of this method.
4223 if (DiagnoseUseOfDecl(OMD, MemberLoc))
4224 return ExprError();
4225 Selector SetterSel =
4226 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4227 PP.getSelectorTable(), Member);
4228 ObjCMethodDecl *SMD = 0;
4229 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
4230 SetterSel, Context))
4231 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
4232 QualType PType = OMD->getSendResultType();
4233
4234 ExprValueKind VK = VK_LValue;
4235 if (!getLangOptions().CPlusPlus &&
4236 IsCForbiddenLValueType(Context, PType))
4237 VK = VK_RValue;
4238 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4239
4240 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
4241 VK, OK,
John Wiegley429bb272011-04-08 18:41:53 +00004242 MemberLoc, BaseExpr.take()));
John McCall028d3972010-12-15 16:46:44 +00004243 }
4244 }
Fariborz Jahanian4eb7f692011-03-15 17:27:48 +00004245 // Use of id.member can only be for a property reference. Do not
4246 // use the 'id' redefinition in this case.
4247 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
John McCall028d3972010-12-15 16:46:44 +00004248 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4249 ObjCImpDecl, HasTemplateArgs);
4250
4251 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
4252 << MemberName << BaseType);
4253 }
4254
4255 // 'Class', unqualified only.
4256 if (OT->isObjCClass()) {
4257 // Only works in a method declaration (??!).
4258 ObjCMethodDecl *MD = getCurMethodDecl();
4259 if (!MD) {
4260 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4261 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4262 ObjCImpDecl, HasTemplateArgs);
4263
4264 goto fail;
4265 }
4266
4267 // Also must look for a getter name which uses property syntax.
4268 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004269 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4270 ObjCMethodDecl *Getter;
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004271 if ((Getter = IFace->lookupClassMethod(Sel))) {
4272 // Check the use of this method.
4273 if (DiagnoseUseOfDecl(Getter, MemberLoc))
4274 return ExprError();
John McCall028d3972010-12-15 16:46:44 +00004275 } else
Fariborz Jahanian74b27562010-12-03 23:37:08 +00004276 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004277 // If we found a getter then this may be a valid dot-reference, we
4278 // will look for the matching setter, in case it is needed.
4279 Selector SetterSel =
John McCall028d3972010-12-15 16:46:44 +00004280 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4281 PP.getSelectorTable(), Member);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004282 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
4283 if (!Setter) {
4284 // If this reference is in an @implementation, also check for 'private'
4285 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +00004286 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004287 }
4288 // Look through local category implementations associated with the class.
4289 if (!Setter)
4290 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004291
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004292 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
4293 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004294
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004295 if (Getter || Setter) {
4296 QualType PType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004297
John McCall09431682010-11-18 19:01:18 +00004298 ExprValueKind VK = VK_LValue;
4299 if (Getter) {
Douglas Gregor5291c3c2010-07-13 08:18:22 +00004300 PType = Getter->getSendResultType();
John McCall09431682010-11-18 19:01:18 +00004301 if (!getLangOptions().CPlusPlus &&
4302 IsCForbiddenLValueType(Context, PType))
4303 VK = VK_RValue;
4304 } else {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004305 // Get the expression type from Setter's incoming parameter.
4306 PType = (*(Setter->param_end() -1))->getType();
John McCall09431682010-11-18 19:01:18 +00004307 }
4308 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4309
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004310 // FIXME: we must check that the setter has property type.
John McCall12f78a62010-12-02 01:19:52 +00004311 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
4312 PType, VK, OK,
John Wiegley429bb272011-04-08 18:41:53 +00004313 MemberLoc, BaseExpr.take()));
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004314 }
John McCall028d3972010-12-15 16:46:44 +00004315
4316 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4317 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4318 ObjCImpDecl, HasTemplateArgs);
4319
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00004320 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall028d3972010-12-15 16:46:44 +00004321 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00004322 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004323
John McCall028d3972010-12-15 16:46:44 +00004324 // Normal property access.
John Wiegley429bb272011-04-08 18:41:53 +00004325 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), MemberName, MemberLoc,
John McCall028d3972010-12-15 16:46:44 +00004326 SourceLocation(), QualType(), false);
Steve Naroff14108da2009-07-10 23:34:53 +00004327 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004328
Chris Lattnerfb173ec2008-07-21 04:28:12 +00004329 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00004330 if (BaseType->isExtVectorType()) {
John McCall5e3c67b2010-12-15 04:42:30 +00004331 // FIXME: this expr should store IsArrow.
Anders Carlsson8f28f992009-08-26 18:25:21 +00004332 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John Wiegley429bb272011-04-08 18:41:53 +00004333 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
John McCall09431682010-11-18 19:01:18 +00004334 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
4335 Member, MemberLoc);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00004336 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00004337 return ExprError();
John McCall09431682010-11-18 19:01:18 +00004338
John Wiegley429bb272011-04-08 18:41:53 +00004339 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
John McCall09431682010-11-18 19:01:18 +00004340 *Member, MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00004341 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004342
John McCall028d3972010-12-15 16:46:44 +00004343 // Adjust builtin-sel to the appropriate redefinition type if that's
4344 // not just a pointer to builtin-sel again.
4345 if (IsArrow &&
4346 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
4347 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004348 BaseExpr = ImpCastExprToType(BaseExpr.take(), Context.ObjCSelRedefinitionType,
4349 CK_BitCast);
John McCall028d3972010-12-15 16:46:44 +00004350 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4351 ObjCImpDecl, HasTemplateArgs);
4352 }
4353
4354 // Failure cases.
4355 fail:
4356
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004357 // Recover from dot accesses to pointers, e.g.:
4358 // type *foo;
4359 // foo.bar
4360 // This is actually well-formed in two cases:
4361 // - 'type' is an Objective C type
4362 // - 'bar' is a pseudo-destructor name which happens to refer to
4363 // the appropriate pointer type
John McCall028d3972010-12-15 16:46:44 +00004364 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004365 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
4366 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
John McCall028d3972010-12-15 16:46:44 +00004367 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley429bb272011-04-08 18:41:53 +00004368 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004369 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall028d3972010-12-15 16:46:44 +00004370
4371 // Recurse as an -> access.
4372 IsArrow = true;
4373 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4374 ObjCImpDecl, HasTemplateArgs);
4375 }
John McCall028d3972010-12-15 16:46:44 +00004376 }
4377
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004378 // If the user is trying to apply -> or . to a function name, it's probably
4379 // because they forgot parentheses to call that function.
4380 bool TryCall = false;
4381 bool Overloaded = false;
4382 UnresolvedSet<8> AllOverloads;
John Wiegley429bb272011-04-08 18:41:53 +00004383 if (const OverloadExpr *Overloads = dyn_cast<OverloadExpr>(BaseExpr.get())) {
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004384 AllOverloads.append(Overloads->decls_begin(), Overloads->decls_end());
4385 TryCall = true;
4386 Overloaded = true;
John Wiegley429bb272011-04-08 18:41:53 +00004387 } else if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(BaseExpr.get())) {
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004388 if (FunctionDecl* Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
4389 AllOverloads.addDecl(Fun);
4390 TryCall = true;
4391 }
4392 }
John McCall028d3972010-12-15 16:46:44 +00004393
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004394 if (TryCall) {
4395 // Plunder the overload set for something that would make the member
4396 // expression valid.
4397 UnresolvedSet<4> ViableOverloads;
4398 bool HasViableZeroArgOverload = false;
4399 for (OverloadExpr::decls_iterator it = AllOverloads.begin(),
4400 DeclsEnd = AllOverloads.end(); it != DeclsEnd; ++it) {
Matt Beaumont-Gayfbe59942011-03-05 02:42:30 +00004401 // Our overload set may include TemplateDecls, which we'll ignore for the
4402 // purposes of determining whether we can issue a '()' fixit.
4403 if (const FunctionDecl *OverloadDecl = dyn_cast<FunctionDecl>(*it)) {
4404 QualType ResultTy = OverloadDecl->getResultType();
4405 if ((!IsArrow && ResultTy->isRecordType()) ||
4406 (IsArrow && ResultTy->isPointerType() &&
4407 ResultTy->getPointeeType()->isRecordType())) {
4408 ViableOverloads.addDecl(*it);
4409 if (OverloadDecl->getMinRequiredArguments() == 0) {
4410 HasViableZeroArgOverload = true;
4411 }
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004412 }
John McCall028d3972010-12-15 16:46:44 +00004413 }
4414 }
4415
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004416 if (!HasViableZeroArgOverload || ViableOverloads.size() != 1) {
John Wiegley429bb272011-04-08 18:41:53 +00004417 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gayfbe59942011-03-05 02:42:30 +00004418 << (AllOverloads.size() > 1) << 0
John Wiegley429bb272011-04-08 18:41:53 +00004419 << BaseExpr.get()->getSourceRange();
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004420 int ViableOverloadCount = ViableOverloads.size();
4421 int I;
4422 for (I = 0; I < ViableOverloadCount; ++I) {
4423 // FIXME: Magic number for max shown overloads stolen from
4424 // OverloadCandidateSet::NoteCandidates.
4425 if (I >= 4 && Diags.getShowOverloads() == Diagnostic::Ovl_Best) {
4426 break;
4427 }
4428 Diag(ViableOverloads[I].getDecl()->getSourceRange().getBegin(),
4429 diag::note_member_ref_possible_intended_overload);
4430 }
4431 if (I != ViableOverloadCount) {
John Wiegley429bb272011-04-08 18:41:53 +00004432 Diag(BaseExpr.get()->getExprLoc(), diag::note_ovl_too_many_candidates)
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004433 << int(ViableOverloadCount - I);
4434 }
4435 return ExprError();
4436 }
4437 } else {
4438 // We don't have an expression that's convenient to get a Decl from, but we
4439 // can at least check if the type is "function of 0 arguments which returns
4440 // an acceptable type".
4441 const FunctionType *Fun = NULL;
4442 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4443 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
4444 TryCall = true;
4445 }
4446 } else if ((Fun = BaseType->getAs<FunctionType>())) {
4447 TryCall = true;
John McCall864c0412011-04-26 20:42:42 +00004448 } else if (BaseType == Context.BoundMemberTy) {
4449 // Look for the bound-member type. If it's still overloaded,
4450 // give up, although we probably should have fallen into the
4451 // OverloadExpr case above if we actually have an overloaded
4452 // bound member.
4453 QualType fnType = Expr::findBoundMemberType(BaseExpr.get());
4454 if (!fnType.isNull()) {
4455 TryCall = true;
4456 Fun = fnType->castAs<FunctionType>();
4457 }
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004458 }
John McCall028d3972010-12-15 16:46:44 +00004459
4460 if (TryCall) {
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004461 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
4462 if (FPT->getNumArgs() == 0) {
4463 QualType ResultTy = Fun->getResultType();
4464 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
4465 (IsArrow && ResultTy->isPointerType() &&
4466 ResultTy->getPointeeType()->isRecordType());
4467 }
Matt Beaumont-Gay26ae5dd2011-02-17 02:54:17 +00004468 }
John McCall028d3972010-12-15 16:46:44 +00004469 }
4470 }
4471
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004472 if (TryCall) {
4473 // At this point, we know BaseExpr looks like it's potentially callable with
4474 // 0 arguments, and that it returns something of a reasonable type, so we
4475 // can emit a fixit and carry on pretending that BaseExpr was actually a
4476 // CallExpr.
4477 SourceLocation ParenInsertionLoc =
John Wiegley429bb272011-04-08 18:41:53 +00004478 PP.getLocForEndOfToken(BaseExpr.get()->getLocEnd());
4479 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004480 << int(Overloaded) << 1
John Wiegley429bb272011-04-08 18:41:53 +00004481 << BaseExpr.get()->getSourceRange()
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004482 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
John Wiegley429bb272011-04-08 18:41:53 +00004483 ExprResult NewBase = ActOnCallExpr(0, BaseExpr.take(), ParenInsertionLoc,
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004484 MultiExprArg(*this, 0, 0),
4485 ParenInsertionLoc);
4486 if (NewBase.isInvalid())
4487 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004488 BaseExpr = NewBase;
4489 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
Matt Beaumont-Gay65b34d72011-02-22 23:52:53 +00004490 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4491 ObjCImpDecl, HasTemplateArgs);
4492 }
4493
Douglas Gregor214f31a2009-03-27 06:00:30 +00004494 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
John Wiegley429bb272011-04-08 18:41:53 +00004495 << BaseType << BaseExpr.get()->getSourceRange();
Douglas Gregor214f31a2009-03-27 06:00:30 +00004496
Douglas Gregor214f31a2009-03-27 06:00:30 +00004497 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00004498}
4499
John McCall129e2df2009-11-30 22:42:35 +00004500/// The main callback when the parser finds something like
4501/// expression . [nested-name-specifier] identifier
4502/// expression -> [nested-name-specifier] identifier
4503/// where 'identifier' encompasses a fairly broad spectrum of
4504/// possibilities, including destructor and operator references.
4505///
4506/// \param OpKind either tok::arrow or tok::period
4507/// \param HasTrailingLParen whether the next token is '(', which
4508/// is used to diagnose mis-uses of special members that can
4509/// only be called
4510/// \param ObjCImpDecl the current ObjC @implementation decl;
4511/// this is an ugly hack around the fact that ObjC @implementations
4512/// aren't properly put in the context chain
John McCall60d7b3a2010-08-24 06:29:42 +00004513ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall5e3c67b2010-12-15 04:42:30 +00004514 SourceLocation OpLoc,
4515 tok::TokenKind OpKind,
4516 CXXScopeSpec &SS,
4517 UnqualifiedId &Id,
4518 Decl *ObjCImpDecl,
4519 bool HasTrailingLParen) {
John McCall129e2df2009-11-30 22:42:35 +00004520 if (SS.isSet() && SS.isInvalid())
4521 return ExprError();
4522
Francois Pichetdbee3412011-01-18 05:04:39 +00004523 // Warn about the explicit constructor calls Microsoft extension.
4524 if (getLangOptions().Microsoft &&
4525 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4526 Diag(Id.getSourceRange().getBegin(),
4527 diag::ext_ms_explicit_constructor_call);
4528
John McCall129e2df2009-11-30 22:42:35 +00004529 TemplateArgumentListInfo TemplateArgsBuffer;
4530
4531 // Decompose the name into its component parts.
Abramo Bagnara25777432010-08-11 22:01:17 +00004532 DeclarationNameInfo NameInfo;
John McCall129e2df2009-11-30 22:42:35 +00004533 const TemplateArgumentListInfo *TemplateArgs;
4534 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnara25777432010-08-11 22:01:17 +00004535 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004536
Abramo Bagnara25777432010-08-11 22:01:17 +00004537 DeclarationName Name = NameInfo.getName();
John McCall129e2df2009-11-30 22:42:35 +00004538 bool IsArrow = (OpKind == tok::arrow);
4539
4540 NamedDecl *FirstQualifierInScope
4541 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4542 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4543
4544 // This is a postfix expression, so get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004545 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004546 if (Result.isInvalid()) return ExprError();
4547 Base = Result.take();
John McCall129e2df2009-11-30 22:42:35 +00004548
Douglas Gregor01e56ae2010-04-12 20:54:26 +00004549 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4550 isDependentScopeSpecifier(SS)) {
John McCall9ae2f072010-08-23 23:25:46 +00004551 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00004552 IsArrow, OpLoc,
4553 SS, FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +00004554 NameInfo, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004555 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00004556 LookupResult R(*this, NameInfo, LookupMemberName);
John Wiegley429bb272011-04-08 18:41:53 +00004557 ExprResult BaseResult = Owned(Base);
4558 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCallad00b772010-06-16 08:42:20 +00004559 SS, ObjCImpDecl, TemplateArgs != 0);
John Wiegley429bb272011-04-08 18:41:53 +00004560 if (BaseResult.isInvalid())
4561 return ExprError();
4562 Base = BaseResult.take();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004563
John McCallad00b772010-06-16 08:42:20 +00004564 if (Result.isInvalid()) {
4565 Owned(Base);
4566 return ExprError();
4567 }
John McCall129e2df2009-11-30 22:42:35 +00004568
John McCallad00b772010-06-16 08:42:20 +00004569 if (Result.get()) {
4570 // The only way a reference to a destructor can be used is to
4571 // immediately call it, which falls into this case. If the
4572 // next token is not a '(', produce a diagnostic and build the
4573 // call now.
4574 if (!HasTrailingLParen &&
4575 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCall9ae2f072010-08-23 23:25:46 +00004576 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall129e2df2009-11-30 22:42:35 +00004577
John McCallad00b772010-06-16 08:42:20 +00004578 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00004579 }
4580
John McCall9ae2f072010-08-23 23:25:46 +00004581 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCallc2233c52010-01-15 08:34:02 +00004582 OpLoc, IsArrow, SS, FirstQualifierInScope,
4583 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004584 }
4585
4586 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00004587}
4588
John McCall60d7b3a2010-08-24 06:29:42 +00004589ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00004590 FunctionDecl *FD,
4591 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00004592 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004593 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00004594 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00004595 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00004596 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00004597 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004598 return ExprError();
4599 }
4600
4601 if (Param->hasUninstantiatedDefaultArg()) {
4602 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00004603
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004604 // Instantiate the expression.
4605 MultiLevelTemplateArgumentList ArgList
4606 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00004607
Nico Weber08e41a62010-11-29 18:19:25 +00004608 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004609 = ArgList.getInnermost();
4610 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4611 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004612
Nico Weber08e41a62010-11-29 18:19:25 +00004613 ExprResult Result;
4614 {
4615 // C++ [dcl.fct.default]p5:
4616 // The names in the [default argument] expression are bound, and
4617 // the semantic constraints are checked, at the point where the
4618 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00004619 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00004620 Result = SubstExpr(UninstExpr, ArgList);
4621 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004622 if (Result.isInvalid())
4623 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00004624
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004625 // Check the expression as an initializer for the parameter.
4626 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004627 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004628 InitializationKind Kind
4629 = InitializationKind::CreateCopy(Param->getLocation(),
4630 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4631 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00004632
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004633 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4634 Result = InitSeq.Perform(*this, Entity, Kind,
4635 MultiExprArg(*this, &ResultE, 1));
4636 if (Result.isInvalid())
4637 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004638
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004639 // Build the default argument expression.
4640 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4641 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004642 }
4643
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004644 // If the default expression creates temporaries, we need to
4645 // push them to the current stack of expression temporaries so they'll
4646 // be properly destroyed.
4647 // FIXME: We should really be rebuilding the default argument with new
4648 // bound temporaries; see the comment in PR5810.
Douglas Gregor5833b0b2010-09-14 22:55:20 +00004649 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4650 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4651 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4652 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4653 ExprTemporaries.push_back(Temporary);
4654 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004655
4656 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00004657 // Just mark all of the declarations in this potentially-evaluated expression
4658 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00004659 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00004660 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00004661}
4662
Douglas Gregor88a35142008-12-22 05:46:06 +00004663/// ConvertArgumentsForCall - Converts the arguments specified in
4664/// Args/NumArgs to the parameter types of the function FDecl with
4665/// function prototype Proto. Call is the call expression itself, and
4666/// Fn is the function expression. For a C++ member function, this
4667/// routine does not attempt to convert the object argument. Returns
4668/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004669bool
4670Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00004671 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00004672 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00004673 Expr **Args, unsigned NumArgs,
4674 SourceLocation RParenLoc) {
John McCall8e10f3b2011-02-26 05:39:39 +00004675 // Bail out early if calling a builtin with custom typechecking.
4676 // We don't need to do this in the
4677 if (FDecl)
4678 if (unsigned ID = FDecl->getBuiltinID())
4679 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4680 return false;
4681
Mike Stumpeed9cac2009-02-19 03:04:26 +00004682 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00004683 // assignment, to the types of the corresponding parameter, ...
4684 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004685 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004686
Douglas Gregor88a35142008-12-22 05:46:06 +00004687 // If too few arguments are available (and we don't have default
4688 // arguments for the remaining parameters), don't make the call.
4689 if (NumArgs < NumArgsInProto) {
4690 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4691 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004692 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00004693 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00004694 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00004695 }
4696
4697 // If too many are passed and not variadic, error on the extras and drop
4698 // them.
4699 if (NumArgs > NumArgsInProto) {
4700 if (!Proto->isVariadic()) {
4701 Diag(Args[NumArgsInProto]->getLocStart(),
4702 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00004703 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00004704 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00004705 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4706 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00004707
4708 // Emit the location of the prototype.
4709 if (FDecl && !FDecl->getBuiltinID())
4710 Diag(FDecl->getLocStart(),
4711 diag::note_typecheck_call_too_many_args)
4712 << FDecl;
4713
Douglas Gregor88a35142008-12-22 05:46:06 +00004714 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004715 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004716 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004717 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004718 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004719 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004720 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004721 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4722 if (Fn->getType()->isBlockPointerType())
4723 CallType = VariadicBlock; // Block
4724 else if (isa<MemberExpr>(Fn))
4725 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004726 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004727 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004728 if (Invalid)
4729 return true;
4730 unsigned TotalNumArgs = AllArgs.size();
4731 for (unsigned i = 0; i < TotalNumArgs; ++i)
4732 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004733
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004734 return false;
4735}
Mike Stumpeed9cac2009-02-19 03:04:26 +00004736
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004737bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4738 FunctionDecl *FDecl,
4739 const FunctionProtoType *Proto,
4740 unsigned FirstProtoArg,
4741 Expr **Args, unsigned NumArgs,
4742 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004743 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004744 unsigned NumArgsInProto = Proto->getNumArgs();
4745 unsigned NumArgsToCheck = NumArgs;
4746 bool Invalid = false;
4747 if (NumArgs != NumArgsInProto)
4748 // Use default arguments for missing arguments
4749 NumArgsToCheck = NumArgsInProto;
4750 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00004751 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004752 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004753 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004754
Douglas Gregor88a35142008-12-22 05:46:06 +00004755 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004756 if (ArgIx < NumArgs) {
4757 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004758
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004759 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4760 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00004761 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004762 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00004763 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004764
Douglas Gregora188ff22009-12-22 16:09:06 +00004765 // Pass the argument
4766 ParmVarDecl *Param = 0;
4767 if (FDecl && i < FDecl->getNumParams())
4768 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00004769
Douglas Gregora188ff22009-12-22 16:09:06 +00004770 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00004771 Param? InitializedEntity::InitializeParameter(Context, Param)
4772 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCall60d7b3a2010-08-24 06:29:42 +00004773 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00004774 SourceLocation(),
4775 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00004776 if (ArgE.isInvalid())
4777 return true;
4778
4779 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004780 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00004781 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004782
John McCall60d7b3a2010-08-24 06:29:42 +00004783 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004784 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00004785 if (ArgExpr.isInvalid())
4786 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004787
Anders Carlsson56c5e332009-08-25 03:49:14 +00004788 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00004789 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00004790 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00004791 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004792
Douglas Gregor88a35142008-12-22 05:46:06 +00004793 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00004794 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00004795
4796 // Assume that extern "C" functions with variadic arguments that
4797 // return __unknown_anytype aren't *really* variadic.
4798 if (Proto->getResultType() == Context.UnknownAnyTy &&
4799 FDecl && FDecl->isExternC()) {
4800 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4801 ExprResult arg;
4802 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
4803 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
4804 else
4805 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4806 Invalid |= arg.isInvalid();
4807 AllArgs.push_back(arg.take());
4808 }
4809
4810 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4811 } else {
4812 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4813 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4814 Invalid |= Arg.isInvalid();
4815 AllArgs.push_back(Arg.take());
4816 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004817 }
4818 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00004819 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00004820}
4821
John McCall755d8492011-04-12 00:42:48 +00004822/// Given a function expression of unknown-any type, try to rebuild it
4823/// to have a function type.
4824static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4825
Steve Narofff69936d2007-09-16 03:34:24 +00004826/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00004827/// This provides the location of the left/right parens and a list of comma
4828/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00004829ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004830Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004831 MultiExprArg args, SourceLocation RParenLoc,
4832 Expr *ExecConfig) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00004833 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00004834
4835 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004836 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00004837 if (Result.isInvalid()) return ExprError();
4838 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00004839
John McCall9ae2f072010-08-23 23:25:46 +00004840 Expr **Args = args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004841
Douglas Gregor88a35142008-12-22 05:46:06 +00004842 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00004843 // If this is a pseudo-destructor expression, build the call immediately.
4844 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4845 if (NumArgs > 0) {
4846 // Pseudo-destructor calls should not have any arguments.
4847 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00004848 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00004849 SourceRange(Args[0]->getLocStart(),
4850 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00004851
Douglas Gregora71d8192009-09-04 17:36:40 +00004852 NumArgs = 0;
4853 }
Mike Stump1eb44332009-09-09 15:08:12 +00004854
Douglas Gregora71d8192009-09-04 17:36:40 +00004855 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00004856 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00004857 }
Mike Stump1eb44332009-09-09 15:08:12 +00004858
Douglas Gregor17330012009-02-04 15:01:18 +00004859 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00004860 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00004861 // FIXME: Will need to cache the results of name lookup (including ADL) in
4862 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00004863 bool Dependent = false;
4864 if (Fn->isTypeDependent())
4865 Dependent = true;
4866 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4867 Dependent = true;
4868
Peter Collingbournee08ce652011-02-09 21:07:24 +00004869 if (Dependent) {
4870 if (ExecConfig) {
4871 return Owned(new (Context) CUDAKernelCallExpr(
4872 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4873 Context.DependentTy, VK_RValue, RParenLoc));
4874 } else {
4875 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4876 Context.DependentTy, VK_RValue,
4877 RParenLoc));
4878 }
4879 }
Douglas Gregor17330012009-02-04 15:01:18 +00004880
4881 // Determine whether this is a call to an object (C++ [over.call.object]).
4882 if (Fn->getType()->isRecordType())
4883 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004884 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00004885
John McCall755d8492011-04-12 00:42:48 +00004886 if (Fn->getType() == Context.UnknownAnyTy) {
4887 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4888 if (result.isInvalid()) return ExprError();
4889 Fn = result.take();
4890 }
4891
John McCall864c0412011-04-26 20:42:42 +00004892 if (Fn->getType() == Context.BoundMemberTy) {
John McCallaa81e162009-12-01 22:10:20 +00004893 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004894 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00004895 }
John McCall864c0412011-04-26 20:42:42 +00004896 }
John McCall129e2df2009-11-30 22:42:35 +00004897
John McCall864c0412011-04-26 20:42:42 +00004898 // Check for overloaded calls. This can happen even in C due to extensions.
4899 if (Fn->getType() == Context.OverloadTy) {
4900 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4901
4902 // We aren't supposed to apply this logic if there's an '&' involved.
4903 if (!find.IsAddressOfOperand) {
4904 OverloadExpr *ovl = find.Expression;
4905 if (isa<UnresolvedLookupExpr>(ovl)) {
4906 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4907 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
4908 RParenLoc, ExecConfig);
4909 } else {
John McCallaa81e162009-12-01 22:10:20 +00004910 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00004911 RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00004912 }
4913 }
Douglas Gregor88a35142008-12-22 05:46:06 +00004914 }
4915
Douglas Gregorfa047642009-02-04 00:32:51 +00004916 // If we're directly calling a function, get the appropriate declaration.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004917
Eli Friedmanefa42f72009-12-26 03:35:45 +00004918 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00004919
John McCall3b4294e2009-12-16 12:17:52 +00004920 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00004921 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4922 if (UnOp->getOpcode() == UO_AddrOf)
4923 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4924
John McCall3b4294e2009-12-16 12:17:52 +00004925 if (isa<DeclRefExpr>(NakedFn))
4926 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00004927 else if (isa<MemberExpr>(NakedFn))
4928 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00004929
Peter Collingbournee08ce652011-02-09 21:07:24 +00004930 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4931 ExecConfig);
4932}
4933
4934ExprResult
4935Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4936 MultiExprArg execConfig, SourceLocation GGGLoc) {
4937 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4938 if (!ConfigDecl)
4939 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4940 << "cudaConfigureCall");
4941 QualType ConfigQTy = ConfigDecl->getType();
4942
4943 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4944 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4945
4946 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCallaa81e162009-12-01 22:10:20 +00004947}
4948
John McCall3b4294e2009-12-16 12:17:52 +00004949/// BuildResolvedCallExpr - Build a call to a resolved expression,
4950/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00004951/// unary-convert to an expression of function-pointer or
4952/// block-pointer type.
4953///
4954/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00004955ExprResult
John McCallaa81e162009-12-01 22:10:20 +00004956Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4957 SourceLocation LParenLoc,
4958 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00004959 SourceLocation RParenLoc,
4960 Expr *Config) {
John McCallaa81e162009-12-01 22:10:20 +00004961 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4962
Chris Lattner04421082008-04-08 04:40:51 +00004963 // Promote the function operand.
John Wiegley429bb272011-04-08 18:41:53 +00004964 ExprResult Result = UsualUnaryConversions(Fn);
4965 if (Result.isInvalid())
4966 return ExprError();
4967 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00004968
Chris Lattner925e60d2007-12-28 05:29:59 +00004969 // Make the call expr early, before semantic checks. This guarantees cleanup
4970 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00004971 CallExpr *TheCall;
4972 if (Config) {
4973 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4974 cast<CallExpr>(Config),
4975 Args, NumArgs,
4976 Context.BoolTy,
4977 VK_RValue,
4978 RParenLoc);
4979 } else {
4980 TheCall = new (Context) CallExpr(Context, Fn,
4981 Args, NumArgs,
4982 Context.BoolTy,
4983 VK_RValue,
4984 RParenLoc);
4985 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00004986
John McCall8e10f3b2011-02-26 05:39:39 +00004987 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4988
4989 // Bail out early if calling a builtin with custom typechecking.
4990 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4991 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4992
John McCall1de4d4e2011-04-07 08:22:57 +00004993 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00004994 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00004995 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00004996 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4997 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00004998 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00004999 if (FuncT == 0)
5000 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5001 << Fn->getType() << Fn->getSourceRange());
5002 } else if (const BlockPointerType *BPT =
5003 Fn->getType()->getAs<BlockPointerType>()) {
5004 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5005 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00005006 // Handle calls to expressions of unknown-any type.
5007 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00005008 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00005009 if (rewrite.isInvalid()) return ExprError();
5010 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00005011 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00005012 goto retry;
5013 }
5014
Sebastian Redl0eb23302009-01-19 00:08:26 +00005015 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5016 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00005017 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00005018
Peter Collingbourne0423fc62011-02-23 01:53:29 +00005019 if (getLangOptions().CUDA) {
5020 if (Config) {
5021 // CUDA: Kernel calls must be to global functions
5022 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5023 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5024 << FDecl->getName() << Fn->getSourceRange());
5025
5026 // CUDA: Kernel function must have 'void' return type
5027 if (!FuncT->getResultType()->isVoidType())
5028 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5029 << Fn->getType() << Fn->getSourceRange());
5030 }
5031 }
5032
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00005033 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005034 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00005035 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00005036 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00005037 return ExprError();
5038
Chris Lattner925e60d2007-12-28 05:29:59 +00005039 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00005040 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00005041 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00005042
Douglas Gregor72564e72009-02-26 23:50:07 +00005043 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00005044 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00005045 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00005046 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00005047 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00005048 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00005049
Douglas Gregor74734d52009-04-02 15:37:10 +00005050 if (FDecl) {
5051 // Check if we have too few/too many template arguments, based
5052 // on our knowledge of the function definition.
5053 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00005054 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00005055 const FunctionProtoType *Proto
5056 = Def->getType()->getAs<FunctionProtoType>();
5057 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00005058 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5059 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00005060 }
Douglas Gregor46542412010-10-25 20:39:23 +00005061
5062 // If the function we're calling isn't a function prototype, but we have
5063 // a function prototype from a prior declaratiom, use that prototype.
5064 if (!FDecl->hasPrototype())
5065 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00005066 }
5067
Steve Naroffb291ab62007-08-28 23:30:39 +00005068 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00005069 for (unsigned i = 0; i != NumArgs; i++) {
5070 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00005071
5072 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00005073 InitializedEntity Entity
5074 = InitializedEntity::InitializeParameter(Context,
5075 Proto->getArgType(i));
5076 ExprResult ArgE = PerformCopyInitialization(Entity,
5077 SourceLocation(),
5078 Owned(Arg));
5079 if (ArgE.isInvalid())
5080 return true;
5081
5082 Arg = ArgE.takeAs<Expr>();
5083
5084 } else {
John Wiegley429bb272011-04-08 18:41:53 +00005085 ExprResult ArgE = DefaultArgumentPromotion(Arg);
5086
5087 if (ArgE.isInvalid())
5088 return true;
5089
5090 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00005091 }
5092
Douglas Gregor0700bbf2010-10-26 05:45:40 +00005093 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
5094 Arg->getType(),
5095 PDiag(diag::err_call_incomplete_argument)
5096 << Arg->getSourceRange()))
5097 return ExprError();
5098
Chris Lattner925e60d2007-12-28 05:29:59 +00005099 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00005100 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005101 }
Chris Lattner925e60d2007-12-28 05:29:59 +00005102
Douglas Gregor88a35142008-12-22 05:46:06 +00005103 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5104 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00005105 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5106 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00005107
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00005108 // Check for sentinels
5109 if (NDecl)
5110 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00005111
Chris Lattner59907c42007-08-10 20:18:51 +00005112 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00005113 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00005114 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00005115 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00005116
John McCall8e10f3b2011-02-26 05:39:39 +00005117 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00005118 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00005119 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00005120 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00005121 return ExprError();
5122 }
Chris Lattner59907c42007-08-10 20:18:51 +00005123
John McCall9ae2f072010-08-23 23:25:46 +00005124 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00005125}
5126
John McCall60d7b3a2010-08-24 06:29:42 +00005127ExprResult
John McCallb3d87482010-08-24 05:47:05 +00005128Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005129 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00005130 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00005131 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00005132 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00005133
5134 TypeSourceInfo *TInfo;
5135 QualType literalType = GetTypeFromParser(Ty, &TInfo);
5136 if (!TInfo)
5137 TInfo = Context.getTrivialTypeSourceInfo(literalType);
5138
John McCall9ae2f072010-08-23 23:25:46 +00005139 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00005140}
5141
John McCall60d7b3a2010-08-24 06:29:42 +00005142ExprResult
John McCall42f56b52010-01-18 19:35:47 +00005143Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCall9ae2f072010-08-23 23:25:46 +00005144 SourceLocation RParenLoc, Expr *literalExpr) {
John McCall42f56b52010-01-18 19:35:47 +00005145 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00005146
Eli Friedman6223c222008-05-20 05:22:08 +00005147 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00005148 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5149 PDiag(diag::err_illegal_decl_array_incomplete_type)
5150 << SourceRange(LParenLoc,
5151 literalExpr->getSourceRange().getEnd())))
5152 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00005153 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005154 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5155 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00005156 } else if (!literalType->isDependentType() &&
5157 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00005158 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005159 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00005160 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005161 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00005162
Douglas Gregor99a2e602009-12-16 01:38:02 +00005163 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00005164 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00005165 InitializationKind Kind
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005166 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor99a2e602009-12-16 01:38:02 +00005167 /*IsCStyleCast=*/true);
Eli Friedman08544622009-12-22 02:35:53 +00005168 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00005169 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00005170 MultiExprArg(*this, &literalExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00005171 &literalType);
5172 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005173 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00005174 literalExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00005175
Chris Lattner371f2582008-12-04 23:50:19 +00005176 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00005177 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00005178 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005179 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00005180 }
Eli Friedman08544622009-12-22 02:35:53 +00005181
John McCallf89e55a2010-11-18 06:31:45 +00005182 // In C, compound literals are l-values for some reason.
5183 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
5184
John McCall1d7d8d62010-01-19 22:33:45 +00005185 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCallf89e55a2010-11-18 06:31:45 +00005186 VK, literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00005187}
5188
John McCall60d7b3a2010-08-24 06:29:42 +00005189ExprResult
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005190Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005191 SourceLocation RBraceLoc) {
5192 unsigned NumInit = initlist.size();
John McCall9ae2f072010-08-23 23:25:46 +00005193 Expr **InitList = initlist.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00005194
Steve Naroff08d92e42007-09-15 18:49:24 +00005195 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00005196 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005197
Ted Kremenek709210f2010-04-13 23:39:13 +00005198 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
5199 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00005200 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005201 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00005202}
5203
John McCallf3ea8cf2010-11-14 08:17:51 +00005204/// Prepares for a scalar cast, performing all the necessary stages
5205/// except the final cast and returning the kind required.
John Wiegley429bb272011-04-08 18:41:53 +00005206static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00005207 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5208 // Also, callers should have filtered out the invalid cases with
5209 // pointers. Everything else should be possible.
5210
John Wiegley429bb272011-04-08 18:41:53 +00005211 QualType SrcTy = Src.get()->getType();
John McCallf3ea8cf2010-11-14 08:17:51 +00005212 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00005213 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00005214
John McCalldaa8e4e2010-11-15 09:13:47 +00005215 switch (SrcTy->getScalarTypeKind()) {
5216 case Type::STK_MemberPointer:
5217 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00005218
John McCalldaa8e4e2010-11-15 09:13:47 +00005219 case Type::STK_Pointer:
5220 switch (DestTy->getScalarTypeKind()) {
5221 case Type::STK_Pointer:
5222 return DestTy->isObjCObjectPointerType() ?
John McCallf3ea8cf2010-11-14 08:17:51 +00005223 CK_AnyPointerToObjCPointerCast :
5224 CK_BitCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005225 case Type::STK_Bool:
5226 return CK_PointerToBoolean;
5227 case Type::STK_Integral:
5228 return CK_PointerToIntegral;
5229 case Type::STK_Floating:
5230 case Type::STK_FloatingComplex:
5231 case Type::STK_IntegralComplex:
5232 case Type::STK_MemberPointer:
5233 llvm_unreachable("illegal cast from pointer");
5234 }
5235 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005236
John McCalldaa8e4e2010-11-15 09:13:47 +00005237 case Type::STK_Bool: // casting from bool is like casting from an integer
5238 case Type::STK_Integral:
5239 switch (DestTy->getScalarTypeKind()) {
5240 case Type::STK_Pointer:
John Wiegley429bb272011-04-08 18:41:53 +00005241 if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00005242 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00005243 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005244 case Type::STK_Bool:
5245 return CK_IntegralToBoolean;
5246 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00005247 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005248 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00005249 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00005250 case Type::STK_IntegralComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005251 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5252 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00005253 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005254 case Type::STK_FloatingComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005255 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5256 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00005257 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005258 case Type::STK_MemberPointer:
5259 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005260 }
5261 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005262
John McCalldaa8e4e2010-11-15 09:13:47 +00005263 case Type::STK_Floating:
5264 switch (DestTy->getScalarTypeKind()) {
5265 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00005266 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005267 case Type::STK_Bool:
5268 return CK_FloatingToBoolean;
5269 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00005270 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00005271 case Type::STK_FloatingComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005272 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5273 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00005274 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005275 case Type::STK_IntegralComplex:
John Wiegley429bb272011-04-08 18:41:53 +00005276 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5277 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00005278 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005279 case Type::STK_Pointer:
5280 llvm_unreachable("valid float->pointer cast?");
5281 case Type::STK_MemberPointer:
5282 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005283 }
5284 break;
5285
John McCalldaa8e4e2010-11-15 09:13:47 +00005286 case Type::STK_FloatingComplex:
5287 switch (DestTy->getScalarTypeKind()) {
5288 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005289 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00005290 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005291 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00005292 case Type::STK_Floating: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00005293 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005294 if (S.Context.hasSameType(ET, DestTy))
5295 return CK_FloatingComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00005296 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00005297 return CK_FloatingCast;
5298 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005299 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00005300 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00005301 case Type::STK_Integral:
John Wiegley429bb272011-04-08 18:41:53 +00005302 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5303 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00005304 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00005305 case Type::STK_Pointer:
5306 llvm_unreachable("valid complex float->pointer cast?");
5307 case Type::STK_MemberPointer:
5308 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005309 }
5310 break;
5311
John McCalldaa8e4e2010-11-15 09:13:47 +00005312 case Type::STK_IntegralComplex:
5313 switch (DestTy->getScalarTypeKind()) {
5314 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005315 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00005316 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00005317 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00005318 case Type::STK_Integral: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00005319 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005320 if (S.Context.hasSameType(ET, DestTy))
5321 return CK_IntegralComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00005322 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00005323 return CK_IntegralCast;
5324 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005325 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00005326 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00005327 case Type::STK_Floating:
John Wiegley429bb272011-04-08 18:41:53 +00005328 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5329 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00005330 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00005331 case Type::STK_Pointer:
5332 llvm_unreachable("valid complex int->pointer cast?");
5333 case Type::STK_MemberPointer:
5334 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00005335 }
5336 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00005337 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005338
John McCallf3ea8cf2010-11-14 08:17:51 +00005339 llvm_unreachable("Unhandled scalar cast");
5340 return CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00005341}
5342
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005343/// CheckCastTypes - Check type constraints for casting between types.
John Wiegley429bb272011-04-08 18:41:53 +00005344ExprResult Sema::CheckCastTypes(SourceRange TyR, QualType castType,
5345 Expr *castExpr, CastKind& Kind, ExprValueKind &VK,
5346 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall1de4d4e2011-04-07 08:22:57 +00005347 if (castExpr->getType() == Context.UnknownAnyTy)
5348 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
5349
Sebastian Redl9cc11e72009-07-25 15:41:38 +00005350 if (getLangOptions().CPlusPlus)
Douglas Gregor40749ee2010-11-03 00:35:38 +00005351 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
5352 castExpr->getLocEnd()),
John McCallf89e55a2010-11-18 06:31:45 +00005353 castType, VK, castExpr, Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00005354 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00005355
John McCallfb8721c2011-04-10 19:13:55 +00005356 assert(!castExpr->getType()->isPlaceholderType());
5357
John McCallf89e55a2010-11-18 06:31:45 +00005358 // We only support r-value casts in C.
5359 VK = VK_RValue;
5360
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005361 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
5362 // type needs to be scalar.
5363 if (castType->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +00005364 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley429bb272011-04-08 18:41:53 +00005365 ExprResult castExprRes = IgnoredValueConversions(castExpr);
5366 if (castExprRes.isInvalid())
5367 return ExprError();
5368 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00005369
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005370 // Cast to void allows any expr type.
John McCall2de56d12010-08-25 11:45:40 +00005371 Kind = CK_ToVoid;
John Wiegley429bb272011-04-08 18:41:53 +00005372 return Owned(castExpr);
Anders Carlssonebeaf202009-10-16 02:35:04 +00005373 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005374
John Wiegley429bb272011-04-08 18:41:53 +00005375 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
5376 if (castExprRes.isInvalid())
5377 return ExprError();
5378 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00005379
Eli Friedman8d438082010-07-17 20:43:49 +00005380 if (RequireCompleteType(TyR.getBegin(), castType,
5381 diag::err_typecheck_cast_to_incomplete))
John Wiegley429bb272011-04-08 18:41:53 +00005382 return ExprError();
Eli Friedman8d438082010-07-17 20:43:49 +00005383
Anders Carlssonebeaf202009-10-16 02:35:04 +00005384 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00005385 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005386 (castType->isStructureType() || castType->isUnionType())) {
5387 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005388 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005389 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
5390 << castType << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005391 Kind = CK_NoOp;
John Wiegley429bb272011-04-08 18:41:53 +00005392 return Owned(castExpr);
Anders Carlssonc3516322009-10-16 02:48:28 +00005393 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005394
Anders Carlssonc3516322009-10-16 02:48:28 +00005395 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005396 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00005397 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005398 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005399 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005400 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005401 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara8c4bfe52010-10-07 21:20:44 +00005402 castExpr->getType()) &&
5403 !Field->isUnnamedBitfield()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005404 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5405 << castExpr->getSourceRange();
5406 break;
5407 }
5408 }
John Wiegley429bb272011-04-08 18:41:53 +00005409 if (Field == FieldEnd) {
5410 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00005411 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005412 return ExprError();
5413 }
John McCall2de56d12010-08-25 11:45:40 +00005414 Kind = CK_ToUnion;
John Wiegley429bb272011-04-08 18:41:53 +00005415 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005416 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005417
Anders Carlssonc3516322009-10-16 02:48:28 +00005418 // Reject any other conversions to non-scalar types.
John Wiegley429bb272011-04-08 18:41:53 +00005419 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlssonc3516322009-10-16 02:48:28 +00005420 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005421 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00005422 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005423
John McCallf3ea8cf2010-11-14 08:17:51 +00005424 // The type we're casting to is known to be a scalar or vector.
5425
5426 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005427 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00005428 !castExpr->getType()->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005429 Diag(castExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005430 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00005431 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005432 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00005433 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005434
5435 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00005436 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005437
Anton Yartsevd06fea82011-03-27 09:32:40 +00005438 if (castType->isVectorType()) {
5439 if (castType->getAs<VectorType>()->getVectorKind() ==
5440 VectorType::AltiVecVector &&
5441 (castExpr->getType()->isIntegerType() ||
5442 castExpr->getType()->isFloatingType())) {
5443 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00005444 return Owned(castExpr);
5445 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
5446 return ExprError();
Anton Yartsevd06fea82011-03-27 09:32:40 +00005447 } else
John Wiegley429bb272011-04-08 18:41:53 +00005448 return Owned(castExpr);
Anton Yartsevd06fea82011-03-27 09:32:40 +00005449 }
John Wiegley429bb272011-04-08 18:41:53 +00005450 if (castExpr->getType()->isVectorType()) {
5451 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
5452 return ExprError();
5453 else
5454 return Owned(castExpr);
5455 }
Anders Carlssonc3516322009-10-16 02:48:28 +00005456
John McCallf3ea8cf2010-11-14 08:17:51 +00005457 // The source and target types are both scalars, i.e.
5458 // - arithmetic types (fundamental, enum, and complex)
5459 // - all kinds of pointers
5460 // Note that member pointers were filtered out with C++, above.
5461
John Wiegley429bb272011-04-08 18:41:53 +00005462 if (isa<ObjCSelectorExpr>(castExpr)) {
5463 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
5464 return ExprError();
5465 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005466
John McCallf3ea8cf2010-11-14 08:17:51 +00005467 // If either type is a pointer, the other type has to be either an
5468 // integer or a pointer.
Anders Carlssonc3516322009-10-16 02:48:28 +00005469 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00005470 QualType castExprType = castExpr->getType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00005471 if (!castExprType->isIntegralType(Context) &&
John Wiegley429bb272011-04-08 18:41:53 +00005472 castExprType->isArithmeticType()) {
5473 Diag(castExpr->getLocStart(),
5474 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00005475 << castExprType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005476 return ExprError();
5477 }
Eli Friedman41826bb2009-05-01 02:23:58 +00005478 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005479 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
5480 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00005481 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00005482 return ExprError();
5483 }
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005484 }
Anders Carlsson82debc72009-10-18 18:12:03 +00005485
John Wiegley429bb272011-04-08 18:41:53 +00005486 castExprRes = Owned(castExpr);
5487 Kind = PrepareScalarCast(*this, castExprRes, castType);
5488 if (castExprRes.isInvalid())
5489 return ExprError();
5490 castExpr = castExprRes.take();
John McCallb7f4ffe2010-08-12 21:44:57 +00005491
John McCallf3ea8cf2010-11-14 08:17:51 +00005492 if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00005493 CheckCastAlign(castExpr, castType, TyR);
5494
John Wiegley429bb272011-04-08 18:41:53 +00005495 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00005496}
5497
Anders Carlssonc3516322009-10-16 02:48:28 +00005498bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00005499 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00005500 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005501
Anders Carlssona64db8f2007-11-27 05:51:55 +00005502 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00005503 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00005504 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00005505 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00005506 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005507 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00005508 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005509 } else
5510 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005511 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00005512 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005513
John McCall2de56d12010-08-25 11:45:40 +00005514 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00005515 return false;
5516}
5517
John Wiegley429bb272011-04-08 18:41:53 +00005518ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5519 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00005520 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005521
Anders Carlsson16a89042009-10-16 05:23:41 +00005522 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005523
Nate Begeman9b10da62009-06-27 22:05:55 +00005524 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5525 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00005526 if (SrcTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005527 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
5528 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00005529 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00005530 return ExprError();
5531 }
John McCall2de56d12010-08-25 11:45:40 +00005532 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00005533 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00005534 }
5535
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005536 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00005537 // conversion will take place first from scalar to elt type, and then
5538 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005539 if (SrcTy->isPointerType())
5540 return Diag(R.getBegin(),
5541 diag::err_invalid_conversion_between_vector_and_scalar)
5542 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00005543
5544 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00005545 ExprResult CastExprRes = Owned(CastExpr);
5546 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
5547 if (CastExprRes.isInvalid())
5548 return ExprError();
5549 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005550
John McCall2de56d12010-08-25 11:45:40 +00005551 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00005552 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00005553}
5554
John McCall60d7b3a2010-08-24 06:29:42 +00005555ExprResult
John McCallb3d87482010-08-24 05:47:05 +00005556Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005557 SourceLocation RParenLoc, Expr *castExpr) {
5558 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005559 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00005560
John McCall9d125032010-01-15 18:39:57 +00005561 TypeSourceInfo *castTInfo;
5562 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5563 if (!castTInfo)
John McCall42f56b52010-01-18 19:35:47 +00005564 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00005565
Nate Begeman2ef13e52009-08-10 23:49:36 +00005566 // If the Expr being casted is a ParenListExpr, handle it specially.
5567 if (isa<ParenListExpr>(castExpr))
John McCall9ae2f072010-08-23 23:25:46 +00005568 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCall42f56b52010-01-18 19:35:47 +00005569 castTInfo);
John McCallb042fdf2010-01-15 18:56:44 +00005570
John McCall9ae2f072010-08-23 23:25:46 +00005571 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallb042fdf2010-01-15 18:56:44 +00005572}
5573
John McCall60d7b3a2010-08-24 06:29:42 +00005574ExprResult
John McCallb042fdf2010-01-15 18:56:44 +00005575Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCall9ae2f072010-08-23 23:25:46 +00005576 SourceLocation RParenLoc, Expr *castExpr) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005577 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +00005578 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +00005579 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +00005580 ExprResult CastResult =
5581 CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
5582 Kind, VK, BasePath);
5583 if (CastResult.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005584 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00005585 castExpr = CastResult.take();
Anders Carlsson0aebc812009-09-09 21:33:21 +00005586
John McCallf871d0c2010-08-07 06:22:56 +00005587 return Owned(CStyleCastExpr::Create(Context,
John Wiegley429bb272011-04-08 18:41:53 +00005588 Ty->getType().getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +00005589 VK, Kind, castExpr, &BasePath, Ty,
John McCallf871d0c2010-08-07 06:22:56 +00005590 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00005591}
5592
Nate Begeman2ef13e52009-08-10 23:49:36 +00005593/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5594/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005595ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005596Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005597 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5598 if (!E)
5599 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00005600
John McCall60d7b3a2010-08-24 06:29:42 +00005601 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00005602
Nate Begeman2ef13e52009-08-10 23:49:36 +00005603 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00005604 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5605 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00005606
John McCall9ae2f072010-08-23 23:25:46 +00005607 if (Result.isInvalid()) return ExprError();
5608
5609 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005610}
5611
John McCall60d7b3a2010-08-24 06:29:42 +00005612ExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00005613Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00005614 SourceLocation RParenLoc, Expr *Op,
John McCall42f56b52010-01-18 19:35:47 +00005615 TypeSourceInfo *TInfo) {
John McCall9ae2f072010-08-23 23:25:46 +00005616 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCall42f56b52010-01-18 19:35:47 +00005617 QualType Ty = TInfo->getType();
Anton Yartsevd06fea82011-03-27 09:32:40 +00005618 bool isVectorLiteral = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005619
Anton Yartsevd06fea82011-03-27 09:32:40 +00005620 // Check for an altivec or OpenCL literal,
John Thompson8bb59a82010-06-30 22:55:51 +00005621 // i.e. all the elements are integer constants.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005622 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5623 if (PE->getNumExprs() == 0) {
5624 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5625 return ExprError();
5626 }
John Thompson8bb59a82010-06-30 22:55:51 +00005627 if (PE->getNumExprs() == 1) {
5628 if (!PE->getExpr(0)->getType()->isVectorType())
Anton Yartsevd06fea82011-03-27 09:32:40 +00005629 isVectorLiteral = true;
John Thompson8bb59a82010-06-30 22:55:51 +00005630 }
5631 else
Anton Yartsevd06fea82011-03-27 09:32:40 +00005632 isVectorLiteral = true;
John Thompson8bb59a82010-06-30 22:55:51 +00005633 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00005634
Anton Yartsevd06fea82011-03-27 09:32:40 +00005635 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
John Thompson8bb59a82010-06-30 22:55:51 +00005636 // then handle it as such.
Anton Yartsevd06fea82011-03-27 09:32:40 +00005637 if (isVectorLiteral) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005638 llvm::SmallVector<Expr *, 8> initExprs;
Anton Yartsevd06fea82011-03-27 09:32:40 +00005639 // '(...)' form of vector initialization in AltiVec: the number of
5640 // initializers must be one or must match the size of the vector.
5641 // If a single value is specified in the initializer then it will be
5642 // replicated to all the components of the vector
5643 if (Ty->getAs<VectorType>()->getVectorKind() ==
5644 VectorType::AltiVecVector) {
5645 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5646 // The number of initializers must be one or must match the size of the
5647 // vector. If a single value is specified in the initializer then it will
5648 // be replicated to all the components of the vector
5649 if (PE->getNumExprs() == 1) {
5650 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00005651 ExprResult Literal = Owned(PE->getExpr(0));
5652 Literal = ImpCastExprToType(Literal.take(), ElemTy,
5653 PrepareScalarCast(*this, Literal, ElemTy));
5654 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
Anton Yartsevd06fea82011-03-27 09:32:40 +00005655 }
5656 else if (PE->getNumExprs() < numElems) {
5657 Diag(PE->getExprLoc(),
5658 diag::err_incorrect_number_of_vector_initializers);
5659 return ExprError();
5660 }
5661 else
5662 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5663 initExprs.push_back(PE->getExpr(i));
5664 }
5665 else
5666 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5667 initExprs.push_back(PE->getExpr(i));
Nate Begeman2ef13e52009-08-10 23:49:36 +00005668
5669 // FIXME: This means that pretty-printing the final AST will produce curly
5670 // braces instead of the original commas.
Ted Kremenek709210f2010-04-13 23:39:13 +00005671 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5672 &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00005673 initExprs.size(), RParenLoc);
5674 E->setType(Ty);
John McCall9ae2f072010-08-23 23:25:46 +00005675 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005676 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00005677 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00005678 // sequence of BinOp comma operators.
John McCall60d7b3a2010-08-24 06:29:42 +00005679 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCall9ae2f072010-08-23 23:25:46 +00005680 if (Result.isInvalid()) return ExprError();
5681 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman2ef13e52009-08-10 23:49:36 +00005682 }
5683}
5684
John McCall60d7b3a2010-08-24 06:29:42 +00005685ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00005686 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005687 MultiExprArg Val,
John McCallb3d87482010-08-24 05:47:05 +00005688 ParsedType TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00005689 unsigned nexprs = Val.size();
5690 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00005691 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5692 Expr *expr;
5693 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5694 expr = new (Context) ParenExpr(L, R, exprs[0]);
5695 else
5696 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00005697 return Owned(expr);
5698}
5699
Chandler Carruth82214a82011-02-18 23:54:50 +00005700/// \brief Emit a specialized diagnostic when one expression is a null pointer
5701/// constant and the other is not a pointer.
5702bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5703 SourceLocation QuestionLoc) {
5704 Expr *NullExpr = LHS;
5705 Expr *NonPointerExpr = RHS;
5706 Expr::NullPointerConstantKind NullKind =
5707 NullExpr->isNullPointerConstant(Context,
5708 Expr::NPC_ValueDependentIsNotNull);
5709
5710 if (NullKind == Expr::NPCK_NotNull) {
5711 NullExpr = RHS;
5712 NonPointerExpr = LHS;
5713 NullKind =
5714 NullExpr->isNullPointerConstant(Context,
5715 Expr::NPC_ValueDependentIsNotNull);
5716 }
5717
5718 if (NullKind == Expr::NPCK_NotNull)
5719 return false;
5720
5721 if (NullKind == Expr::NPCK_ZeroInteger) {
5722 // In this case, check to make sure that we got here from a "NULL"
5723 // string in the source code.
5724 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00005725 SourceLocation loc = NullExpr->getExprLoc();
5726 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00005727 return false;
5728 }
5729
5730 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5731 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5732 << NonPointerExpr->getType() << DiagType
5733 << NonPointerExpr->getSourceRange();
5734 return true;
5735}
5736
Sebastian Redl28507842009-02-26 14:39:58 +00005737/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5738/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00005739/// C99 6.5.15
John Wiegley429bb272011-04-08 18:41:53 +00005740QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCall56ca35d2011-02-17 10:25:35 +00005741 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00005742 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00005743
John McCallfb8721c2011-04-10 19:13:55 +00005744 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00005745 if (!lhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00005746 LHS = move(lhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00005747
John McCallfb8721c2011-04-10 19:13:55 +00005748 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00005749 if (!rhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00005750 RHS = move(rhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00005751
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005752 // C++ is sufficiently different to merit its own checker.
5753 if (getLangOptions().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00005754 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00005755
5756 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00005757 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005758
John Wiegley429bb272011-04-08 18:41:53 +00005759 Cond = UsualUnaryConversions(Cond.take());
5760 if (Cond.isInvalid())
5761 return QualType();
5762 LHS = UsualUnaryConversions(LHS.take());
5763 if (LHS.isInvalid())
5764 return QualType();
5765 RHS = UsualUnaryConversions(RHS.take());
5766 if (RHS.isInvalid())
5767 return QualType();
5768
5769 QualType CondTy = Cond.get()->getType();
5770 QualType LHSTy = LHS.get()->getType();
5771 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005772
Reid Spencer5f016e22007-07-11 17:01:13 +00005773 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005774 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begeman6155d732010-09-20 22:41:17 +00005775 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5776 // Throw an error if its not either.
5777 if (getLangOptions().OpenCL) {
5778 if (!CondTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005779 Diag(Cond.get()->getLocStart(),
Nate Begeman6155d732010-09-20 22:41:17 +00005780 diag::err_typecheck_cond_expect_scalar_or_vector)
5781 << CondTy;
5782 return QualType();
5783 }
5784 }
5785 else {
John Wiegley429bb272011-04-08 18:41:53 +00005786 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00005787 << CondTy;
5788 return QualType();
5789 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005790 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005791
Chris Lattner70d67a92008-01-06 22:42:25 +00005792 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00005793 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5794 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00005795
Nate Begeman6155d732010-09-20 22:41:17 +00005796 // OpenCL: If the condition is a vector, and both operands are scalar,
5797 // attempt to implicity convert them to the vector type to act like the
5798 // built in select.
5799 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5800 // Both operands should be of scalar type.
5801 if (!LHSTy->isScalarType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005802 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00005803 << CondTy;
5804 return QualType();
5805 }
5806 if (!RHSTy->isScalarType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005807 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00005808 << CondTy;
5809 return QualType();
5810 }
5811 // Implicity convert these scalars to the type of the condition.
John Wiegley429bb272011-04-08 18:41:53 +00005812 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5813 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begeman6155d732010-09-20 22:41:17 +00005814 }
5815
Chris Lattner70d67a92008-01-06 22:42:25 +00005816 // If both operands have arithmetic type, do the usual arithmetic conversions
5817 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005818 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5819 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00005820 if (LHS.isInvalid() || RHS.isInvalid())
5821 return QualType();
5822 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00005823 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005824
Chris Lattner70d67a92008-01-06 22:42:25 +00005825 // If both operands are the same structure or union type, the result is that
5826 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005827 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5828 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00005829 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00005830 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00005831 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005832 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005833 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00005834 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005835
Chris Lattner70d67a92008-01-06 22:42:25 +00005836 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00005837 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005838 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5839 if (!LHSTy->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +00005840 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5841 << RHS.get()->getSourceRange();
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005842 if (!RHSTy->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +00005843 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5844 << LHS.get()->getSourceRange();
5845 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
5846 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00005847 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00005848 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00005849 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5850 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005851 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
John Wiegley429bb272011-04-08 18:41:53 +00005852 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005853 // promote the null to a pointer.
John Wiegley429bb272011-04-08 18:41:53 +00005854 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005855 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00005856 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005857 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
John Wiegley429bb272011-04-08 18:41:53 +00005858 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5859 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005860 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00005861 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005862
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005863 // All objective-c pointer type analysis is done here.
5864 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5865 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00005866 if (LHS.isInvalid() || RHS.isInvalid())
5867 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005868 if (!compositeType.isNull())
5869 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005870
5871
Steve Naroff7154a772009-07-01 14:36:47 +00005872 // Handle block pointer types.
5873 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5874 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5875 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5876 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00005877 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5878 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005879 return destType;
5880 }
5881 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00005882 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00005883 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00005884 }
Steve Naroff7154a772009-07-01 14:36:47 +00005885 // We have 2 block pointer types.
5886 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5887 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005888 return LHSTy;
5889 }
Steve Naroff7154a772009-07-01 14:36:47 +00005890 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00005891 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5892 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005893
Steve Naroff7154a772009-07-01 14:36:47 +00005894 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5895 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00005896 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00005897 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00005898 // In this situation, we assume void* type. No especially good
5899 // reason, but this is what gcc does, and we do have to pick
5900 // to get a consistent AST.
5901 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00005902 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5903 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00005904 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005905 }
Steve Naroff7154a772009-07-01 14:36:47 +00005906 // The block pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00005907 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
5908 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00005909 return LHSTy;
5910 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005911
Steve Naroff7154a772009-07-01 14:36:47 +00005912 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5913 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5914 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00005915 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5916 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00005917
5918 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5919 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5920 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00005921 QualType destPointee
5922 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00005923 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005924 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005925 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005926 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005927 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005928 return destType;
5929 }
5930 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00005931 QualType destPointee
5932 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00005933 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005934 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00005935 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00005936 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00005937 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005938 return destType;
5939 }
5940
5941 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5942 // Two identical pointer types are always compatible.
5943 return LHSTy;
5944 }
5945 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5946 rhptee.getUnqualifiedType())) {
5947 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00005948 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00005949 // In this situation, we assume void* type. No especially good
5950 // reason, but this is what gcc does, and we do have to pick
5951 // to get a consistent AST.
5952 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00005953 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5954 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005955 return incompatTy;
5956 }
5957 // The pointer types are compatible.
5958 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5959 // differently qualified versions of compatible types, the result type is
5960 // a pointer to an appropriately qualified version of the *composite*
5961 // type.
5962 // FIXME: Need to calculate the composite type.
5963 // FIXME: Need to add qualifiers
John Wiegley429bb272011-04-08 18:41:53 +00005964 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
5965 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00005966 return LHSTy;
5967 }
Mike Stump1eb44332009-09-09 15:08:12 +00005968
John McCall404cd162010-11-13 01:35:44 +00005969 // GCC compatibility: soften pointer/integer mismatch. Note that
5970 // null pointers have been filtered out by this point.
Steve Naroff7154a772009-07-01 14:36:47 +00005971 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5972 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley429bb272011-04-08 18:41:53 +00005973 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5974 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00005975 return RHSTy;
5976 }
5977 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5978 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley429bb272011-04-08 18:41:53 +00005979 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5980 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00005981 return LHSTy;
5982 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00005983
Chandler Carruth82214a82011-02-18 23:54:50 +00005984 // Emit a better diagnostic if one of the expressions is a null pointer
5985 // constant and the other is not a pointer type. In this case, the user most
5986 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00005987 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00005988 return QualType();
5989
Chris Lattner70d67a92008-01-06 22:42:25 +00005990 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00005991 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00005992 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005993 return QualType();
5994}
5995
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005996/// FindCompositeObjCPointerType - Helper method to find composite type of
5997/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00005998QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00005999 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00006000 QualType LHSTy = LHS.get()->getType();
6001 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006002
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006003 // Handle things like Class and struct objc_class*. Here we case the result
6004 // to the pseudo-builtin, because that will be implicitly cast back to the
6005 // redefinition type if an attempt is made to access its fields.
6006 if (LHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00006007 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006008 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006009 return LHSTy;
6010 }
6011 if (RHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00006012 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006013 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006014 return RHSTy;
6015 }
6016 // And the same for struct objc_object* / id
6017 if (LHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00006018 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006019 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006020 return LHSTy;
6021 }
6022 if (RHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00006023 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006024 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006025 return RHSTy;
6026 }
6027 // And the same for struct objc_selector* / SEL
6028 if (Context.isObjCSelType(LHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00006029 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006030 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006031 return LHSTy;
6032 }
6033 if (Context.isObjCSelType(RHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00006034 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00006035 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006036 return RHSTy;
6037 }
6038 // Check constraints for Objective-C object pointers types.
6039 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006040
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006041 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6042 // Two identical object pointer types are always compatible.
6043 return LHSTy;
6044 }
6045 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
6046 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
6047 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006048
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006049 // If both operands are interfaces and either operand can be
6050 // assigned to the other, use that type as the composite
6051 // type. This allows
6052 // xxx ? (A*) a : (B*) b
6053 // where B is a subclass of A.
6054 //
6055 // Additionally, as for assignment, if either type is 'id'
6056 // allow silent coercion. Finally, if the types are
6057 // incompatible then make sure to use 'id' as the composite
6058 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006059
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006060 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6061 // It could return the composite type.
6062 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6063 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6064 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6065 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6066 } else if ((LHSTy->isObjCQualifiedIdType() ||
6067 RHSTy->isObjCQualifiedIdType()) &&
6068 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6069 // Need to handle "id<xx>" explicitly.
6070 // GCC allows qualified id and any Objective-C type to devolve to
6071 // id. Currently localizing to here until clear this should be
6072 // part of ObjCQualifiedIdTypesAreCompatible.
6073 compositeType = Context.getObjCIdType();
6074 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6075 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006076 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006077 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
6078 ;
6079 else {
6080 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6081 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00006082 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006083 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00006084 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6085 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006086 return incompatTy;
6087 }
6088 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00006089 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
6090 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006091 return compositeType;
6092 }
6093 // Check Objective-C object pointer types and 'void *'
6094 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6095 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6096 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6097 QualType destPointee
6098 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6099 QualType destType = Context.getPointerType(destPointee);
6100 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00006101 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006102 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00006103 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006104 return destType;
6105 }
6106 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6107 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6108 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6109 QualType destPointee
6110 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6111 QualType destType = Context.getPointerType(destPointee);
6112 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00006113 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006114 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00006115 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00006116 return destType;
6117 }
6118 return QualType();
6119}
6120
Steve Narofff69936d2007-09-16 03:34:24 +00006121/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00006122/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00006123ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00006124 SourceLocation ColonLoc,
6125 Expr *CondExpr, Expr *LHSExpr,
6126 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00006127 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6128 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00006129 OpaqueValueExpr *opaqueValue = 0;
6130 Expr *commonExpr = 0;
6131 if (LHSExpr == 0) {
6132 commonExpr = CondExpr;
6133
6134 // We usually want to apply unary conversions *before* saving, except
6135 // in the special case of a C++ l-value conditional.
6136 if (!(getLangOptions().CPlusPlus
6137 && !commonExpr->isTypeDependent()
6138 && commonExpr->getValueKind() == RHSExpr->getValueKind()
6139 && commonExpr->isGLValue()
6140 && commonExpr->isOrdinaryOrBitFieldObject()
6141 && RHSExpr->isOrdinaryOrBitFieldObject()
6142 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00006143 ExprResult commonRes = UsualUnaryConversions(commonExpr);
6144 if (commonRes.isInvalid())
6145 return ExprError();
6146 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00006147 }
6148
6149 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6150 commonExpr->getType(),
6151 commonExpr->getValueKind(),
6152 commonExpr->getObjectKind());
6153 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00006154 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006155
John McCallf89e55a2010-11-18 06:31:45 +00006156 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00006157 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00006158 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
6159 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00006160 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00006161 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6162 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006163 return ExprError();
6164
John McCall56ca35d2011-02-17 10:25:35 +00006165 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00006166 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
6167 LHS.take(), ColonLoc,
6168 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00006169
6170 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00006171 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
6172 RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00006173}
6174
John McCalle4be87e2011-01-31 23:13:11 +00006175// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00006176// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00006177// routine is it effectively iqnores the qualifiers on the top level pointee.
6178// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6179// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00006180static Sema::AssignConvertType
6181checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6182 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6183 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006184
Reid Spencer5f016e22007-07-11 17:01:13 +00006185 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00006186 const Type *lhptee, *rhptee;
6187 Qualifiers lhq, rhq;
6188 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
6189 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006190
John McCalle4be87e2011-01-31 23:13:11 +00006191 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006192
6193 // C99 6.5.16.1p1: This following citation is common to constraints
6194 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6195 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00006196 Qualifiers lq;
6197
6198 if (!lhq.compatiblyIncludes(rhq)) {
6199 // Treat address-space mismatches as fatal. TODO: address subspaces
6200 if (lhq.getAddressSpace() != rhq.getAddressSpace())
6201 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6202
John McCall22348732011-03-26 02:56:45 +00006203 // It's okay to add or remove GC qualifiers when converting to
6204 // and from void*.
6205 else if (lhq.withoutObjCGCAttr().compatiblyIncludes(rhq.withoutObjCGCAttr())
6206 && (lhptee->isVoidType() || rhptee->isVoidType()))
6207 ; // keep old
6208
John McCall86c05f32011-02-01 00:10:29 +00006209 // For GCC compatibility, other qualifier mismatches are treated
6210 // as still compatible in C.
6211 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6212 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006213
Mike Stumpeed9cac2009-02-19 03:04:26 +00006214 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6215 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00006216 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006217 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00006218 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00006219 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006220
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006221 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00006222 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00006223 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006224 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006225
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006226 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00006227 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00006228 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006229
6230 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00006231 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00006232 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00006233 }
John McCall86c05f32011-02-01 00:10:29 +00006234
Mike Stumpeed9cac2009-02-19 03:04:26 +00006235 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00006236 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00006237 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6238 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006239 // Check if the pointee types are compatible ignoring the sign.
6240 // We explicitly check for char so that we catch "char" vs
6241 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00006242 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00006243 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00006244 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00006245 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006246
Chris Lattner6a2b9262009-10-17 20:33:28 +00006247 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00006248 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00006249 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00006250 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00006251
John McCall86c05f32011-02-01 00:10:29 +00006252 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006253 // Types are compatible ignoring the sign. Qualifier incompatibility
6254 // takes priority over sign incompatibility because the sign
6255 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00006256 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006257 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00006258
John McCalle4be87e2011-01-31 23:13:11 +00006259 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006260 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006261
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006262 // If we are a multi-level pointer, it's possible that our issue is simply
6263 // one of qualification - e.g. char ** -> const char ** is not allowed. If
6264 // the eventual target type is the same and the pointers have the same
6265 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00006266 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006267 do {
John McCall86c05f32011-02-01 00:10:29 +00006268 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6269 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00006270 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006271
John McCall86c05f32011-02-01 00:10:29 +00006272 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00006273 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006274 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006275
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006276 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00006277 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006278 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00006279 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006280}
6281
John McCalle4be87e2011-01-31 23:13:11 +00006282/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00006283/// block pointer types are compatible or whether a block and normal pointer
6284/// are compatible. It is more restrict than comparing two function pointer
6285// types.
John McCalle4be87e2011-01-31 23:13:11 +00006286static Sema::AssignConvertType
6287checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
6288 QualType rhsType) {
6289 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6290 assert(rhsType.isCanonical() && "RHS not canonicalized!");
6291
Steve Naroff1c7d0672008-09-04 15:10:53 +00006292 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006293
Steve Naroff1c7d0672008-09-04 15:10:53 +00006294 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCalle4be87e2011-01-31 23:13:11 +00006295 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
6296 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006297
John McCalle4be87e2011-01-31 23:13:11 +00006298 // In C++, the types have to match exactly.
6299 if (S.getLangOptions().CPlusPlus)
6300 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006301
John McCalle4be87e2011-01-31 23:13:11 +00006302 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006303
Steve Naroff1c7d0672008-09-04 15:10:53 +00006304 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00006305 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6306 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006307
John McCalle4be87e2011-01-31 23:13:11 +00006308 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
6309 return Sema::IncompatibleBlockPointer;
6310
Steve Naroff1c7d0672008-09-04 15:10:53 +00006311 return ConvTy;
6312}
6313
John McCalle4be87e2011-01-31 23:13:11 +00006314/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006315/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00006316static Sema::AssignConvertType
6317checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6318 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
6319 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
6320
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00006321 if (lhsType->isObjCBuiltinType()) {
6322 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00006323 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
6324 !rhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00006325 return Sema::IncompatiblePointer;
6326 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00006327 }
6328 if (rhsType->isObjCBuiltinType()) {
6329 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00006330 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
6331 !lhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00006332 return Sema::IncompatiblePointer;
6333 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00006334 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006335 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006336 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006337 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006338 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006339
John McCalle4be87e2011-01-31 23:13:11 +00006340 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
6341 return Sema::CompatiblePointerDiscardsQualifiers;
6342
6343 if (S.Context.typesAreCompatible(lhsType, rhsType))
6344 return Sema::Compatible;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006345 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00006346 return Sema::IncompatibleObjCQualifiedId;
6347 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00006348}
6349
John McCall1c23e912010-11-16 02:32:08 +00006350Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00006351Sema::CheckAssignmentConstraints(SourceLocation Loc,
6352 QualType lhsType, QualType rhsType) {
John McCall1c23e912010-11-16 02:32:08 +00006353 // Fake up an opaque expression. We don't actually care about what
6354 // cast operations are required, so if CheckAssignmentConstraints
6355 // adds casts to this they'll be wasted, but fortunately that doesn't
6356 // usually happen on valid code.
Douglas Gregorb608b982011-01-28 02:26:04 +00006357 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00006358 ExprResult rhsPtr = &rhs;
John McCall1c23e912010-11-16 02:32:08 +00006359 CastKind K = CK_Invalid;
6360
6361 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
6362}
6363
Mike Stumpeed9cac2009-02-19 03:04:26 +00006364/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6365/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00006366/// pointers. Here are some objectionable examples that GCC considers warnings:
6367///
6368/// int a, *pint;
6369/// short *pshort;
6370/// struct foo *pfoo;
6371///
6372/// pint = pshort; // warning: assignment from incompatible pointer type
6373/// a = pint; // warning: assignment makes integer from pointer without a cast
6374/// pint = a; // warning: assignment makes pointer from integer without a cast
6375/// pint = pfoo; // warning: assignment from incompatible pointer type
6376///
6377/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00006378/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00006379///
John McCalldaa8e4e2010-11-15 09:13:47 +00006380/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00006381Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00006382Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCalldaa8e4e2010-11-15 09:13:47 +00006383 CastKind &Kind) {
John Wiegley429bb272011-04-08 18:41:53 +00006384 QualType rhsType = rhs.get()->getType();
John McCall1c23e912010-11-16 02:32:08 +00006385
Chris Lattnerfc144e22008-01-04 23:18:45 +00006386 // Get canonical types. We're not formatting these types, just comparing
6387 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00006388 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
6389 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006390
John McCallb6cfa242011-01-31 22:28:28 +00006391 // Common case: no conversion required.
John McCalldaa8e4e2010-11-15 09:13:47 +00006392 if (lhsType == rhsType) {
6393 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00006394 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00006395 }
6396
Douglas Gregor9d293df2008-10-28 00:22:11 +00006397 // If the left-hand side is a reference type, then we are in a
6398 // (rare!) case where we've allowed the use of references in C,
6399 // e.g., as a parameter type in a built-in function. In this case,
6400 // just make sure that the type referenced is compatible with the
6401 // right-hand side type. The caller is responsible for adjusting
6402 // lhsType so that the resulting expression does not have reference
6403 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00006404 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006405 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
6406 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00006407 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006408 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00006409 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00006410 }
John McCallb6cfa242011-01-31 22:28:28 +00006411
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006412 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6413 // to the same ExtVector type.
6414 if (lhsType->isExtVectorType()) {
6415 if (rhsType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00006416 return Incompatible;
6417 if (rhsType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00006418 // CK_VectorSplat does T -> vector T, so first cast to the
6419 // element type.
6420 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
6421 if (elType != rhsType) {
6422 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley429bb272011-04-08 18:41:53 +00006423 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00006424 }
6425 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006426 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006427 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006428 }
Mike Stump1eb44332009-09-09 15:08:12 +00006429
John McCallb6cfa242011-01-31 22:28:28 +00006430 // Conversions to or from vector type.
Nate Begemanbe2341d2008-07-14 18:02:46 +00006431 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor255210e2010-08-06 10:14:59 +00006432 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00006433 // Allow assignments of an AltiVec vector type to an equivalent GCC
6434 // vector type and vice versa
6435 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6436 Kind = CK_BitCast;
6437 return Compatible;
6438 }
6439
Douglas Gregor255210e2010-08-06 10:14:59 +00006440 // If we are allowing lax vector conversions, and LHS and RHS are both
6441 // vectors, the total size only needs to be the same. This is a bitcast;
6442 // no bits are changed but the result type is different.
6443 if (getLangOptions().LaxVectorConversions &&
John McCalldaa8e4e2010-11-15 09:13:47 +00006444 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00006445 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006446 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00006447 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00006448 }
6449 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006450 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006451
John McCallb6cfa242011-01-31 22:28:28 +00006452 // Arithmetic conversions.
Douglas Gregor88623ad2010-05-23 21:53:47 +00006453 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00006454 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall1c23e912010-11-16 02:32:08 +00006455 Kind = PrepareScalarCast(*this, rhs, lhsType);
Reid Spencer5f016e22007-07-11 17:01:13 +00006456 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006457 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006458
John McCallb6cfa242011-01-31 22:28:28 +00006459 // Conversions to normal pointers.
6460 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
6461 // U* -> T*
John McCalldaa8e4e2010-11-15 09:13:47 +00006462 if (isa<PointerType>(rhsType)) {
6463 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00006464 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalldaa8e4e2010-11-15 09:13:47 +00006465 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006466
John McCallb6cfa242011-01-31 22:28:28 +00006467 // int -> T*
6468 if (rhsType->isIntegerType()) {
6469 Kind = CK_IntegralToPointer; // FIXME: null?
6470 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00006471 }
John McCallb6cfa242011-01-31 22:28:28 +00006472
6473 // C pointers are not compatible with ObjC object pointers,
6474 // with two exceptions:
6475 if (isa<ObjCObjectPointerType>(rhsType)) {
6476 // - conversions to void*
6477 if (lhsPointer->getPointeeType()->isVoidType()) {
6478 Kind = CK_AnyPointerToObjCPointerCast;
6479 return Compatible;
6480 }
6481
6482 // - conversions from 'Class' to the redefinition type
6483 if (rhsType->isObjCClassType() &&
6484 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006485 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00006486 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006487 }
Steve Naroffb4406862008-09-29 18:10:17 +00006488
John McCallb6cfa242011-01-31 22:28:28 +00006489 Kind = CK_BitCast;
6490 return IncompatiblePointer;
6491 }
6492
6493 // U^ -> void*
6494 if (rhsType->getAs<BlockPointerType>()) {
6495 if (lhsPointer->getPointeeType()->isVoidType()) {
6496 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00006497 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006498 }
Steve Naroffb4406862008-09-29 18:10:17 +00006499 }
John McCallb6cfa242011-01-31 22:28:28 +00006500
Steve Naroff1c7d0672008-09-04 15:10:53 +00006501 return Incompatible;
6502 }
6503
John McCallb6cfa242011-01-31 22:28:28 +00006504 // Conversions to block pointers.
Steve Naroff1c7d0672008-09-04 15:10:53 +00006505 if (isa<BlockPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006506 // U^ -> T^
6507 if (rhsType->isBlockPointerType()) {
6508 Kind = CK_AnyPointerToBlockPointerCast;
John McCalle4be87e2011-01-31 23:13:11 +00006509 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00006510 }
6511
6512 // int or null -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00006513 if (rhsType->isIntegerType()) {
6514 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00006515 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00006516 }
6517
John McCallb6cfa242011-01-31 22:28:28 +00006518 // id -> T^
6519 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6520 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00006521 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006522 }
Steve Naroffb4406862008-09-29 18:10:17 +00006523
John McCallb6cfa242011-01-31 22:28:28 +00006524 // void* -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00006525 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00006526 if (RHSPT->getPointeeType()->isVoidType()) {
6527 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00006528 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006529 }
John McCalldaa8e4e2010-11-15 09:13:47 +00006530
Chris Lattnerfc144e22008-01-04 23:18:45 +00006531 return Incompatible;
6532 }
6533
John McCallb6cfa242011-01-31 22:28:28 +00006534 // Conversions to Objective-C pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00006535 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006536 // A* -> B*
6537 if (rhsType->isObjCObjectPointerType()) {
6538 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00006539 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00006540 }
6541
6542 // int or null -> A*
John McCalldaa8e4e2010-11-15 09:13:47 +00006543 if (rhsType->isIntegerType()) {
6544 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00006545 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00006546 }
6547
John McCallb6cfa242011-01-31 22:28:28 +00006548 // In general, C pointers are not compatible with ObjC object pointers,
6549 // with two exceptions:
Steve Naroff14108da2009-07-10 23:34:53 +00006550 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006551 // - conversions from 'void*'
6552 if (rhsType->isVoidPointerType()) {
6553 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006554 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006555 }
6556
6557 // - conversions to 'Class' from its redefinition type
6558 if (lhsType->isObjCClassType() &&
6559 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6560 Kind = CK_BitCast;
6561 return Compatible;
6562 }
6563
6564 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00006565 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00006566 }
John McCallb6cfa242011-01-31 22:28:28 +00006567
6568 // T^ -> A*
6569 if (rhsType->isBlockPointerType()) {
6570 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00006571 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00006572 }
6573
Steve Naroff14108da2009-07-10 23:34:53 +00006574 return Incompatible;
6575 }
John McCallb6cfa242011-01-31 22:28:28 +00006576
6577 // Conversions from pointers that are not covered by the above.
Chris Lattner78eca282008-04-07 06:49:41 +00006578 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006579 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00006580 if (lhsType == Context.BoolTy) {
6581 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006582 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006583 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006584
John McCallb6cfa242011-01-31 22:28:28 +00006585 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00006586 if (lhsType->isIntegerType()) {
6587 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006588 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006589 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006590
Chris Lattnerfc144e22008-01-04 23:18:45 +00006591 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00006592 }
John McCallb6cfa242011-01-31 22:28:28 +00006593
6594 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff14108da2009-07-10 23:34:53 +00006595 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00006596 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00006597 if (lhsType == Context.BoolTy) {
6598 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00006599 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006600 }
Steve Naroff14108da2009-07-10 23:34:53 +00006601
John McCallb6cfa242011-01-31 22:28:28 +00006602 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00006603 if (lhsType->isIntegerType()) {
6604 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00006605 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00006606 }
6607
Steve Naroff14108da2009-07-10 23:34:53 +00006608 return Incompatible;
6609 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00006610
John McCallb6cfa242011-01-31 22:28:28 +00006611 // struct A -> struct B
Chris Lattnerfc144e22008-01-04 23:18:45 +00006612 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006613 if (Context.typesAreCompatible(lhsType, rhsType)) {
6614 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00006615 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00006616 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006617 }
John McCallb6cfa242011-01-31 22:28:28 +00006618
Reid Spencer5f016e22007-07-11 17:01:13 +00006619 return Incompatible;
6620}
6621
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006622/// \brief Constructs a transparent union from an expression that is
6623/// used to initialize the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00006624static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006625 QualType UnionType, FieldDecl *Field) {
6626 // Build an initializer list that designates the appropriate member
6627 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00006628 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00006629 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00006630 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006631 SourceLocation());
6632 Initializer->setType(UnionType);
6633 Initializer->setInitializedFieldInUnion(Field);
6634
6635 // Build a compound literal constructing a value of the transparent
6636 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00006637 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00006638 EResult = S.Owned(
6639 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6640 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006641}
6642
6643Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00006644Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
6645 QualType FromType = rExpr.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006646
Mike Stump1eb44332009-09-09 15:08:12 +00006647 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006648 // transparent_union GCC extension.
6649 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006650 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006651 return Incompatible;
6652
6653 // The field to initialize within the transparent union.
6654 RecordDecl *UD = UT->getDecl();
6655 FieldDecl *InitField = 0;
6656 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006657 for (RecordDecl::field_iterator it = UD->field_begin(),
6658 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006659 it != itend; ++it) {
6660 if (it->getType()->isPointerType()) {
6661 // If the transparent union contains a pointer type, we allow:
6662 // 1) void pointer
6663 // 2) null pointer constant
6664 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00006665 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006666 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006667 InitField = *it;
6668 break;
6669 }
Mike Stump1eb44332009-09-09 15:08:12 +00006670
John Wiegley429bb272011-04-08 18:41:53 +00006671 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006672 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00006673 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006674 InitField = *it;
6675 break;
6676 }
6677 }
6678
John McCalldaa8e4e2010-11-15 09:13:47 +00006679 CastKind Kind = CK_Invalid;
John Wiegley429bb272011-04-08 18:41:53 +00006680 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006681 == Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +00006682 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006683 InitField = *it;
6684 break;
6685 }
6686 }
6687
6688 if (!InitField)
6689 return Incompatible;
6690
John Wiegley429bb272011-04-08 18:41:53 +00006691 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00006692 return Compatible;
6693}
6694
Chris Lattner5cf216b2008-01-04 18:04:52 +00006695Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00006696Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00006697 if (getLangOptions().CPlusPlus) {
6698 if (!lhsType->isRecordType()) {
6699 // C++ 5.17p3: If the left operand is not of class type, the
6700 // expression is implicitly converted (C++ 4) to the
6701 // cv-unqualified type of the left operand.
John Wiegley429bb272011-04-08 18:41:53 +00006702 ExprResult Res = PerformImplicitConversion(rExpr.get(),
6703 lhsType.getUnqualifiedType(),
6704 AA_Assigning);
6705 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00006706 return Incompatible;
John Wiegley429bb272011-04-08 18:41:53 +00006707 rExpr = move(Res);
Chris Lattner2c4463f2009-04-12 09:02:39 +00006708 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00006709 }
6710
6711 // FIXME: Currently, we fall through and treat C++ classes like C
6712 // structures.
John McCallf6a16482010-12-04 03:47:34 +00006713 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00006714
Steve Naroff529a4ad2007-11-27 17:58:44 +00006715 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6716 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00006717 if ((lhsType->isPointerType() ||
6718 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00006719 lhsType->isBlockPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00006720 && rExpr.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006721 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00006722 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00006723 return Compatible;
6724 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006725
Chris Lattner943140e2007-10-16 02:55:40 +00006726 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00006727 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00006728 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00006729 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00006730 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00006731 // Suppress this for references: C++ 8.5.3p5.
John Wiegley429bb272011-04-08 18:41:53 +00006732 if (!lhsType->isReferenceType()) {
6733 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
6734 if (rExpr.isInvalid())
6735 return Incompatible;
6736 }
Steve Narofff1120de2007-08-24 22:33:52 +00006737
John McCalldaa8e4e2010-11-15 09:13:47 +00006738 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006739 Sema::AssignConvertType result =
John McCall1c23e912010-11-16 02:32:08 +00006740 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006741
Steve Narofff1120de2007-08-24 22:33:52 +00006742 // C99 6.5.16.1p2: The value of the right operand is converted to the
6743 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00006744 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6745 // so that we can use references in built-in functions even in C.
6746 // The getNonReferenceType() call makes sure that the resulting expression
6747 // does not have reference type.
John Wiegley429bb272011-04-08 18:41:53 +00006748 if (result != Incompatible && rExpr.get()->getType() != lhsType)
6749 rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00006750 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00006751}
6752
John Wiegley429bb272011-04-08 18:41:53 +00006753QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006754 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley429bb272011-04-08 18:41:53 +00006755 << lex.get()->getType() << rex.get()->getType()
6756 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00006757 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006758}
6759
John Wiegley429bb272011-04-08 18:41:53 +00006760QualType Sema::CheckVectorOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00006761 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006762 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00006763 QualType lhsType =
John Wiegley429bb272011-04-08 18:41:53 +00006764 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattnerb77792e2008-07-26 22:17:49 +00006765 QualType rhsType =
John Wiegley429bb272011-04-08 18:41:53 +00006766 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006767
Nate Begemanbe2341d2008-07-14 18:02:46 +00006768 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00006769 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00006770 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00006771
Nate Begemanbe2341d2008-07-14 18:02:46 +00006772 // Handle the case of a vector & extvector type of the same size and element
6773 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006774 if (getLangOptions().LaxVectorConversions) {
John McCall183700f2009-09-21 23:43:11 +00006775 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth629f9e42010-08-30 07:36:24 +00006776 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00006777 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006778 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregor26bcf672010-05-19 03:21:00 +00006779 if (lhsType->isExtVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006780 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006781 return lhsType;
6782 }
6783
John Wiegley429bb272011-04-08 18:41:53 +00006784 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006785 return rhsType;
Eric Christophere84f9eb2010-08-26 00:42:16 +00006786 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6787 // If we are allowing lax vector conversions, and LHS and RHS are both
6788 // vectors, the total size only needs to be the same. This is a
6789 // bitcast; no bits are changed but the result type is different.
John Wiegley429bb272011-04-08 18:41:53 +00006790 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Eric Christophere84f9eb2010-08-26 00:42:16 +00006791 return lhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006792 }
Eric Christophere84f9eb2010-08-26 00:42:16 +00006793 }
Chandler Carruth629f9e42010-08-30 07:36:24 +00006794 }
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00006795 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006796
Douglas Gregor255210e2010-08-06 10:14:59 +00006797 // Handle the case of equivalent AltiVec and GCC vector types
6798 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6799 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John Wiegley429bb272011-04-08 18:41:53 +00006800 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor255210e2010-08-06 10:14:59 +00006801 return rhsType;
6802 }
6803
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006804 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6805 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6806 bool swapped = false;
6807 if (rhsType->isExtVectorType()) {
6808 swapped = true;
6809 std::swap(rex, lex);
6810 std::swap(rhsType, lhsType);
6811 }
Mike Stump1eb44332009-09-09 15:08:12 +00006812
Nate Begemandde25982009-06-28 19:12:57 +00006813 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00006814 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006815 QualType EltTy = LV->getElementType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00006816 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006817 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6818 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00006819 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006820 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00006821 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006822 if (swapped) std::swap(rex, lex);
6823 return lhsType;
6824 }
6825 }
6826 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6827 rhsType->isRealFloatingType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00006828 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6829 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00006830 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00006831 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00006832 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00006833 if (swapped) std::swap(rex, lex);
6834 return lhsType;
6835 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00006836 }
6837 }
Mike Stump1eb44332009-09-09 15:08:12 +00006838
Nate Begemandde25982009-06-28 19:12:57 +00006839 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006840 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley429bb272011-04-08 18:41:53 +00006841 << lex.get()->getType() << rex.get()->getType()
6842 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006843 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00006844}
6845
Chris Lattner7ef655a2010-01-12 21:23:57 +00006846QualType Sema::CheckMultiplyDivideOperands(
John Wiegley429bb272011-04-08 18:41:53 +00006847 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
6848 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006849 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006850
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006851 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00006852 if (lex.isInvalid() || rex.isInvalid())
6853 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006854
John Wiegley429bb272011-04-08 18:41:53 +00006855 if (!lex.get()->getType()->isArithmeticType() ||
6856 !rex.get()->getType()->isArithmeticType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00006857 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006858
Chris Lattner7ef655a2010-01-12 21:23:57 +00006859 // Check for division by zero.
6860 if (isDiv &&
John Wiegley429bb272011-04-08 18:41:53 +00006861 rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6862 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
6863 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006864
Chris Lattner7ef655a2010-01-12 21:23:57 +00006865 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006866}
6867
Chris Lattner7ef655a2010-01-12 21:23:57 +00006868QualType Sema::CheckRemainderOperands(
John Wiegley429bb272011-04-08 18:41:53 +00006869 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
6870 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
6871 if (lex.get()->getType()->hasIntegerRepresentation() &&
6872 rex.get()->getType()->hasIntegerRepresentation())
Daniel Dunbar523aa602009-01-05 22:55:36 +00006873 return CheckVectorOperands(Loc, lex, rex);
6874 return InvalidOperands(Loc, lex, rex);
6875 }
Steve Naroff90045e82007-07-13 23:32:42 +00006876
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006877 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00006878 if (lex.isInvalid() || rex.isInvalid())
6879 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006880
John Wiegley429bb272011-04-08 18:41:53 +00006881 if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00006882 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006883
Chris Lattner7ef655a2010-01-12 21:23:57 +00006884 // Check for remainder by zero.
John Wiegley429bb272011-04-08 18:41:53 +00006885 if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6886 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
6887 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006888
Chris Lattner7ef655a2010-01-12 21:23:57 +00006889 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006890}
6891
Chris Lattner7ef655a2010-01-12 21:23:57 +00006892QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00006893 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
6894 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006895 QualType compType = CheckVectorOperands(Loc, lex, rex);
6896 if (CompLHSTy) *CompLHSTy = compType;
6897 return compType;
6898 }
Steve Naroff49b45262007-07-13 16:58:59 +00006899
Eli Friedmanab3a8522009-03-28 01:22:36 +00006900 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00006901 if (lex.isInvalid() || rex.isInvalid())
6902 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006903
Reid Spencer5f016e22007-07-11 17:01:13 +00006904 // handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00006905 if (lex.get()->getType()->isArithmeticType() &&
6906 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006907 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006908 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006909 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006910
Eli Friedmand72d16e2008-05-18 18:08:51 +00006911 // Put any potential pointer into PExp
John Wiegley429bb272011-04-08 18:41:53 +00006912 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006913 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00006914 std::swap(PExp, IExp);
6915
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006916 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006917
Eli Friedmand72d16e2008-05-18 18:08:51 +00006918 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00006919 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00006920
Chris Lattnerb5f15622009-04-24 23:50:08 +00006921 // Check for arithmetic on pointers to incomplete types.
6922 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006923 if (getLangOptions().CPlusPlus) {
6924 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley429bb272011-04-08 18:41:53 +00006925 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006926 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00006927 }
Douglas Gregore7450f52009-03-24 19:52:54 +00006928
6929 // GNU extension: arithmetic on pointer to void
6930 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley429bb272011-04-08 18:41:53 +00006931 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00006932 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006933 if (getLangOptions().CPlusPlus) {
6934 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley429bb272011-04-08 18:41:53 +00006935 << lex.get()->getType() << lex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00006936 return QualType();
6937 }
6938
6939 // GNU extension: arithmetic on pointer to function
6940 Diag(Loc, diag::ext_gnu_ptr_func_arith)
John Wiegley429bb272011-04-08 18:41:53 +00006941 << lex.get()->getType() << lex.get()->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00006942 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00006943 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00006944 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00006945 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00006946 PExp->getType()->isObjCObjectPointerType()) &&
6947 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00006948 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6949 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00006950 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00006951 return QualType();
6952 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00006953 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00006954 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00006955 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6956 << PointeeTy << PExp->getSourceRange();
6957 return QualType();
6958 }
Mike Stump1eb44332009-09-09 15:08:12 +00006959
Eli Friedmanab3a8522009-03-28 01:22:36 +00006960 if (CompLHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00006961 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman04e83572009-08-20 04:21:42 +00006962 if (LHSTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +00006963 LHSTy = lex.get()->getType();
Eli Friedman04e83572009-08-20 04:21:42 +00006964 if (LHSTy->isPromotableIntegerType())
6965 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00006966 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00006967 *CompLHSTy = LHSTy;
6968 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00006969 return PExp->getType();
6970 }
6971 }
6972
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006973 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006974}
6975
Chris Lattnereca7be62008-04-07 05:30:13 +00006976// C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00006977QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00006978 SourceLocation Loc, QualType* CompLHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00006979 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006980 QualType compType = CheckVectorOperands(Loc, lex, rex);
6981 if (CompLHSTy) *CompLHSTy = compType;
6982 return compType;
6983 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006984
Eli Friedmanab3a8522009-03-28 01:22:36 +00006985 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00006986 if (lex.isInvalid() || rex.isInvalid())
6987 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006988
Chris Lattner6e4ab612007-12-09 21:53:25 +00006989 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006990
Chris Lattner6e4ab612007-12-09 21:53:25 +00006991 // Handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00006992 if (lex.get()->getType()->isArithmeticType() &&
6993 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006994 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006995 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006996 }
Mike Stump1eb44332009-09-09 15:08:12 +00006997
Chris Lattner6e4ab612007-12-09 21:53:25 +00006998 // Either ptr - int or ptr - ptr.
John Wiegley429bb272011-04-08 18:41:53 +00006999 if (lex.get()->getType()->isAnyPointerType()) {
7000 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007001
Douglas Gregore7450f52009-03-24 19:52:54 +00007002 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00007003
Douglas Gregore7450f52009-03-24 19:52:54 +00007004 bool ComplainAboutVoid = false;
7005 Expr *ComplainAboutFunc = 0;
7006 if (lpointee->isVoidType()) {
7007 if (getLangOptions().CPlusPlus) {
7008 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley429bb272011-04-08 18:41:53 +00007009 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00007010 return QualType();
7011 }
7012
7013 // GNU C extension: arithmetic on pointer to void
7014 ComplainAboutVoid = true;
7015 } else if (lpointee->isFunctionType()) {
7016 if (getLangOptions().CPlusPlus) {
7017 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley429bb272011-04-08 18:41:53 +00007018 << lex.get()->getType() << lex.get()->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00007019 return QualType();
7020 }
Douglas Gregore7450f52009-03-24 19:52:54 +00007021
7022 // GNU C extension: arithmetic on pointer to function
John Wiegley429bb272011-04-08 18:41:53 +00007023 ComplainAboutFunc = lex.get();
Douglas Gregore7450f52009-03-24 19:52:54 +00007024 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00007025 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00007026 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley429bb272011-04-08 18:41:53 +00007027 << lex.get()->getSourceRange()
7028 << lex.get()->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00007029 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00007030
Chris Lattnerb5f15622009-04-24 23:50:08 +00007031 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00007032 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00007033 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley429bb272011-04-08 18:41:53 +00007034 << lpointee << lex.get()->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00007035 return QualType();
7036 }
Mike Stump1eb44332009-09-09 15:08:12 +00007037
Chris Lattner6e4ab612007-12-09 21:53:25 +00007038 // The result type of a pointer-int computation is the pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00007039 if (rex.get()->getType()->isIntegerType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00007040 if (ComplainAboutVoid)
7041 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley429bb272011-04-08 18:41:53 +00007042 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00007043 if (ComplainAboutFunc)
7044 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00007045 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00007046 << ComplainAboutFunc->getSourceRange();
7047
John Wiegley429bb272011-04-08 18:41:53 +00007048 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
7049 return lex.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00007050 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007051
Chris Lattner6e4ab612007-12-09 21:53:25 +00007052 // Handle pointer-pointer subtractions.
John Wiegley429bb272011-04-08 18:41:53 +00007053 if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00007054 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007055
Douglas Gregore7450f52009-03-24 19:52:54 +00007056 // RHS must be a completely-type object type.
7057 // Handle the GNU void* extension.
7058 if (rpointee->isVoidType()) {
7059 if (getLangOptions().CPlusPlus) {
7060 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley429bb272011-04-08 18:41:53 +00007061 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00007062 return QualType();
7063 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007064
Douglas Gregore7450f52009-03-24 19:52:54 +00007065 ComplainAboutVoid = true;
7066 } else if (rpointee->isFunctionType()) {
7067 if (getLangOptions().CPlusPlus) {
7068 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley429bb272011-04-08 18:41:53 +00007069 << rex.get()->getType() << rex.get()->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00007070 return QualType();
7071 }
Douglas Gregore7450f52009-03-24 19:52:54 +00007072
7073 // GNU extension: arithmetic on pointer to function
7074 if (!ComplainAboutFunc)
John Wiegley429bb272011-04-08 18:41:53 +00007075 ComplainAboutFunc = rex.get();
Douglas Gregore7450f52009-03-24 19:52:54 +00007076 } else if (!rpointee->isDependentType() &&
7077 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00007078 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley429bb272011-04-08 18:41:53 +00007079 << rex.get()->getSourceRange()
7080 << rex.get()->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00007081 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007082
Eli Friedman88d936b2009-05-16 13:54:38 +00007083 if (getLangOptions().CPlusPlus) {
7084 // Pointee types must be the same: C++ [expr.add]
7085 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7086 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley429bb272011-04-08 18:41:53 +00007087 << lex.get()->getType() << rex.get()->getType()
7088 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman88d936b2009-05-16 13:54:38 +00007089 return QualType();
7090 }
7091 } else {
7092 // Pointee types must be compatible C99 6.5.6p3
7093 if (!Context.typesAreCompatible(
7094 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7095 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7096 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley429bb272011-04-08 18:41:53 +00007097 << lex.get()->getType() << rex.get()->getType()
7098 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman88d936b2009-05-16 13:54:38 +00007099 return QualType();
7100 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00007101 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007102
Douglas Gregore7450f52009-03-24 19:52:54 +00007103 if (ComplainAboutVoid)
7104 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley429bb272011-04-08 18:41:53 +00007105 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00007106 if (ComplainAboutFunc)
7107 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00007108 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00007109 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00007110
John Wiegley429bb272011-04-08 18:41:53 +00007111 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00007112 return Context.getPointerDiffType();
7113 }
7114 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007115
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007116 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007117}
7118
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007119static bool isScopedEnumerationType(QualType T) {
7120 if (const EnumType *ET = dyn_cast<EnumType>(T))
7121 return ET->getDecl()->isScoped();
7122 return false;
7123}
7124
John Wiegley429bb272011-04-08 18:41:53 +00007125static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth21206d52011-02-23 23:34:11 +00007126 SourceLocation Loc, unsigned Opc,
7127 QualType LHSTy) {
7128 llvm::APSInt Right;
7129 // Check right/shifter operand
John Wiegley429bb272011-04-08 18:41:53 +00007130 if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00007131 return;
7132
7133 if (Right.isNegative()) {
John Wiegley429bb272011-04-08 18:41:53 +00007134 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00007135 S.PDiag(diag::warn_shift_negative)
John Wiegley429bb272011-04-08 18:41:53 +00007136 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00007137 return;
7138 }
7139 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley429bb272011-04-08 18:41:53 +00007140 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00007141 if (Right.uge(LeftBits)) {
John Wiegley429bb272011-04-08 18:41:53 +00007142 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00007143 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley429bb272011-04-08 18:41:53 +00007144 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00007145 return;
7146 }
7147 if (Opc != BO_Shl)
7148 return;
7149
7150 // When left shifting an ICE which is signed, we can check for overflow which
7151 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7152 // integers have defined behavior modulo one more than the maximum value
7153 // representable in the result type, so never warn for those.
7154 llvm::APSInt Left;
John Wiegley429bb272011-04-08 18:41:53 +00007155 if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth21206d52011-02-23 23:34:11 +00007156 LHSTy->hasUnsignedIntegerRepresentation())
7157 return;
7158 llvm::APInt ResultBits =
7159 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7160 if (LeftBits.uge(ResultBits))
7161 return;
7162 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7163 Result = Result.shl(Right);
7164
7165 // If we are only missing a sign bit, this is less likely to result in actual
7166 // bugs -- if the result is cast back to an unsigned type, it will have the
7167 // expected value. Thus we place this behind a different warning that can be
7168 // turned off separately if needed.
7169 if (LeftBits == ResultBits - 1) {
7170 S.Diag(Loc, diag::warn_shift_result_overrides_sign_bit)
7171 << Result.toString(10) << LHSTy
John Wiegley429bb272011-04-08 18:41:53 +00007172 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00007173 return;
7174 }
7175
7176 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7177 << Result.toString(10) << Result.getMinSignedBits() << LHSTy
John Wiegley429bb272011-04-08 18:41:53 +00007178 << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00007179}
7180
Chris Lattnereca7be62008-04-07 05:30:13 +00007181// C99 6.5.7
John Wiegley429bb272011-04-08 18:41:53 +00007182QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Chandler Carruth21206d52011-02-23 23:34:11 +00007183 unsigned Opc, bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00007184 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley429bb272011-04-08 18:41:53 +00007185 if (!lex.get()->getType()->hasIntegerRepresentation() ||
7186 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007187 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007188
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007189 // C++0x: Don't allow scoped enums. FIXME: Use something better than
7190 // hasIntegerRepresentation() above instead of this.
John Wiegley429bb272011-04-08 18:41:53 +00007191 if (isScopedEnumerationType(lex.get()->getType()) ||
7192 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007193 return InvalidOperands(Loc, lex, rex);
7194 }
7195
Nate Begeman2207d792009-10-25 02:26:48 +00007196 // Vector shifts promote their scalar inputs to vector type.
John Wiegley429bb272011-04-08 18:41:53 +00007197 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Nate Begeman2207d792009-10-25 02:26:48 +00007198 return CheckVectorOperands(Loc, lex, rex);
7199
Chris Lattnerca5eede2007-12-12 05:47:28 +00007200 // Shifts don't perform usual arithmetic conversions, they just do integer
7201 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00007202
John McCall1bc80af2010-12-16 19:28:59 +00007203 // For the LHS, do usual unary conversions, but then reset them away
7204 // if this is a compound assignment.
John Wiegley429bb272011-04-08 18:41:53 +00007205 ExprResult old_lex = lex;
7206 lex = UsualUnaryConversions(lex.take());
7207 if (lex.isInvalid())
7208 return QualType();
7209 QualType LHSTy = lex.get()->getType();
John McCall1bc80af2010-12-16 19:28:59 +00007210 if (isCompAssign) lex = old_lex;
7211
7212 // The RHS is simpler.
John Wiegley429bb272011-04-08 18:41:53 +00007213 rex = UsualUnaryConversions(rex.take());
7214 if (rex.isInvalid())
7215 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007216
Ryan Flynnd0439682009-08-07 16:20:20 +00007217 // Sanity-check shift operands
Chandler Carruth21206d52011-02-23 23:34:11 +00007218 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnd0439682009-08-07 16:20:20 +00007219
Chris Lattnerca5eede2007-12-12 05:47:28 +00007220 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00007221 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007222}
7223
Chandler Carruth99919472010-07-10 12:30:03 +00007224static bool IsWithinTemplateSpecialization(Decl *D) {
7225 if (DeclContext *DC = D->getDeclContext()) {
7226 if (isa<ClassTemplateSpecializationDecl>(DC))
7227 return true;
7228 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7229 return FD->isFunctionTemplateSpecialization();
7230 }
7231 return false;
7232}
7233
Douglas Gregor0c6db942009-05-04 06:07:12 +00007234// C99 6.5.8, C++ [expr.rel]
John Wiegley429bb272011-04-08 18:41:53 +00007235QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00007236 unsigned OpaqueOpc, bool isRelational) {
John McCall2de56d12010-08-25 11:45:40 +00007237 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00007238
Chris Lattner02dd4b12009-12-05 05:40:13 +00007239 // Handle vector comparisons separately.
John Wiegley429bb272011-04-08 18:41:53 +00007240 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007241 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007242
John Wiegley429bb272011-04-08 18:41:53 +00007243 QualType lType = lex.get()->getType();
7244 QualType rType = rex.get()->getType();
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007245
John Wiegley429bb272011-04-08 18:41:53 +00007246 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
7247 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00007248 QualType LHSStrippedType = LHSStripped->getType();
7249 QualType RHSStrippedType = RHSStripped->getType();
7250
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007251
7252
Chandler Carruth543cb652011-02-17 08:37:06 +00007253 // Two different enums will raise a warning when compared.
7254 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
7255 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
7256 if (LHSEnumType->getDecl()->getIdentifier() &&
7257 RHSEnumType->getDecl()->getIdentifier() &&
7258 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
7259 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7260 << LHSStrippedType << RHSStrippedType
John Wiegley429bb272011-04-08 18:41:53 +00007261 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth543cb652011-02-17 08:37:06 +00007262 }
7263 }
7264 }
7265
Douglas Gregor8eee1192010-06-22 22:12:46 +00007266 if (!lType->hasFloatingRepresentation() &&
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00007267 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley429bb272011-04-08 18:41:53 +00007268 !lex.get()->getLocStart().isMacroID() &&
7269 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00007270 // For non-floating point types, check for self-comparisons of the form
7271 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7272 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00007273 //
7274 // NOTE: Don't warn about comparison expressions resulting from macro
7275 // expansion. Also don't warn about comparisons which are only self
7276 // comparisons within a template specialization. The warnings should catch
7277 // obvious cases in the definition of the template anyways. The idea is to
7278 // warn when the typed comparison operator will always evaluate to the same
7279 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00007280 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00007281 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00007282 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00007283 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00007284 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00007285 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00007286 << (Opc == BO_EQ
7287 || Opc == BO_LE
7288 || Opc == BO_GE));
Douglas Gregord64fdd02010-06-08 19:50:34 +00007289 } else if (lType->isArrayType() && rType->isArrayType() &&
7290 !DRL->getDecl()->getType()->isReferenceType() &&
7291 !DRR->getDecl()->getType()->isReferenceType()) {
7292 // what is it always going to eval to?
7293 char always_evals_to;
7294 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007295 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00007296 always_evals_to = 0; // false
7297 break;
John McCall2de56d12010-08-25 11:45:40 +00007298 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00007299 always_evals_to = 1; // true
7300 break;
7301 default:
7302 // best we can say is 'a constant'
7303 always_evals_to = 2; // e.g. array1 <= array2
7304 break;
7305 }
Ted Kremenek351ba912011-02-23 01:52:04 +00007306 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00007307 << 1 // array
7308 << always_evals_to);
7309 }
7310 }
Chandler Carruth99919472010-07-10 12:30:03 +00007311 }
Mike Stump1eb44332009-09-09 15:08:12 +00007312
Chris Lattner55660a72009-03-08 19:39:53 +00007313 if (isa<CastExpr>(LHSStripped))
7314 LHSStripped = LHSStripped->IgnoreParenCasts();
7315 if (isa<CastExpr>(RHSStripped))
7316 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00007317
Chris Lattner55660a72009-03-08 19:39:53 +00007318 // Warn about comparisons against a string constant (unless the other
7319 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00007320 Expr *literalString = 0;
7321 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00007322 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007323 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007324 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00007325 literalString = lex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007326 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00007327 } else if ((isa<StringLiteral>(RHSStripped) ||
7328 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007329 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007330 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00007331 literalString = rex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00007332 literalStringStripped = RHSStripped;
7333 }
7334
7335 if (literalString) {
7336 std::string resultComparison;
7337 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007338 case BO_LT: resultComparison = ") < 0"; break;
7339 case BO_GT: resultComparison = ") > 0"; break;
7340 case BO_LE: resultComparison = ") <= 0"; break;
7341 case BO_GE: resultComparison = ") >= 0"; break;
7342 case BO_EQ: resultComparison = ") == 0"; break;
7343 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregora86b8322009-04-06 18:45:53 +00007344 default: assert(false && "Invalid comparison operator");
7345 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007346
Ted Kremenek351ba912011-02-23 01:52:04 +00007347 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00007348 PDiag(diag::warn_stringcompare)
7349 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00007350 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00007351 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00007352 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007353
Douglas Gregord64fdd02010-06-08 19:50:34 +00007354 // C99 6.5.8p3 / C99 6.5.9p4
John Wiegley429bb272011-04-08 18:41:53 +00007355 if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00007356 UsualArithmeticConversions(lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00007357 if (lex.isInvalid() || rex.isInvalid())
7358 return QualType();
7359 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00007360 else {
John Wiegley429bb272011-04-08 18:41:53 +00007361 lex = UsualUnaryConversions(lex.take());
7362 if (lex.isInvalid())
7363 return QualType();
7364
7365 rex = UsualUnaryConversions(rex.take());
7366 if (rex.isInvalid())
7367 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007368 }
7369
John Wiegley429bb272011-04-08 18:41:53 +00007370 lType = lex.get()->getType();
7371 rType = rex.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00007372
Douglas Gregor447b69e2008-11-19 03:25:36 +00007373 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00007374 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00007375
Chris Lattnera5937dd2007-08-26 01:18:55 +00007376 if (isRelational) {
7377 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007378 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007379 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00007380 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007381 if (lType->hasFloatingRepresentation())
John Wiegley429bb272011-04-08 18:41:53 +00007382 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007383
Chris Lattnera5937dd2007-08-26 01:18:55 +00007384 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00007385 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00007386 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007387
John Wiegley429bb272011-04-08 18:41:53 +00007388 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007389 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00007390 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00007391 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007392
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007393 // All of the following pointer-related warnings are GCC extensions, except
7394 // when handling null pointer constants.
Steve Naroff77878cc2007-08-27 04:08:11 +00007395 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00007396 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00007397 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00007398 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00007399 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007400
Douglas Gregor0c6db942009-05-04 06:07:12 +00007401 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00007402 if (LCanPointeeTy == RCanPointeeTy)
7403 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007404 if (!isRelational &&
7405 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7406 // Valid unless comparison between non-null pointer and function pointer
7407 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007408 // In a SFINAE context, we treat this as a hard error to maintain
7409 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007410 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7411 && !LHSIsNull && !RHSIsNull) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007412 Diag(Loc,
7413 isSFINAEContext()?
7414 diag::err_typecheck_comparison_of_fptr_to_void
7415 : diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley429bb272011-04-08 18:41:53 +00007416 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007417
7418 if (isSFINAEContext())
7419 return QualType();
7420
John Wiegley429bb272011-04-08 18:41:53 +00007421 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00007422 return ResultTy;
7423 }
7424 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007425
Douglas Gregor0c6db942009-05-04 06:07:12 +00007426 // C++ [expr.rel]p2:
7427 // [...] Pointer conversions (4.10) and qualification
7428 // conversions (4.4) are performed on pointer operands (or on
7429 // a pointer operand and a null pointer constant) to bring
7430 // them to their composite pointer type. [...]
7431 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00007432 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00007433 // comparisons of pointers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007434 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00007435 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007436 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor0c6db942009-05-04 06:07:12 +00007437 if (T.isNull()) {
7438 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007439 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00007440 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007441 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007442 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007443 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007444 << lType << rType << T
John Wiegley429bb272011-04-08 18:41:53 +00007445 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00007446 }
7447
John Wiegley429bb272011-04-08 18:41:53 +00007448 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7449 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00007450 return ResultTy;
7451 }
Eli Friedman3075e762009-08-23 00:27:47 +00007452 // C99 6.5.9p2 and C99 6.5.8p2
7453 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7454 RCanPointeeTy.getUnqualifiedType())) {
7455 // Valid unless a relational comparison of function pointers
7456 if (isRelational && LCanPointeeTy->isFunctionType()) {
7457 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007458 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007459 }
7460 } else if (!isRelational &&
7461 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7462 // Valid unless comparison between non-null pointer and function pointer
7463 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7464 && !LHSIsNull && !RHSIsNull) {
7465 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley429bb272011-04-08 18:41:53 +00007466 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00007467 }
7468 } else {
7469 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007470 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007471 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007472 }
John McCall34d6f932011-03-11 04:25:25 +00007473 if (LCanPointeeTy != RCanPointeeTy) {
7474 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007475 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007476 else
John Wiegley429bb272011-04-08 18:41:53 +00007477 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007478 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00007479 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00007480 }
Mike Stump1eb44332009-09-09 15:08:12 +00007481
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007482 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007483 // Comparison of nullptr_t with itself.
7484 if (lType->isNullPtrType() && rType->isNullPtrType())
7485 return ResultTy;
7486
Mike Stump1eb44332009-09-09 15:08:12 +00007487 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00007488 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00007489 if (RHSIsNull &&
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007490 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregor20b3e992009-08-24 17:42:35 +00007491 (!isRelational && lType->isMemberPointerType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00007492 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregor443c2122010-08-07 13:36:37 +00007493 lType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007494 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007495 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007496 return ResultTy;
7497 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007498 if (LHSIsNull &&
Anders Carlsson0c8209e2010-11-04 03:17:43 +00007499 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregor20b3e992009-08-24 17:42:35 +00007500 (!isRelational && rType->isMemberPointerType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00007501 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregor443c2122010-08-07 13:36:37 +00007502 rType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00007503 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00007504 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007505 return ResultTy;
7506 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00007507
7508 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00007509 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00007510 lType->isMemberPointerType() && rType->isMemberPointerType()) {
7511 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00007512 // In addition, pointers to members can be compared, or a pointer to
7513 // member and a null pointer constant. Pointer to member conversions
7514 // (4.11) and qualification conversions (4.4) are performed to bring
7515 // them to a common type. If one operand is a null pointer constant,
7516 // the common type is the type of the other operand. Otherwise, the
7517 // common type is a pointer to member type similar (4.4) to the type
7518 // of one of the operands, with a cv-qualification signature (4.4)
7519 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00007520 // types.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007521 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00007522 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007523 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor20b3e992009-08-24 17:42:35 +00007524 if (T.isNull()) {
7525 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007526 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00007527 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007528 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007529 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00007530 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007531 << lType << rType << T
John Wiegley429bb272011-04-08 18:41:53 +00007532 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00007533 }
Mike Stump1eb44332009-09-09 15:08:12 +00007534
John Wiegley429bb272011-04-08 18:41:53 +00007535 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7536 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00007537 return ResultTy;
7538 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007539
7540 // Handle scoped enumeration types specifically, since they don't promote
7541 // to integers.
John Wiegley429bb272011-04-08 18:41:53 +00007542 if (lex.get()->getType()->isEnumeralType() &&
7543 Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00007544 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00007545 }
Mike Stump1eb44332009-09-09 15:08:12 +00007546
Steve Naroff1c7d0672008-09-04 15:10:53 +00007547 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00007548 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00007549 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7550 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007551
Steve Naroff1c7d0672008-09-04 15:10:53 +00007552 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00007553 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007554 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley429bb272011-04-08 18:41:53 +00007555 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00007556 }
John Wiegley429bb272011-04-08 18:41:53 +00007557 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007558 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007559 }
John Wiegley429bb272011-04-08 18:41:53 +00007560
Steve Naroff59f53942008-09-28 01:11:11 +00007561 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00007562 if (!isRelational
7563 && ((lType->isBlockPointerType() && rType->isPointerType())
7564 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00007565 if (!LHSIsNull && !RHSIsNull) {
John McCall34d6f932011-03-11 04:25:25 +00007566 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007567 ->getPointeeType()->isVoidType())
John McCall34d6f932011-03-11 04:25:25 +00007568 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00007569 ->getPointeeType()->isVoidType())))
7570 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley429bb272011-04-08 18:41:53 +00007571 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00007572 }
John McCall34d6f932011-03-11 04:25:25 +00007573 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007574 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007575 else
John Wiegley429bb272011-04-08 18:41:53 +00007576 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007577 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00007578 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00007579
John McCall34d6f932011-03-11 04:25:25 +00007580 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
7581 const PointerType *LPT = lType->getAs<PointerType>();
7582 const PointerType *RPT = rType->getAs<PointerType>();
7583 if (LPT || RPT) {
7584 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7585 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007586
Steve Naroffa8069f12008-11-17 19:49:16 +00007587 if (!LPtrToVoid && !RPtrToVoid &&
7588 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00007589 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007590 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00007591 }
John McCall34d6f932011-03-11 04:25:25 +00007592 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007593 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007594 else
John Wiegley429bb272011-04-08 18:41:53 +00007595 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007596 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00007597 }
Steve Naroff14108da2009-07-10 23:34:53 +00007598 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007599 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00007600 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00007601 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
John McCall34d6f932011-03-11 04:25:25 +00007602 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00007603 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00007604 else
John Wiegley429bb272011-04-08 18:41:53 +00007605 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007606 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00007607 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00007608 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007609 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7610 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007611 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007612 bool isError = false;
7613 if ((LHSIsNull && lType->isIntegerType()) ||
7614 (RHSIsNull && rType->isIntegerType())) {
7615 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007616 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007617 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007618 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007619 else if (getLangOptions().CPlusPlus) {
7620 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7621 isError = true;
7622 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007623 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00007624
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007625 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00007626 Diag(Loc, DiagID)
John Wiegley429bb272011-04-08 18:41:53 +00007627 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007628 if (isError)
7629 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00007630 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007631
7632 if (lType->isIntegerType())
John Wiegley429bb272011-04-08 18:41:53 +00007633 lex = ImpCastExprToType(lex.take(), rType,
John McCall404cd162010-11-13 01:35:44 +00007634 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00007635 else
John Wiegley429bb272011-04-08 18:41:53 +00007636 rex = ImpCastExprToType(rex.take(), lType,
John McCall404cd162010-11-13 01:35:44 +00007637 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007638 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007639 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00007640
Steve Naroff39218df2008-09-04 16:56:14 +00007641 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00007642 if (!isRelational && RHSIsNull
7643 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00007644 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007645 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007646 }
Mike Stumpaf199f32009-05-07 18:43:07 +00007647 if (!isRelational && LHSIsNull
7648 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00007649 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00007650 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00007651 }
Douglas Gregor90566c02011-03-01 17:16:20 +00007652
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007653 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007654}
7655
Nate Begemanbe2341d2008-07-14 18:02:46 +00007656/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00007657/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007658/// like a scalar comparison, a vector comparison produces a vector of integer
7659/// types.
John Wiegley429bb272011-04-08 18:41:53 +00007660QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007661 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00007662 bool isRelational) {
7663 // Check to make sure we're operating on vectors of the same type and width,
7664 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007665 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00007666 if (vType.isNull())
7667 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007668
John Wiegley429bb272011-04-08 18:41:53 +00007669 QualType lType = lex.get()->getType();
7670 QualType rType = rex.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007671
Anton Yartsev7870b132011-03-27 15:36:07 +00007672 // If AltiVec, the comparison results in a numeric type, i.e.
7673 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00007674 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00007675 return Context.getLogicalOperationType();
7676
Nate Begemanbe2341d2008-07-14 18:02:46 +00007677 // For non-floating point types, check for self-comparisons of the form
7678 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7679 // often indicate logic errors in the program.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007680 if (!lType->hasFloatingRepresentation()) {
John Wiegley429bb272011-04-08 18:41:53 +00007681 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
7682 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007683 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00007684 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00007685 PDiag(diag::warn_comparison_always)
7686 << 0 // self-
7687 << 2 // "a constant"
7688 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00007689 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007690
Nate Begemanbe2341d2008-07-14 18:02:46 +00007691 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00007692 if (!isRelational && lType->hasFloatingRepresentation()) {
7693 assert (rType->hasFloatingRepresentation());
John Wiegley429bb272011-04-08 18:41:53 +00007694 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00007695 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007696
Nate Begemanbe2341d2008-07-14 18:02:46 +00007697 // Return the type for the comparison, which is the same as vector type for
7698 // integer vectors, or an integer type of identical size and number of
7699 // elements for floating point vectors.
Douglas Gregorf6094622010-07-23 15:58:24 +00007700 if (lType->hasIntegerRepresentation())
Nate Begemanbe2341d2008-07-14 18:02:46 +00007701 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007702
John McCall183700f2009-09-21 23:43:11 +00007703 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00007704 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00007705 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00007706 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00007707 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00007708 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7709
Mike Stumpeed9cac2009-02-19 03:04:26 +00007710 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00007711 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00007712 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7713}
7714
Reid Spencer5f016e22007-07-11 17:01:13 +00007715inline QualType Sema::CheckBitwiseOperands(
John Wiegley429bb272011-04-08 18:41:53 +00007716 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
7717 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
7718 if (lex.get()->getType()->hasIntegerRepresentation() &&
7719 rex.get()->getType()->hasIntegerRepresentation())
Douglas Gregorf6094622010-07-23 15:58:24 +00007720 return CheckVectorOperands(Loc, lex, rex);
7721
7722 return InvalidOperands(Loc, lex, rex);
7723 }
Steve Naroff90045e82007-07-13 23:32:42 +00007724
John Wiegley429bb272011-04-08 18:41:53 +00007725 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
7726 QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
7727 if (lexResult.isInvalid() || rexResult.isInvalid())
7728 return QualType();
7729 lex = lexResult.take();
7730 rex = rexResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007731
John Wiegley429bb272011-04-08 18:41:53 +00007732 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
7733 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00007734 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007735 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00007736}
7737
7738inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley429bb272011-04-08 18:41:53 +00007739 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00007740
7741 // Diagnose cases where the user write a logical and/or but probably meant a
7742 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7743 // is a constant.
John Wiegley429bb272011-04-08 18:41:53 +00007744 if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
7745 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Chris Lattner23ef3e42010-07-15 00:26:43 +00007746 // Don't warn in macros.
Chris Lattnerb7690b42010-07-24 01:10:11 +00007747 !Loc.isMacroID()) {
7748 // If the RHS can be constant folded, and if it constant folds to something
7749 // that isn't 0 or 1 (which indicate a potential logical operation that
7750 // happened to fold to true/false) then warn.
7751 Expr::EvalResult Result;
John Wiegley429bb272011-04-08 18:41:53 +00007752 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects &&
Chris Lattnerb7690b42010-07-24 01:10:11 +00007753 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7754 Diag(Loc, diag::warn_logical_instead_of_bitwise)
John Wiegley429bb272011-04-08 18:41:53 +00007755 << rex.get()->getSourceRange()
John McCall2de56d12010-08-25 11:45:40 +00007756 << (Opc == BO_LAnd ? "&&" : "||")
7757 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattnerb7690b42010-07-24 01:10:11 +00007758 }
7759 }
Chris Lattner90a8f272010-07-13 19:41:32 +00007760
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007761 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007762 lex = UsualUnaryConversions(lex.take());
7763 if (lex.isInvalid())
7764 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007765
John Wiegley429bb272011-04-08 18:41:53 +00007766 rex = UsualUnaryConversions(rex.take());
7767 if (rex.isInvalid())
7768 return QualType();
7769
7770 if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007771 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007772
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007773 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00007774 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007775
John McCall75f7c0f2010-06-04 00:29:51 +00007776 // The following is safe because we only use this method for
7777 // non-overloadable operands.
7778
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007779 // C++ [expr.log.and]p1
7780 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00007781 // The operands are both contextually converted to type bool.
John Wiegley429bb272011-04-08 18:41:53 +00007782 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
7783 if (lexRes.isInvalid())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007784 return InvalidOperands(Loc, lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00007785 lex = move(lexRes);
7786
7787 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
7788 if (rexRes.isInvalid())
7789 return InvalidOperands(Loc, lex, rex);
7790 rex = move(rexRes);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007791
Anders Carlssona4c98cd2009-11-23 21:47:44 +00007792 // C++ [expr.log.and]p2
7793 // C++ [expr.log.or]p2
7794 // The result is a bool.
7795 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007796}
7797
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007798/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7799/// is a read-only property; return true if so. A readonly property expression
7800/// depends on various declarations and thus must be treated specially.
7801///
Mike Stump1eb44332009-09-09 15:08:12 +00007802static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007803 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7804 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCall12f78a62010-12-02 01:19:52 +00007805 if (PropExpr->isImplicitProperty()) return false;
7806
7807 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7808 QualType BaseType = PropExpr->isSuperReceiver() ?
7809 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00007810 PropExpr->getBase()->getType();
7811
John McCall12f78a62010-12-02 01:19:52 +00007812 if (const ObjCObjectPointerType *OPT =
7813 BaseType->getAsObjCInterfacePointerType())
7814 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7815 if (S.isPropertyReadonly(PDecl, IFace))
7816 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007817 }
7818 return false;
7819}
7820
Fariborz Jahanian14086762011-03-28 23:47:18 +00007821static bool IsConstProperty(Expr *E, Sema &S) {
7822 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7823 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
7824 if (PropExpr->isImplicitProperty()) return false;
7825
7826 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7827 QualType T = PDecl->getType();
7828 if (T->isReferenceType())
Fariborz Jahanian61750f22011-03-30 16:59:30 +00007829 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanian14086762011-03-28 23:47:18 +00007830 CanQualType CT = S.Context.getCanonicalType(T);
7831 return CT.isConstQualified();
7832 }
7833 return false;
7834}
7835
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007836static bool IsReadonlyMessage(Expr *E, Sema &S) {
7837 if (E->getStmtClass() != Expr::MemberExprClass)
7838 return false;
7839 const MemberExpr *ME = cast<MemberExpr>(E);
7840 NamedDecl *Member = ME->getMemberDecl();
7841 if (isa<FieldDecl>(Member)) {
7842 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
7843 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
7844 return false;
7845 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
7846 }
7847 return false;
7848}
7849
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007850/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7851/// emit an error and return true. If so, return false.
7852static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007853 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00007854 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007855 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00007856 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7857 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian14086762011-03-28 23:47:18 +00007858 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7859 IsLV = Expr::MLV_Valid;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007860 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7861 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007862 if (IsLV == Expr::MLV_Valid)
7863 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007864
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007865 unsigned Diag = 0;
7866 bool NeedType = false;
7867 switch (IsLV) { // C99 6.5.16p2
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007868 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007869 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007870 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7871 NeedType = true;
7872 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007873 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007874 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7875 NeedType = true;
7876 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00007877 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007878 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7879 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00007880 case Expr::MLV_Valid:
7881 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00007882 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00007883 case Expr::MLV_MemberFunction:
7884 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007885 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7886 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007887 case Expr::MLV_IncompleteType:
7888 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00007889 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007890 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00007891 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00007892 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007893 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7894 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00007895 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007896 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7897 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00007898 case Expr::MLV_ReadonlyProperty:
7899 Diag = diag::error_readonly_property_assignment;
7900 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00007901 case Expr::MLV_NoSetterProperty:
7902 Diag = diag::error_nosetter_property_assignment;
7903 break;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007904 case Expr::MLV_InvalidMessageExpression:
7905 Diag = diag::error_readonly_message_assignment;
7906 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00007907 case Expr::MLV_SubObjCPropertySetting:
7908 Diag = diag::error_no_subobject_property_setting;
7909 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007910 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00007911
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007912 SourceRange Assign;
7913 if (Loc != OrigLoc)
7914 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007915 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00007916 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007917 else
Mike Stump1eb44332009-09-09 15:08:12 +00007918 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007919 return true;
7920}
7921
7922
7923
7924// C99 6.5.16.1
John Wiegley429bb272011-04-08 18:41:53 +00007925QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007926 SourceLocation Loc,
7927 QualType CompoundType) {
7928 // Verify that LHS is a modifiable lvalue, and emit error if not.
7929 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00007930 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007931
7932 QualType LHSType = LHS->getType();
John Wiegley429bb272011-04-08 18:41:53 +00007933 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007934 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007935 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007936 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007937 // Simple assignment "x = y".
John Wiegley429bb272011-04-08 18:41:53 +00007938 if (LHS->getObjectKind() == OK_ObjCProperty) {
7939 ExprResult LHSResult = Owned(LHS);
7940 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7941 if (LHSResult.isInvalid())
7942 return QualType();
7943 LHS = LHSResult.take();
7944 }
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00007945 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00007946 if (RHS.isInvalid())
7947 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007948 // Special case of NSObject attributes on c-style pointer types.
7949 if (ConvTy == IncompatiblePointer &&
7950 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007951 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007952 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00007953 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00007954 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007955
John McCallf89e55a2010-11-18 06:31:45 +00007956 if (ConvTy == Compatible &&
7957 getLangOptions().ObjCNonFragileABI &&
7958 LHSType->isObjCObjectType())
7959 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7960 << LHSType;
7961
Chris Lattner2c156472008-08-21 18:04:13 +00007962 // If the RHS is a unary plus or minus, check to see if they = and + are
7963 // right next to each other. If so, the user may have typo'd "x =+ 4"
7964 // instead of "x += 4".
John Wiegley429bb272011-04-08 18:41:53 +00007965 Expr *RHSCheck = RHS.get();
Chris Lattner2c156472008-08-21 18:04:13 +00007966 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7967 RHSCheck = ICE->getSubExpr();
7968 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00007969 if ((UO->getOpcode() == UO_Plus ||
7970 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007971 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00007972 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00007973 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7974 // And there is a space or other character before the subexpr of the
7975 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00007976 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7977 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007978 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00007979 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007980 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00007981 }
Chris Lattner2c156472008-08-21 18:04:13 +00007982 }
7983 } else {
7984 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00007985 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00007986 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00007987
Chris Lattner29a1cfb2008-11-18 01:30:42 +00007988 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00007989 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00007990 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00007991
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +00007992 CheckForNullPointerDereference(*this, LHS);
Ted Kremeneka0125d82011-02-16 01:57:07 +00007993 // Check for trivial buffer overflows.
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007994 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremeneka0125d82011-02-16 01:57:07 +00007995
Reid Spencer5f016e22007-07-11 17:01:13 +00007996 // C99 6.5.16p3: The type of an assignment expression is the type of the
7997 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00007998 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00007999 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8000 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008001 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00008002 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00008003 return (getLangOptions().CPlusPlus
8004 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008005}
8006
Chris Lattner29a1cfb2008-11-18 01:30:42 +00008007// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00008008static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00008009 SourceLocation Loc) {
John Wiegley429bb272011-04-08 18:41:53 +00008010 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00008011
John McCallfb8721c2011-04-10 19:13:55 +00008012 LHS = S.CheckPlaceholderExpr(LHS.take());
8013 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00008014 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00008015 return QualType();
8016
John McCallcf2e5062010-10-12 07:14:40 +00008017 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8018 // operands, but not unary promotions.
8019 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008020
John McCallf6a16482010-12-04 03:47:34 +00008021 // So we treat the LHS as a ignored value, and in C++ we allow the
8022 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00008023 LHS = S.IgnoredValueConversions(LHS.take());
8024 if (LHS.isInvalid())
8025 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00008026
8027 if (!S.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00008028 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8029 if (RHS.isInvalid())
8030 return QualType();
8031 if (!RHS.get()->getType()->isVoidType())
8032 S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00008033 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008034
John Wiegley429bb272011-04-08 18:41:53 +00008035 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008036}
8037
Steve Naroff49b45262007-07-13 16:58:59 +00008038/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8039/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00008040static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8041 ExprValueKind &VK,
8042 SourceLocation OpLoc,
8043 bool isInc, bool isPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00008044 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008045 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008046
Chris Lattner3528d352008-11-21 07:05:48 +00008047 QualType ResType = Op->getType();
8048 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008049
John McCall09431682010-11-18 19:01:18 +00008050 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00008051 // Decrement of bool is not allowed.
8052 if (!isInc) {
John McCall09431682010-11-18 19:01:18 +00008053 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00008054 return QualType();
8055 }
8056 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00008057 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00008058 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00008059 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00008060 } else if (ResType->isAnyPointerType()) {
8061 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00008062
Chris Lattner3528d352008-11-21 07:05:48 +00008063 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00008064 if (PointeeTy->isVoidType()) {
John McCall09431682010-11-18 19:01:18 +00008065 if (S.getLangOptions().CPlusPlus) {
8066 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00008067 << Op->getSourceRange();
8068 return QualType();
8069 }
8070
8071 // Pointer to void is a GNU extension in C.
John McCall09431682010-11-18 19:01:18 +00008072 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00008073 } else if (PointeeTy->isFunctionType()) {
John McCall09431682010-11-18 19:01:18 +00008074 if (S.getLangOptions().CPlusPlus) {
8075 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00008076 << Op->getType() << Op->getSourceRange();
8077 return QualType();
8078 }
8079
John McCall09431682010-11-18 19:01:18 +00008080 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00008081 << ResType << Op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00008082 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
8083 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00008084 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00008085 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00008086 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00008087 // Diagnose bad cases where we step over interface counts.
John McCall09431682010-11-18 19:01:18 +00008088 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
8089 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00008090 << PointeeTy << Op->getSourceRange();
8091 return QualType();
8092 }
Eli Friedman5b088a12010-01-03 00:20:48 +00008093 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00008094 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00008095 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00008096 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008097 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008098 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008099 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008100 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8101 isInc, isPrefix);
Anton Yartsev683564a2011-02-07 02:17:30 +00008102 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
8103 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00008104 } else {
John McCall09431682010-11-18 19:01:18 +00008105 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00008106 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00008107 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008108 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008109 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00008110 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00008111 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00008112 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008113 // In C++, a prefix increment is the same type as the operand. Otherwise
8114 // (in C or with postfix), the increment is the unqualified type of the
8115 // operand.
John McCall09431682010-11-18 19:01:18 +00008116 if (isPrefix && S.getLangOptions().CPlusPlus) {
8117 VK = VK_LValue;
8118 return ResType;
8119 } else {
8120 VK = VK_RValue;
8121 return ResType.getUnqualifiedType();
8122 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008123}
8124
John Wiegley429bb272011-04-08 18:41:53 +00008125ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCallf6a16482010-12-04 03:47:34 +00008126 assert(E->getValueKind() == VK_LValue &&
8127 E->getObjectKind() == OK_ObjCProperty);
8128 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
8129
8130 ExprValueKind VK = VK_RValue;
8131 if (PRE->isImplicitProperty()) {
Fariborz Jahanian99130e52010-12-22 19:46:35 +00008132 if (const ObjCMethodDecl *GetterMethod =
8133 PRE->getImplicitPropertyGetter()) {
8134 QualType Result = GetterMethod->getResultType();
8135 VK = Expr::getValueKindForType(Result);
8136 }
8137 else {
8138 Diag(PRE->getLocation(), diag::err_getter_not_found)
8139 << PRE->getBase()->getType();
8140 }
John McCallf6a16482010-12-04 03:47:34 +00008141 }
8142
8143 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
8144 E, 0, VK);
John McCalldb67e2f2010-12-10 01:49:45 +00008145
8146 ExprResult Result = MaybeBindToTemporary(E);
8147 if (!Result.isInvalid())
8148 E = Result.take();
John Wiegley429bb272011-04-08 18:41:53 +00008149
8150 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00008151}
8152
John Wiegley429bb272011-04-08 18:41:53 +00008153void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
8154 assert(LHS.get()->getValueKind() == VK_LValue &&
8155 LHS.get()->getObjectKind() == OK_ObjCProperty);
8156 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCallf6a16482010-12-04 03:47:34 +00008157
John Wiegley429bb272011-04-08 18:41:53 +00008158 if (PropRef->isImplicitProperty()) {
John McCallf6a16482010-12-04 03:47:34 +00008159 // If using property-dot syntax notation for assignment, and there is a
8160 // setter, RHS expression is being passed to the setter argument. So,
8161 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley429bb272011-04-08 18:41:53 +00008162 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCallf6a16482010-12-04 03:47:34 +00008163 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
8164 LHSTy = (*P)->getType();
8165
8166 // Otherwise, if the getter returns an l-value, just call that.
8167 } else {
John Wiegley429bb272011-04-08 18:41:53 +00008168 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCallf6a16482010-12-04 03:47:34 +00008169 ExprValueKind VK = Expr::getValueKindForType(Result);
8170 if (VK == VK_LValue) {
John Wiegley429bb272011-04-08 18:41:53 +00008171 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
8172 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCallf6a16482010-12-04 03:47:34 +00008173 return;
John McCall12f78a62010-12-02 01:19:52 +00008174 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008175 }
John McCallf6a16482010-12-04 03:47:34 +00008176 }
8177
8178 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008179 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00008180 InitializedEntity::InitializeParameter(Context, LHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00008181 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008182 if (!ArgE.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00008183 RHS = ArgE;
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00008184 }
8185}
8186
8187
Anders Carlsson369dee42008-02-01 07:15:58 +00008188/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00008189/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008190/// where the declaration is needed for type checking. We only need to
8191/// handle cases when the expression references a function designator
8192/// or is an lvalue. Here are some examples:
8193/// - &(x) => x
8194/// - &*****f => f for f a function designator.
8195/// - &s.xx => s
8196/// - &s.zz[1].yy -> s, if zz is an array
8197/// - *(x + 1) -> x, if x is an array
8198/// - &"123"[2] -> 0
8199/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00008200static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00008201 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00008202 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00008203 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00008204 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00008205 // If this is an arrow operator, the address is an offset from
8206 // the base's value, so the object the base refers to is
8207 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00008208 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00008209 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00008210 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00008211 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00008212 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00008213 // FIXME: This code shouldn't be necessary! We should catch the implicit
8214 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00008215 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8216 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8217 if (ICE->getSubExpr()->getType()->isArrayType())
8218 return getPrimaryDecl(ICE->getSubExpr());
8219 }
8220 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00008221 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008222 case Stmt::UnaryOperatorClass: {
8223 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008224
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008225 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00008226 case UO_Real:
8227 case UO_Imag:
8228 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00008229 return getPrimaryDecl(UO->getSubExpr());
8230 default:
8231 return 0;
8232 }
8233 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008234 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00008235 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00008236 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00008237 // If the result of an implicit cast is an l-value, we care about
8238 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00008239 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00008240 default:
8241 return 0;
8242 }
8243}
8244
8245/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00008246/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00008247/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008248/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00008249/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008250/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00008251/// we allow the '&' but retain the overloaded-function type.
John McCall09431682010-11-18 19:01:18 +00008252static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
8253 SourceLocation OpLoc) {
John McCall9c72c602010-08-27 09:08:28 +00008254 if (OrigOp->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008255 return S.Context.DependentTy;
8256 if (OrigOp->getType() == S.Context.OverloadTy)
8257 return S.Context.OverloadTy;
John McCall755d8492011-04-12 00:42:48 +00008258 if (OrigOp->getType() == S.Context.UnknownAnyTy)
8259 return S.Context.UnknownAnyTy;
John McCall864c0412011-04-26 20:42:42 +00008260 if (OrigOp->getType() == S.Context.BoundMemberTy) {
8261 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8262 << OrigOp->getSourceRange();
8263 return QualType();
8264 }
John McCall9c72c602010-08-27 09:08:28 +00008265
John McCall755d8492011-04-12 00:42:48 +00008266 assert(!OrigOp->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00008267
John McCall9c72c602010-08-27 09:08:28 +00008268 // Make sure to ignore parentheses in subsequent checks
8269 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00008270
John McCall09431682010-11-18 19:01:18 +00008271 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00008272 // Implement C99-only parts of addressof rules.
8273 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00008274 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00008275 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8276 // (assuming the deref expression is valid).
8277 return uOp->getSubExpr()->getType();
8278 }
8279 // Technically, there should be a check for array subscript
8280 // expressions here, but the result of one is always an lvalue anyway.
8281 }
John McCall5808ce42011-02-03 08:15:49 +00008282 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00008283 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00008284
Fariborz Jahanian077f4902011-03-26 19:48:30 +00008285 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00008286 bool sfinae = S.isSFINAEContext();
8287 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8288 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00008289 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00008290 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00008291 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00008292 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008293 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00008294 } else if (lval == Expr::LV_MemberFunction) {
8295 // If it's an instance method, make a member pointer.
8296 // The expression must have exactly the form &A::foo.
8297
8298 // If the underlying expression isn't a decl ref, give up.
8299 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00008300 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00008301 << OrigOp->getSourceRange();
8302 return QualType();
8303 }
8304 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8305 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8306
8307 // The id-expression was parenthesized.
8308 if (OrigOp != DRE) {
John McCall09431682010-11-18 19:01:18 +00008309 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00008310 << OrigOp->getSourceRange();
8311
8312 // The method was named without a qualifier.
8313 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00008314 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00008315 << op->getSourceRange();
8316 }
8317
John McCall09431682010-11-18 19:01:18 +00008318 return S.Context.getMemberPointerType(op->getType(),
8319 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00008320 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00008321 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008322 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00008323 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00008324 // FIXME: emit more specific diag...
John McCall09431682010-11-18 19:01:18 +00008325 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008326 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00008327 return QualType();
8328 }
John McCall7eb0a9e2010-11-24 05:12:34 +00008329 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00008330 // The operand cannot be a bit-field
John McCall09431682010-11-18 19:01:18 +00008331 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman23d58ce2009-04-20 08:23:18 +00008332 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00008333 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00008334 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00008335 // The operand cannot be an element of a vector
John McCall09431682010-11-18 19:01:18 +00008336 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00008337 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00008338 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00008339 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian0337f212009-07-07 18:50:52 +00008340 // cannot take address of a property expression.
John McCall09431682010-11-18 19:01:18 +00008341 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian0337f212009-07-07 18:50:52 +00008342 << "property expression" << op->getSourceRange();
8343 return QualType();
Steve Naroffbcb2b612008-02-29 23:30:25 +00008344 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00008345 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00008346 // with the register storage-class specifier.
8347 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00008348 // in C++ it is not error to take address of a register
8349 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00008350 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00008351 !S.getLangOptions().CPlusPlus) {
8352 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008353 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00008354 return QualType();
8355 }
John McCallba135432009-11-21 08:51:07 +00008356 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00008357 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00008358 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00008359 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00008360 // Could be a pointer to member, though, if there is an explicit
8361 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00008362 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00008363 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008364 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00008365 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00008366 S.Diag(OpLoc,
8367 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00008368 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008369 return QualType();
8370 }
Mike Stump1eb44332009-09-09 15:08:12 +00008371
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00008372 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8373 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00008374 return S.Context.getMemberPointerType(op->getType(),
8375 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00008376 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00008377 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00008378 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00008379 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00008380 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00008381
Eli Friedman441cf102009-05-16 23:27:50 +00008382 if (lval == Expr::LV_IncompleteVoidType) {
8383 // Taking the address of a void variable is technically illegal, but we
8384 // allow it in cases which are otherwise valid.
8385 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00008386 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00008387 }
8388
Reid Spencer5f016e22007-07-11 17:01:13 +00008389 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00008390 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00008391 return S.Context.getObjCObjectPointerType(op->getType());
8392 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00008393}
8394
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008395/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00008396static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8397 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00008398 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00008399 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00008400
John Wiegley429bb272011-04-08 18:41:53 +00008401 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8402 if (ConvResult.isInvalid())
8403 return QualType();
8404 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008405 QualType OpTy = Op->getType();
8406 QualType Result;
8407
8408 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8409 // is an incomplete type or void. It would be possible to warn about
8410 // dereferencing a void pointer, but it's completely well-defined, and such a
8411 // warning is unlikely to catch any mistakes.
8412 if (const PointerType *PT = OpTy->getAs<PointerType>())
8413 Result = PT->getPointeeType();
8414 else if (const ObjCObjectPointerType *OPT =
8415 OpTy->getAs<ObjCObjectPointerType>())
8416 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00008417 else {
John McCallfb8721c2011-04-10 19:13:55 +00008418 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00008419 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00008420 if (PR.take() != Op)
8421 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00008422 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008423
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008424 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00008425 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008426 << OpTy << Op->getSourceRange();
8427 return QualType();
8428 }
John McCall09431682010-11-18 19:01:18 +00008429
8430 // Dereferences are usually l-values...
8431 VK = VK_LValue;
8432
8433 // ...except that certain expressions are never l-values in C.
8434 if (!S.getLangOptions().CPlusPlus &&
8435 IsCForbiddenLValueType(S.Context, Result))
8436 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00008437
8438 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00008439}
8440
John McCall2de56d12010-08-25 11:45:40 +00008441static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008442 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008443 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008444 switch (Kind) {
8445 default: assert(0 && "Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00008446 case tok::periodstar: Opc = BO_PtrMemD; break;
8447 case tok::arrowstar: Opc = BO_PtrMemI; break;
8448 case tok::star: Opc = BO_Mul; break;
8449 case tok::slash: Opc = BO_Div; break;
8450 case tok::percent: Opc = BO_Rem; break;
8451 case tok::plus: Opc = BO_Add; break;
8452 case tok::minus: Opc = BO_Sub; break;
8453 case tok::lessless: Opc = BO_Shl; break;
8454 case tok::greatergreater: Opc = BO_Shr; break;
8455 case tok::lessequal: Opc = BO_LE; break;
8456 case tok::less: Opc = BO_LT; break;
8457 case tok::greaterequal: Opc = BO_GE; break;
8458 case tok::greater: Opc = BO_GT; break;
8459 case tok::exclaimequal: Opc = BO_NE; break;
8460 case tok::equalequal: Opc = BO_EQ; break;
8461 case tok::amp: Opc = BO_And; break;
8462 case tok::caret: Opc = BO_Xor; break;
8463 case tok::pipe: Opc = BO_Or; break;
8464 case tok::ampamp: Opc = BO_LAnd; break;
8465 case tok::pipepipe: Opc = BO_LOr; break;
8466 case tok::equal: Opc = BO_Assign; break;
8467 case tok::starequal: Opc = BO_MulAssign; break;
8468 case tok::slashequal: Opc = BO_DivAssign; break;
8469 case tok::percentequal: Opc = BO_RemAssign; break;
8470 case tok::plusequal: Opc = BO_AddAssign; break;
8471 case tok::minusequal: Opc = BO_SubAssign; break;
8472 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8473 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8474 case tok::ampequal: Opc = BO_AndAssign; break;
8475 case tok::caretequal: Opc = BO_XorAssign; break;
8476 case tok::pipeequal: Opc = BO_OrAssign; break;
8477 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008478 }
8479 return Opc;
8480}
8481
John McCall2de56d12010-08-25 11:45:40 +00008482static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00008483 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00008484 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00008485 switch (Kind) {
8486 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00008487 case tok::plusplus: Opc = UO_PreInc; break;
8488 case tok::minusminus: Opc = UO_PreDec; break;
8489 case tok::amp: Opc = UO_AddrOf; break;
8490 case tok::star: Opc = UO_Deref; break;
8491 case tok::plus: Opc = UO_Plus; break;
8492 case tok::minus: Opc = UO_Minus; break;
8493 case tok::tilde: Opc = UO_Not; break;
8494 case tok::exclaim: Opc = UO_LNot; break;
8495 case tok::kw___real: Opc = UO_Real; break;
8496 case tok::kw___imag: Opc = UO_Imag; break;
8497 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00008498 }
8499 return Opc;
8500}
8501
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008502/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8503/// This warning is only emitted for builtin assignment operations. It is also
8504/// suppressed in the event of macro expansions.
8505static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
8506 SourceLocation OpLoc) {
8507 if (!S.ActiveTemplateInstantiations.empty())
8508 return;
8509 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8510 return;
8511 lhs = lhs->IgnoreParenImpCasts();
8512 rhs = rhs->IgnoreParenImpCasts();
8513 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
8514 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
8515 if (!LeftDeclRef || !RightDeclRef ||
8516 LeftDeclRef->getLocation().isMacroID() ||
8517 RightDeclRef->getLocation().isMacroID())
8518 return;
8519 const ValueDecl *LeftDecl =
8520 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
8521 const ValueDecl *RightDecl =
8522 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
8523 if (LeftDecl != RightDecl)
8524 return;
8525 if (LeftDecl->getType().isVolatileQualified())
8526 return;
8527 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
8528 if (RefTy->getPointeeType().isVolatileQualified())
8529 return;
8530
8531 S.Diag(OpLoc, diag::warn_self_assignment)
8532 << LeftDeclRef->getType()
8533 << lhs->getSourceRange() << rhs->getSourceRange();
8534}
8535
Douglas Gregoreaebc752008-11-06 23:29:22 +00008536/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8537/// operator @p Opc at location @c TokLoc. This routine only supports
8538/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00008539ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008540 BinaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008541 Expr *lhsExpr, Expr *rhsExpr) {
8542 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008543 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00008544 // The following two variables are used for compound assignment operators
8545 QualType CompLHSTy; // Type of LHS after promotions for computation
8546 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00008547 ExprValueKind VK = VK_RValue;
8548 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00008549
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008550 // Check if a 'foo<int>' involved in a binary op, identifies a single
8551 // function unambiguously (i.e. an lvalue ala 13.4)
8552 // But since an assignment can trigger target based overload, exclude it in
8553 // our blind search. i.e:
8554 // template<class T> void f(); template<class T, class U> void f(U);
8555 // f<int> == 0; // resolve f<int> blindly
8556 // void (*p)(int); p = f<int>; // resolve f<int> using target
8557 if (Opc != BO_Assign) {
John McCallfb8721c2011-04-10 19:13:55 +00008558 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008559 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008560 lhs = move(resolvedLHS);
John McCall1de4d4e2011-04-07 08:22:57 +00008561
John McCallfb8721c2011-04-10 19:13:55 +00008562 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008563 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008564 rhs = move(resolvedRHS);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008565 }
8566
Douglas Gregoreaebc752008-11-06 23:29:22 +00008567 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008568 case BO_Assign:
John Wiegley429bb272011-04-08 18:41:53 +00008569 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00008570 if (getLangOptions().CPlusPlus &&
John Wiegley429bb272011-04-08 18:41:53 +00008571 lhs.get()->getObjectKind() != OK_ObjCProperty) {
8572 VK = lhs.get()->getValueKind();
8573 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008574 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00008575 if (!ResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00008576 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008577 break;
John McCall2de56d12010-08-25 11:45:40 +00008578 case BO_PtrMemD:
8579 case BO_PtrMemI:
John McCallf89e55a2010-11-18 06:31:45 +00008580 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008581 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00008582 break;
John McCall2de56d12010-08-25 11:45:40 +00008583 case BO_Mul:
8584 case BO_Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00008585 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00008586 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008587 break;
John McCall2de56d12010-08-25 11:45:40 +00008588 case BO_Rem:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008589 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
8590 break;
John McCall2de56d12010-08-25 11:45:40 +00008591 case BO_Add:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008592 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
8593 break;
John McCall2de56d12010-08-25 11:45:40 +00008594 case BO_Sub:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008595 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
8596 break;
John McCall2de56d12010-08-25 11:45:40 +00008597 case BO_Shl:
8598 case BO_Shr:
Chandler Carruth21206d52011-02-23 23:34:11 +00008599 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008600 break;
John McCall2de56d12010-08-25 11:45:40 +00008601 case BO_LE:
8602 case BO_LT:
8603 case BO_GE:
8604 case BO_GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00008605 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008606 break;
John McCall2de56d12010-08-25 11:45:40 +00008607 case BO_EQ:
8608 case BO_NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00008609 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008610 break;
John McCall2de56d12010-08-25 11:45:40 +00008611 case BO_And:
8612 case BO_Xor:
8613 case BO_Or:
Douglas Gregoreaebc752008-11-06 23:29:22 +00008614 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
8615 break;
John McCall2de56d12010-08-25 11:45:40 +00008616 case BO_LAnd:
8617 case BO_LOr:
Chris Lattner90a8f272010-07-13 19:41:32 +00008618 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008619 break;
John McCall2de56d12010-08-25 11:45:40 +00008620 case BO_MulAssign:
8621 case BO_DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00008622 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00008623 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008624 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00008625 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8626 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008627 break;
John McCall2de56d12010-08-25 11:45:40 +00008628 case BO_RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008629 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
8630 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00008631 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8632 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008633 break;
John McCall2de56d12010-08-25 11:45:40 +00008634 case BO_AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008635 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00008636 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8637 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008638 break;
John McCall2de56d12010-08-25 11:45:40 +00008639 case BO_SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008640 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00008641 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8642 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008643 break;
John McCall2de56d12010-08-25 11:45:40 +00008644 case BO_ShlAssign:
8645 case BO_ShrAssign:
Chandler Carruth21206d52011-02-23 23:34:11 +00008646 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00008647 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00008648 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8649 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008650 break;
John McCall2de56d12010-08-25 11:45:40 +00008651 case BO_AndAssign:
8652 case BO_XorAssign:
8653 case BO_OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00008654 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
8655 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00008656 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8657 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00008658 break;
John McCall2de56d12010-08-25 11:45:40 +00008659 case BO_Comma:
John McCall09431682010-11-18 19:01:18 +00008660 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00008661 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
8662 VK = rhs.get()->getValueKind();
8663 OK = rhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008664 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00008665 break;
8666 }
John Wiegley429bb272011-04-08 18:41:53 +00008667 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008668 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00008669 if (CompResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00008670 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
8671 ResultTy, VK, OK, OpLoc));
8672 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00008673 VK = VK_LValue;
John Wiegley429bb272011-04-08 18:41:53 +00008674 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00008675 }
John Wiegley429bb272011-04-08 18:41:53 +00008676 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
8677 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00008678 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00008679}
8680
Sebastian Redlaee3c932009-10-27 12:10:02 +00008681/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
8682/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008683static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8684 const PartialDiagnostic &PD,
Douglas Gregor55b38842010-04-14 16:09:52 +00008685 const PartialDiagnostic &FirstNote,
8686 SourceRange FirstParenRange,
8687 const PartialDiagnostic &SecondNote,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008688 SourceRange SecondParenRange) {
Douglas Gregor55b38842010-04-14 16:09:52 +00008689 Self.Diag(Loc, PD);
8690
8691 if (!FirstNote.getDiagID())
8692 return;
8693
8694 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
8695 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8696 // We can't display the parentheses, so just return.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008697 return;
8698 }
8699
Douglas Gregor55b38842010-04-14 16:09:52 +00008700 Self.Diag(Loc, FirstNote)
8701 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregor849b2432010-03-31 17:46:05 +00008702 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008703
Douglas Gregor55b38842010-04-14 16:09:52 +00008704 if (!SecondNote.getDiagID())
Douglas Gregor827feec2010-01-08 00:20:23 +00008705 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008706
Douglas Gregor827feec2010-01-08 00:20:23 +00008707 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
8708 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8709 // We can't display the parentheses, so just dig the
8710 // warning/error and return.
Douglas Gregor55b38842010-04-14 16:09:52 +00008711 Self.Diag(Loc, SecondNote);
Douglas Gregor827feec2010-01-08 00:20:23 +00008712 return;
8713 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008714
Douglas Gregor55b38842010-04-14 16:09:52 +00008715 Self.Diag(Loc, SecondNote)
Douglas Gregor849b2432010-03-31 17:46:05 +00008716 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
8717 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008718}
8719
Sebastian Redlaee3c932009-10-27 12:10:02 +00008720/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8721/// operators are mixed in a way that suggests that the programmer forgot that
8722/// comparison operators have higher precedence. The most typical example of
8723/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00008724static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008725 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00008726 typedef BinaryOperator BinOp;
8727 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
8728 rhsopc = static_cast<BinOp::Opcode>(-1);
8729 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008730 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00008731 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008732 rhsopc = BO->getOpcode();
8733
8734 // Subs are not binary operators.
8735 if (lhsopc == -1 && rhsopc == -1)
8736 return;
8737
8738 // Bitwise operations are sometimes used as eager logical ops.
8739 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00008740 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
8741 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008742 return;
8743
Sebastian Redlaee3c932009-10-27 12:10:02 +00008744 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008745 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008746 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00008747 << SourceRange(lhs->getLocStart(), OpLoc)
8748 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor55b38842010-04-14 16:09:52 +00008749 Self.PDiag(diag::note_precedence_bitwise_silence)
8750 << BinOp::getOpcodeStr(lhsopc),
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00008751 lhs->getSourceRange(),
8752 Self.PDiag(diag::note_precedence_bitwise_first)
8753 << BinOp::getOpcodeStr(Opc),
8754 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
Sebastian Redlaee3c932009-10-27 12:10:02 +00008755 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00008756 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008757 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00008758 << SourceRange(OpLoc, rhs->getLocEnd())
8759 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00008760 Self.PDiag(diag::note_precedence_bitwise_silence)
8761 << BinOp::getOpcodeStr(rhsopc),
8762 rhs->getSourceRange(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008763 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00008764 << BinOp::getOpcodeStr(Opc),
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00008765 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008766}
8767
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008768/// \brief It accepts a '&&' expr that is inside a '||' one.
8769/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8770/// in parentheses.
8771static void
8772EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008773 BinaryOperator *Bop) {
8774 assert(Bop->getOpcode() == BO_LAnd);
8775 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008776 Self.PDiag(diag::warn_logical_and_in_logical_or)
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008777 << Bop->getSourceRange() << OpLoc,
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008778 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00008779 Bop->getSourceRange(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008780 Self.PDiag(0), SourceRange());
8781}
8782
8783/// \brief Returns true if the given expression can be evaluated as a constant
8784/// 'true'.
8785static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8786 bool Res;
8787 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8788}
8789
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008790/// \brief Returns true if the given expression can be evaluated as a constant
8791/// 'false'.
8792static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8793 bool Res;
8794 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8795}
8796
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008797/// \brief Look for '&&' in the left hand of a '||' expr.
8798static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008799 Expr *OrLHS, Expr *OrRHS) {
8800 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008801 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008802 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8803 if (EvaluatesAsFalse(S, OrRHS))
8804 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008805 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8806 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8807 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8808 } else if (Bop->getOpcode() == BO_LOr) {
8809 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8810 // If it's "a || b && 1 || c" we didn't warn earlier for
8811 // "a || b && 1", but warn now.
8812 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8813 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8814 }
8815 }
8816 }
8817}
8818
8819/// \brief Look for '&&' in the right hand of a '||' expr.
8820static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008821 Expr *OrLHS, Expr *OrRHS) {
8822 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008823 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008824 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8825 if (EvaluatesAsFalse(S, OrLHS))
8826 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008827 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8828 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8829 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008830 }
8831 }
8832}
8833
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008834/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008835/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00008836static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008837 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008838 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00008839 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008840 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8841
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00008842 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8843 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00008844 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00008845 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8846 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00008847 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008848}
8849
Reid Spencer5f016e22007-07-11 17:01:13 +00008850// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008851ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00008852 tok::TokenKind Kind,
8853 Expr *lhs, Expr *rhs) {
8854 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Narofff69936d2007-09-16 03:34:24 +00008855 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8856 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00008857
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00008858 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8859 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8860
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008861 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8862}
8863
John McCall60d7b3a2010-08-24 06:29:42 +00008864ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008865 BinaryOperatorKind Opc,
8866 Expr *lhs, Expr *rhs) {
John McCall01b2e4e2010-12-06 05:26:58 +00008867 if (getLangOptions().CPlusPlus) {
8868 bool UseBuiltinOperator;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008869
John McCall01b2e4e2010-12-06 05:26:58 +00008870 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8871 UseBuiltinOperator = false;
8872 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8873 UseBuiltinOperator = true;
8874 } else {
8875 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8876 !rhs->getType()->isOverloadableType();
8877 }
8878
8879 if (!UseBuiltinOperator) {
8880 // Find all of the overloaded operators visible from this
8881 // point. We perform both an operator-name lookup from the local
8882 // scope and an argument-dependent lookup based on the types of
8883 // the arguments.
8884 UnresolvedSet<16> Functions;
8885 OverloadedOperatorKind OverOp
8886 = BinaryOperator::getOverloadedOperator(Opc);
8887 if (S && OverOp != OO_None)
8888 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8889 Functions);
8890
8891 // Build the (potentially-overloaded, potentially-dependent)
8892 // binary operation.
8893 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8894 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00008895 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008896
Douglas Gregoreaebc752008-11-06 23:29:22 +00008897 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008898 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00008899}
8900
John McCall60d7b3a2010-08-24 06:29:42 +00008901ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00008902 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00008903 Expr *InputExpr) {
8904 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00008905 ExprValueKind VK = VK_RValue;
8906 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00008907 QualType resultType;
8908 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00008909 case UO_PreInc:
8910 case UO_PreDec:
8911 case UO_PostInc:
8912 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00008913 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008914 Opc == UO_PreInc ||
8915 Opc == UO_PostInc,
8916 Opc == UO_PreInc ||
8917 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00008918 break;
John McCall2de56d12010-08-25 11:45:40 +00008919 case UO_AddrOf:
John Wiegley429bb272011-04-08 18:41:53 +00008920 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008921 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008922 case UO_Deref: {
John McCallfb8721c2011-04-10 19:13:55 +00008923 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall1de4d4e2011-04-07 08:22:57 +00008924 if (!resolved.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008925 Input = move(resolved);
8926 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8927 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00008928 break;
John McCall1de4d4e2011-04-07 08:22:57 +00008929 }
John McCall2de56d12010-08-25 11:45:40 +00008930 case UO_Plus:
8931 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00008932 Input = UsualUnaryConversions(Input.take());
8933 if (Input.isInvalid()) return ExprError();
8934 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008935 if (resultType->isDependentType())
8936 break;
Douglas Gregor00619622010-06-22 23:41:02 +00008937 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8938 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00008939 break;
8940 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8941 resultType->isEnumeralType())
8942 break;
8943 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00008944 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00008945 resultType->isPointerType())
8946 break;
John McCall2cd11fe2010-10-12 02:09:17 +00008947 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008948 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008949 if (Input.isInvalid()) return ExprError();
8950 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008951 }
Douglas Gregor74253732008-11-19 15:42:04 +00008952
Sebastian Redl0eb23302009-01-19 00:08:26 +00008953 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008954 << resultType << Input.get()->getSourceRange());
8955
John McCall2de56d12010-08-25 11:45:40 +00008956 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008957 Input = UsualUnaryConversions(Input.take());
8958 if (Input.isInvalid()) return ExprError();
8959 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008960 if (resultType->isDependentType())
8961 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008962 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8963 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8964 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008965 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008966 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008967 else if (resultType->hasIntegerRepresentation())
8968 break;
8969 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008970 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008971 if (Input.isInvalid()) return ExprError();
8972 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008973 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008974 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008975 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008976 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008977 break;
John Wiegley429bb272011-04-08 18:41:53 +00008978
John McCall2de56d12010-08-25 11:45:40 +00008979 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008980 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008981 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8982 if (Input.isInvalid()) return ExprError();
8983 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008984 if (resultType->isDependentType())
8985 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008986 if (resultType->isScalarType()) {
8987 // C99 6.5.3.3p1: ok, fallthrough;
8988 if (Context.getLangOptions().CPlusPlus) {
8989 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8990 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008991 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8992 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008993 }
John McCall2cd11fe2010-10-12 02:09:17 +00008994 } else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008995 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008996 if (Input.isInvalid()) return ExprError();
8997 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008998 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008999 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00009000 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00009001 }
Douglas Gregorea844f32010-09-20 17:13:33 +00009002
Reid Spencer5f016e22007-07-11 17:01:13 +00009003 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00009004 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00009005 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00009006 break;
John McCall2de56d12010-08-25 11:45:40 +00009007 case UO_Real:
9008 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00009009 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00009010 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley429bb272011-04-08 18:41:53 +00009011 if (Input.isInvalid()) return ExprError();
9012 if (Input.get()->getValueKind() != VK_RValue &&
9013 Input.get()->getObjectKind() == OK_Ordinary)
9014 VK = Input.get()->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00009015 break;
John McCall2de56d12010-08-25 11:45:40 +00009016 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00009017 resultType = Input.get()->getType();
9018 VK = Input.get()->getValueKind();
9019 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00009020 break;
9021 }
John Wiegley429bb272011-04-08 18:41:53 +00009022 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00009023 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009024
John Wiegley429bb272011-04-08 18:41:53 +00009025 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00009026 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00009027}
9028
John McCall60d7b3a2010-08-24 06:29:42 +00009029ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00009030 UnaryOperatorKind Opc,
9031 Expr *Input) {
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00009032 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00009033 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009034 // Find all of the overloaded operators visible from this
9035 // point. We perform both an operator-name lookup from the local
9036 // scope and an argument-dependent lookup based on the types of
9037 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00009038 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009039 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00009040 if (S && OverOp != OO_None)
9041 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9042 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009043
John McCall9ae2f072010-08-23 23:25:46 +00009044 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009045 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009046
John McCall9ae2f072010-08-23 23:25:46 +00009047 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009048}
9049
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009050// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00009051ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00009052 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00009053 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009054}
9055
Steve Naroff1b273c42007-09-16 14:56:35 +00009056/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00009057ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00009058 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00009059 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00009060 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00009061 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009062 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00009063}
9064
John McCall60d7b3a2010-08-24 06:29:42 +00009065ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00009066Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009067 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009068 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9069 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9070
Douglas Gregordd8f5692010-03-10 04:54:39 +00009071 bool isFileScope
9072 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00009073 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00009074 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00009075
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009076 // FIXME: there are a variety of strange constraints to enforce here, for
9077 // example, it is not possible to goto into a stmt expression apparently.
9078 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00009079
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009080 // If there are sub stmts in the compound stmt, take the type of the last one
9081 // as the type of the stmtexpr.
9082 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009083 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009084 if (!Compound->body_empty()) {
9085 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009086 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009087 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009088 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9089 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00009090 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009091 }
John Wiegley429bb272011-04-08 18:41:53 +00009092 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00009093 // Do function/array conversion on the last expression, but not
9094 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00009095 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9096 if (LastExpr.isInvalid())
9097 return ExprError();
9098 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00009099
John Wiegley429bb272011-04-08 18:41:53 +00009100 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9101 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009102 InitializedEntity::InitializeResult(LPLoc,
9103 Ty,
9104 false),
9105 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00009106 LastExpr);
9107 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009108 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009109 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009110 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00009111 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009112 else
John Wiegley429bb272011-04-08 18:41:53 +00009113 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009114 StmtExprMayBindToTemp = true;
9115 }
9116 }
9117 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00009118 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009119
Eli Friedmanb1d796d2009-03-23 00:24:07 +00009120 // FIXME: Check that expression type is complete/non-abstract; statement
9121 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00009122 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9123 if (StmtExprMayBindToTemp)
9124 return MaybeBindToTemporary(ResStmtExpr);
9125 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00009126}
Steve Naroffd34e9152007-08-01 22:05:33 +00009127
John McCall60d7b3a2010-08-24 06:29:42 +00009128ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009129 TypeSourceInfo *TInfo,
9130 OffsetOfComponent *CompPtr,
9131 unsigned NumComponents,
9132 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009133 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00009134 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009135 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009136
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009137 // We must have at least one component that refers to the type, and the first
9138 // one is known to be a field designator. Verify that the ArgTy represents
9139 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00009140 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009141 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9142 << ArgTy << TypeRange);
9143
9144 // Type must be complete per C99 7.17p3 because a declaring a variable
9145 // with an incomplete type would be ill-formed.
9146 if (!Dependent
9147 && RequireCompleteType(BuiltinLoc, ArgTy,
9148 PDiag(diag::err_offsetof_incomplete_type)
9149 << TypeRange))
9150 return ExprError();
9151
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009152 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9153 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00009154 // FIXME: This diagnostic isn't actually visible because the location is in
9155 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00009156 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00009157 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9158 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009159
9160 bool DidWarnAboutNonPOD = false;
9161 QualType CurrentType = ArgTy;
9162 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9163 llvm::SmallVector<OffsetOfNode, 4> Comps;
9164 llvm::SmallVector<Expr*, 4> Exprs;
9165 for (unsigned i = 0; i != NumComponents; ++i) {
9166 const OffsetOfComponent &OC = CompPtr[i];
9167 if (OC.isBrackets) {
9168 // Offset of an array sub-field. TODO: Should we allow vector elements?
9169 if (!CurrentType->isDependentType()) {
9170 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9171 if(!AT)
9172 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9173 << CurrentType);
9174 CurrentType = AT->getElementType();
9175 } else
9176 CurrentType = Context.DependentTy;
9177
9178 // The expression must be an integral expression.
9179 // FIXME: An integral constant expression?
9180 Expr *Idx = static_cast<Expr*>(OC.U.E);
9181 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9182 !Idx->getType()->isIntegerType())
9183 return ExprError(Diag(Idx->getLocStart(),
9184 diag::err_typecheck_subscript_not_integer)
9185 << Idx->getSourceRange());
9186
9187 // Record this array index.
9188 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9189 Exprs.push_back(Idx);
9190 continue;
9191 }
9192
9193 // Offset of a field.
9194 if (CurrentType->isDependentType()) {
9195 // We have the offset of a field, but we can't look into the dependent
9196 // type. Just record the identifier of the field.
9197 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9198 CurrentType = Context.DependentTy;
9199 continue;
9200 }
9201
9202 // We need to have a complete type to look into.
9203 if (RequireCompleteType(OC.LocStart, CurrentType,
9204 diag::err_offsetof_incomplete_type))
9205 return ExprError();
9206
9207 // Look for the designated field.
9208 const RecordType *RC = CurrentType->getAs<RecordType>();
9209 if (!RC)
9210 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9211 << CurrentType);
9212 RecordDecl *RD = RC->getDecl();
9213
9214 // C++ [lib.support.types]p5:
9215 // The macro offsetof accepts a restricted set of type arguments in this
9216 // International Standard. type shall be a POD structure or a POD union
9217 // (clause 9).
9218 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9219 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00009220 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009221 PDiag(diag::warn_offsetof_non_pod_type)
9222 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9223 << CurrentType))
9224 DidWarnAboutNonPOD = true;
9225 }
9226
9227 // Look for the field.
9228 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9229 LookupQualifiedName(R, RD);
9230 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00009231 IndirectFieldDecl *IndirectMemberDecl = 0;
9232 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00009233 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00009234 MemberDecl = IndirectMemberDecl->getAnonField();
9235 }
9236
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009237 if (!MemberDecl)
9238 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9239 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9240 OC.LocEnd));
9241
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00009242 // C99 7.17p3:
9243 // (If the specified member is a bit-field, the behavior is undefined.)
9244 //
9245 // We diagnose this as an error.
9246 if (MemberDecl->getBitWidth()) {
9247 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9248 << MemberDecl->getDeclName()
9249 << SourceRange(BuiltinLoc, RParenLoc);
9250 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9251 return ExprError();
9252 }
Eli Friedman19410a72010-08-05 10:11:36 +00009253
9254 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00009255 if (IndirectMemberDecl)
9256 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00009257
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009258 // If the member was found in a base class, introduce OffsetOfNodes for
9259 // the base class indirections.
9260 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9261 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00009262 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00009263 CXXBasePath &Path = Paths.front();
9264 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9265 B != BEnd; ++B)
9266 Comps.push_back(OffsetOfNode(B->Base));
9267 }
Eli Friedman19410a72010-08-05 10:11:36 +00009268
Francois Pichet87c2e122010-11-21 06:08:52 +00009269 if (IndirectMemberDecl) {
9270 for (IndirectFieldDecl::chain_iterator FI =
9271 IndirectMemberDecl->chain_begin(),
9272 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9273 assert(isa<FieldDecl>(*FI));
9274 Comps.push_back(OffsetOfNode(OC.LocStart,
9275 cast<FieldDecl>(*FI), OC.LocEnd));
9276 }
9277 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009278 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00009279
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009280 CurrentType = MemberDecl->getType().getNonReferenceType();
9281 }
9282
9283 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9284 TInfo, Comps.data(), Comps.size(),
9285 Exprs.data(), Exprs.size(), RParenLoc));
9286}
Mike Stumpeed9cac2009-02-19 03:04:26 +00009287
John McCall60d7b3a2010-08-24 06:29:42 +00009288ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00009289 SourceLocation BuiltinLoc,
9290 SourceLocation TypeLoc,
9291 ParsedType argty,
9292 OffsetOfComponent *CompPtr,
9293 unsigned NumComponents,
9294 SourceLocation RPLoc) {
9295
Douglas Gregor8ecdb652010-04-28 22:16:22 +00009296 TypeSourceInfo *ArgTInfo;
9297 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
9298 if (ArgTy.isNull())
9299 return ExprError();
9300
Eli Friedman5a15dc12010-08-05 10:15:45 +00009301 if (!ArgTInfo)
9302 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9303
9304 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9305 RPLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00009306}
9307
9308
John McCall60d7b3a2010-08-24 06:29:42 +00009309ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00009310 Expr *CondExpr,
9311 Expr *LHSExpr, Expr *RHSExpr,
9312 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00009313 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9314
John McCallf89e55a2010-11-18 06:31:45 +00009315 ExprValueKind VK = VK_RValue;
9316 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00009317 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00009318 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00009319 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00009320 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00009321 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00009322 } else {
9323 // The conditional expression is required to be a constant expression.
9324 llvm::APSInt condEval(32);
9325 SourceLocation ExpLoc;
9326 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00009327 return ExprError(Diag(ExpLoc,
9328 diag::err_typecheck_choose_expr_requires_constant)
9329 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00009330
Sebastian Redl28507842009-02-26 14:39:58 +00009331 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00009332 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9333
9334 resType = ActiveExpr->getType();
9335 ValueDependent = ActiveExpr->isValueDependent();
9336 VK = ActiveExpr->getValueKind();
9337 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00009338 }
9339
Sebastian Redlf53597f2009-03-15 17:47:39 +00009340 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00009341 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00009342 resType->isDependentType(),
9343 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00009344}
9345
Steve Naroff4eb206b2008-09-03 18:15:37 +00009346//===----------------------------------------------------------------------===//
9347// Clang Extensions.
9348//===----------------------------------------------------------------------===//
9349
9350/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00009351void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009352 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9353 PushBlockScope(BlockScope, Block);
9354 CurContext->addDecl(Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009355 if (BlockScope)
9356 PushDeclContext(BlockScope, Block);
9357 else
9358 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00009359}
9360
Mike Stump98eb8a72009-02-04 22:31:32 +00009361void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00009362 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00009363 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009364 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009365
John McCallbf1a0282010-06-04 23:28:52 +00009366 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00009367 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00009368
John McCall711c52b2011-01-05 12:14:39 +00009369 // GetTypeForDeclarator always produces a function type for a block
9370 // literal signature. Furthermore, it is always a FunctionProtoType
9371 // unless the function was written with a typedef.
9372 assert(T->isFunctionType() &&
9373 "GetTypeForDeclarator made a non-function block signature");
9374
9375 // Look for an explicit signature in that function type.
9376 FunctionProtoTypeLoc ExplicitSignature;
9377
9378 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9379 if (isa<FunctionProtoTypeLoc>(tmp)) {
9380 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9381
9382 // Check whether that explicit signature was synthesized by
9383 // GetTypeForDeclarator. If so, don't save that as part of the
9384 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00009385 if (ExplicitSignature.getLocalRangeBegin() ==
9386 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00009387 // This would be much cheaper if we stored TypeLocs instead of
9388 // TypeSourceInfos.
9389 TypeLoc Result = ExplicitSignature.getResultLoc();
9390 unsigned Size = Result.getFullDataSize();
9391 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9392 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9393
9394 ExplicitSignature = FunctionProtoTypeLoc();
9395 }
John McCall82dc0092010-06-04 11:21:44 +00009396 }
Mike Stump1eb44332009-09-09 15:08:12 +00009397
John McCall711c52b2011-01-05 12:14:39 +00009398 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9399 CurBlock->FunctionType = T;
9400
9401 const FunctionType *Fn = T->getAs<FunctionType>();
9402 QualType RetTy = Fn->getResultType();
9403 bool isVariadic =
9404 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9405
John McCallc71a4912010-06-04 19:02:56 +00009406 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00009407
John McCall82dc0092010-06-04 11:21:44 +00009408 // Don't allow returning a objc interface by value.
9409 if (RetTy->isObjCObjectType()) {
9410 Diag(ParamInfo.getSourceRange().getBegin(),
9411 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9412 return;
9413 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009414
John McCall82dc0092010-06-04 11:21:44 +00009415 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00009416 // return type. TODO: what should we do with declarators like:
9417 // ^ * { ... }
9418 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00009419 if (RetTy != Context.DependentTy)
9420 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009421
John McCall82dc0092010-06-04 11:21:44 +00009422 // Push block parameters from the declarator if we had them.
John McCallc71a4912010-06-04 19:02:56 +00009423 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00009424 if (ExplicitSignature) {
9425 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9426 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009427 if (Param->getIdentifier() == 0 &&
9428 !Param->isImplicit() &&
9429 !Param->isInvalidDecl() &&
9430 !getLangOptions().CPlusPlus)
9431 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00009432 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00009433 }
John McCall82dc0092010-06-04 11:21:44 +00009434
9435 // Fake up parameter variables if we have a typedef, like
9436 // ^ fntype { ... }
9437 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9438 for (FunctionProtoType::arg_type_iterator
9439 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9440 ParmVarDecl *Param =
9441 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9442 ParamInfo.getSourceRange().getBegin(),
9443 *I);
John McCallc71a4912010-06-04 19:02:56 +00009444 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00009445 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009446 }
John McCall82dc0092010-06-04 11:21:44 +00009447
John McCallc71a4912010-06-04 19:02:56 +00009448 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00009449 if (!Params.empty()) {
John McCallc71a4912010-06-04 19:02:56 +00009450 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregor82aa7132010-11-01 18:37:59 +00009451 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9452 CurBlock->TheDecl->param_end(),
9453 /*CheckParameterNames=*/false);
9454 }
9455
John McCall82dc0092010-06-04 11:21:44 +00009456 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009457 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00009458
John McCallc71a4912010-06-04 19:02:56 +00009459 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00009460 Diag(ParamInfo.getAttributes()->getLoc(),
9461 diag::warn_attribute_sentinel_not_variadic) << 1;
9462 // FIXME: remove the attribute.
9463 }
9464
9465 // Put the parameter variables in scope. We can bail out immediately
9466 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00009467 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00009468 return;
9469
Steve Naroff090276f2008-10-10 01:28:17 +00009470 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00009471 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9472 (*AI)->setOwningFunction(CurBlock->TheDecl);
9473
Steve Naroff090276f2008-10-10 01:28:17 +00009474 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00009475 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009476 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00009477
Steve Naroff090276f2008-10-10 01:28:17 +00009478 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00009479 }
John McCall7a9813c2010-01-22 00:28:27 +00009480 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00009481}
9482
9483/// ActOnBlockError - If there is an error parsing a block, this callback
9484/// is invoked to pop the information about the block from the action impl.
9485void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00009486 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00009487 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009488 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009489}
9490
9491/// ActOnBlockStmtExpr - This is called when the body of a block statement
9492/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00009493ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00009494 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00009495 // If blocks are disabled, emit an error.
9496 if (!LangOpts.Blocks)
9497 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00009498
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009499 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00009500
Steve Naroff090276f2008-10-10 01:28:17 +00009501 PopDeclContext();
9502
Steve Naroff4eb206b2008-09-03 18:15:37 +00009503 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00009504 if (!BSI->ReturnType.isNull())
9505 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00009506
Mike Stump56925862009-07-28 22:04:01 +00009507 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00009508 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00009509
John McCall469a1eb2011-02-02 13:00:07 +00009510 // Set the captured variables on the block.
John McCall6b5a61b2011-02-07 10:33:21 +00009511 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
9512 BSI->CapturesCXXThis);
John McCall469a1eb2011-02-02 13:00:07 +00009513
John McCallc71a4912010-06-04 19:02:56 +00009514 // If the user wrote a function type in some form, try to use that.
9515 if (!BSI->FunctionType.isNull()) {
9516 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9517
9518 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9519 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9520
9521 // Turn protoless block types into nullary block types.
9522 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00009523 FunctionProtoType::ExtProtoInfo EPI;
9524 EPI.ExtInfo = Ext;
9525 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009526
9527 // Otherwise, if we don't need to change anything about the function type,
9528 // preserve its sugar structure.
9529 } else if (FTy->getResultType() == RetTy &&
9530 (!NoReturn || FTy->getNoReturnAttr())) {
9531 BlockTy = BSI->FunctionType;
9532
9533 // Otherwise, make the minimal modifications to the function type.
9534 } else {
9535 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00009536 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9537 EPI.TypeQuals = 0; // FIXME: silently?
9538 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00009539 BlockTy = Context.getFunctionType(RetTy,
9540 FPT->arg_type_begin(),
9541 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00009542 EPI);
John McCallc71a4912010-06-04 19:02:56 +00009543 }
9544
9545 // If we don't have a function type, just build one from nothing.
9546 } else {
John McCalle23cf432010-12-14 08:05:40 +00009547 FunctionProtoType::ExtProtoInfo EPI;
Eli Friedmana49218e2011-04-09 08:18:08 +00009548 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, false, 0, CC_Default);
John McCalle23cf432010-12-14 08:05:40 +00009549 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00009550 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009551
John McCallc71a4912010-06-04 19:02:56 +00009552 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9553 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00009554 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009555
Chris Lattner17a78302009-04-19 05:28:12 +00009556 // If needed, diagnose invalid gotos and switches in the block.
John McCall781472f2010-08-25 08:40:02 +00009557 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00009558 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00009559
Chris Lattnere476bdc2011-02-17 23:58:47 +00009560 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009561
John McCall469a1eb2011-02-02 13:00:07 +00009562 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCalle0054f62010-08-25 05:56:39 +00009563
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00009564 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9565 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00009566 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00009567}
9568
John McCall60d7b3a2010-08-24 06:29:42 +00009569ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallb3d87482010-08-24 05:47:05 +00009570 Expr *expr, ParsedType type,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009571 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009572 TypeSourceInfo *TInfo;
Jeffrey Yasskindec09842011-01-18 02:00:16 +00009573 GetTypeFromParser(type, &TInfo);
John McCall9ae2f072010-08-23 23:25:46 +00009574 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009575}
9576
John McCall60d7b3a2010-08-24 06:29:42 +00009577ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00009578 Expr *E, TypeSourceInfo *TInfo,
9579 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009580 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00009581
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009582 // Get the va_list type
9583 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009584 if (VaListType->isArrayType()) {
9585 // Deal with implicit array decay; for example, on x86-64,
9586 // va_list is an array, but it's supposed to decay to
9587 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009588 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00009589 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00009590 ExprResult Result = UsualUnaryConversions(E);
9591 if (Result.isInvalid())
9592 return ExprError();
9593 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00009594 } else {
9595 // Otherwise, the va_list argument must be an l-value because
9596 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00009597 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00009598 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00009599 return ExprError();
9600 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00009601
Douglas Gregordd027302009-05-19 23:10:31 +00009602 if (!E->isTypeDependent() &&
9603 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00009604 return ExprError(Diag(E->getLocStart(),
9605 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00009606 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00009607 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009608
Eli Friedmanb1d796d2009-03-23 00:24:07 +00009609 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009610 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00009611
Abramo Bagnara2cad9002010-08-10 10:06:15 +00009612 QualType T = TInfo->getType().getNonLValueExprType(Context);
9613 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00009614}
9615
John McCall60d7b3a2010-08-24 06:29:42 +00009616ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009617 // The type of __null will be int or long, depending on the size of
9618 // pointers on the target.
9619 QualType Ty;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009620 unsigned pw = Context.Target.getPointerWidth(0);
9621 if (pw == Context.Target.getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009622 Ty = Context.IntTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009623 else if (pw == Context.Target.getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009624 Ty = Context.LongTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00009625 else if (pw == Context.Target.getLongLongWidth())
9626 Ty = Context.LongLongTy;
9627 else {
9628 assert(!"I don't know size of pointer!");
9629 Ty = Context.IntTy;
9630 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009631
Sebastian Redlf53597f2009-03-15 17:47:39 +00009632 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00009633}
9634
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009635static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00009636 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009637 if (!SemaRef.getLangOptions().ObjC1)
9638 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009639
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009640 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9641 if (!PT)
9642 return;
9643
9644 // Check if the destination is of type 'id'.
9645 if (!PT->isObjCIdType()) {
9646 // Check if the destination is the 'NSString' interface.
9647 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9648 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9649 return;
9650 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009651
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009652 // Strip off any parens and casts.
9653 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
9654 if (!SL || SL->isWide())
9655 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009656
Douglas Gregor849b2432010-03-31 17:46:05 +00009657 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009658}
9659
Chris Lattner5cf216b2008-01-04 18:04:52 +00009660bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9661 SourceLocation Loc,
9662 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00009663 Expr *SrcExpr, AssignmentAction Action,
9664 bool *Complained) {
9665 if (Complained)
9666 *Complained = false;
9667
Chris Lattner5cf216b2008-01-04 18:04:52 +00009668 // Decode the result (notice that AST's are still created for extensions).
9669 bool isInvalid = false;
9670 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00009671 FixItHint Hint;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009672
Chris Lattner5cf216b2008-01-04 18:04:52 +00009673 switch (ConvTy) {
9674 default: assert(0 && "Unknown conversion type");
9675 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009676 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00009677 DiagKind = diag::ext_typecheck_convert_pointer_int;
9678 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00009679 case IntToPointer:
9680 DiagKind = diag::ext_typecheck_convert_int_pointer;
9681 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009682 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00009683 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00009684 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9685 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00009686 case IncompatiblePointerSign:
9687 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9688 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009689 case FunctionVoidPointer:
9690 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9691 break;
John McCall86c05f32011-02-01 00:10:29 +00009692 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00009693 // Perform array-to-pointer decay if necessary.
9694 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9695
John McCall86c05f32011-02-01 00:10:29 +00009696 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9697 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9698 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9699 DiagKind = diag::err_typecheck_incompatible_address_space;
9700 break;
9701 }
9702
9703 llvm_unreachable("unknown error case for discarding qualifiers!");
9704 // fallthrough
9705 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00009706 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00009707 // If the qualifiers lost were because we were applying the
9708 // (deprecated) C++ conversion from a string literal to a char*
9709 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9710 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00009711 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00009712 // bit of refactoring (so that the second argument is an
9713 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00009714 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00009715 // C++ semantics.
9716 if (getLangOptions().CPlusPlus &&
9717 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9718 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009719 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9720 break;
Sean Huntc9132b62009-11-08 07:46:34 +00009721 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00009722 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00009723 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009724 case IntToBlockPointer:
9725 DiagKind = diag::err_int_to_block_pointer;
9726 break;
9727 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00009728 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00009729 break;
Steve Naroff39579072008-10-14 22:18:38 +00009730 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00009731 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00009732 // it can give a more specific diagnostic.
9733 DiagKind = diag::warn_incompatible_qualified_id;
9734 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00009735 case IncompatibleVectors:
9736 DiagKind = diag::warn_incompatible_vectors;
9737 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009738 case Incompatible:
9739 DiagKind = diag::err_typecheck_convert_incompatible;
9740 isInvalid = true;
9741 break;
9742 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009743
Douglas Gregord4eea832010-04-09 00:35:39 +00009744 QualType FirstType, SecondType;
9745 switch (Action) {
9746 case AA_Assigning:
9747 case AA_Initializing:
9748 // The destination type comes first.
9749 FirstType = DstType;
9750 SecondType = SrcType;
9751 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009752
Douglas Gregord4eea832010-04-09 00:35:39 +00009753 case AA_Returning:
9754 case AA_Passing:
9755 case AA_Converting:
9756 case AA_Sending:
9757 case AA_Casting:
9758 // The source type comes first.
9759 FirstType = SrcType;
9760 SecondType = DstType;
9761 break;
9762 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009763
Douglas Gregord4eea832010-04-09 00:35:39 +00009764 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00009765 << SrcExpr->getSourceRange() << Hint;
Douglas Gregora41a8c52010-04-22 00:20:18 +00009766 if (Complained)
9767 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00009768 return isInvalid;
9769}
Anders Carlssone21555e2008-11-30 19:50:32 +00009770
Chris Lattner3bf68932009-04-25 21:59:05 +00009771bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009772 llvm::APSInt ICEResult;
9773 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9774 if (Result)
9775 *Result = ICEResult;
9776 return false;
9777 }
9778
Anders Carlssone21555e2008-11-30 19:50:32 +00009779 Expr::EvalResult EvalResult;
9780
Mike Stumpeed9cac2009-02-19 03:04:26 +00009781 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00009782 EvalResult.HasSideEffects) {
9783 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9784
9785 if (EvalResult.Diag) {
9786 // We only show the note if it's not the usual "invalid subexpression"
9787 // or if it's actually in a subexpression.
9788 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9789 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9790 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9791 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00009792
Anders Carlssone21555e2008-11-30 19:50:32 +00009793 return true;
9794 }
9795
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009796 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9797 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00009798
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009799 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00009800 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9801 != Diagnostic::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +00009802 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00009803
Anders Carlssone21555e2008-11-30 19:50:32 +00009804 if (Result)
9805 *Result = EvalResult.Val.getInt();
9806 return false;
9807}
Douglas Gregore0762c92009-06-19 23:52:42 +00009808
Douglas Gregor2afce722009-11-26 00:44:06 +00009809void
Mike Stump1eb44332009-09-09 15:08:12 +00009810Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009811 ExprEvalContexts.push_back(
9812 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00009813}
9814
Mike Stump1eb44332009-09-09 15:08:12 +00009815void
Douglas Gregor2afce722009-11-26 00:44:06 +00009816Sema::PopExpressionEvaluationContext() {
9817 // Pop the current expression evaluation context off the stack.
9818 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9819 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009820
Douglas Gregor06d33692009-12-12 07:57:52 +00009821 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9822 if (Rec.PotentiallyReferenced) {
9823 // Mark any remaining declarations in the current position of the stack
9824 // as "referenced". If they were not meant to be referenced, semantic
9825 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009826 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00009827 I = Rec.PotentiallyReferenced->begin(),
9828 IEnd = Rec.PotentiallyReferenced->end();
9829 I != IEnd; ++I)
9830 MarkDeclarationReferenced(I->first, I->second);
9831 }
9832
9833 if (Rec.PotentiallyDiagnosed) {
9834 // Emit any pending diagnostics.
9835 for (PotentiallyEmittedDiagnostics::iterator
9836 I = Rec.PotentiallyDiagnosed->begin(),
9837 IEnd = Rec.PotentiallyDiagnosed->end();
9838 I != IEnd; ++I)
9839 Diag(I->first, I->second);
9840 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009841 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009842
9843 // When are coming out of an unevaluated context, clear out any
9844 // temporaries that we may have created as part of the evaluation of
9845 // the expression in that context: they aren't relevant because they
9846 // will never be constructed.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009847 if (Rec.Context == Unevaluated &&
Douglas Gregor2afce722009-11-26 00:44:06 +00009848 ExprTemporaries.size() > Rec.NumTemporaries)
9849 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9850 ExprTemporaries.end());
9851
9852 // Destroy the popped expression evaluation record.
9853 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009854}
Douglas Gregore0762c92009-06-19 23:52:42 +00009855
9856/// \brief Note that the given declaration was referenced in the source code.
9857///
9858/// This routine should be invoke whenever a given declaration is referenced
9859/// in the source code, and where that reference occurred. If this declaration
9860/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9861/// C99 6.9p3), then the declaration will be marked as used.
9862///
9863/// \param Loc the location where the declaration was referenced.
9864///
9865/// \param D the declaration that has been referenced by the source code.
9866void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9867 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00009868
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +00009869 D->setReferenced();
9870
Douglas Gregorc070cc62010-06-17 23:14:26 +00009871 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009872 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009873
Douglas Gregorb5352cf2009-10-08 21:35:42 +00009874 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9875 // template or not. The reason for this is that unevaluated expressions
9876 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9877 // -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009878 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009879 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +00009880 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009881 return;
9882 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009883
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009884 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9885 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009886
Douglas Gregore0762c92009-06-19 23:52:42 +00009887 // Do not mark anything as "used" within a dependent context; wait for
9888 // an instantiation.
9889 if (CurContext->isDependentContext())
9890 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009891
Douglas Gregor2afce722009-11-26 00:44:06 +00009892 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00009893 case Unevaluated:
9894 // We are in an expression that is not potentially evaluated; do nothing.
9895 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009896
Douglas Gregorac7610d2009-06-22 20:57:11 +00009897 case PotentiallyEvaluated:
9898 // We are in a potentially-evaluated expression, so this declaration is
9899 // "used"; handle this below.
9900 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009901
Douglas Gregorac7610d2009-06-22 20:57:11 +00009902 case PotentiallyPotentiallyEvaluated:
9903 // We are in an expression that may be potentially evaluated; queue this
9904 // declaration reference until we know whether the expression is
9905 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00009906 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00009907 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009908
9909 case PotentiallyEvaluatedIfUsed:
9910 // Referenced declarations will only be used if the construct in the
9911 // containing expression is used.
9912 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009913 }
Mike Stump1eb44332009-09-09 15:08:12 +00009914
Douglas Gregore0762c92009-06-19 23:52:42 +00009915 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00009916 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009917 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00009918 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00009919 if (Constructor->getParent()->hasTrivialConstructor())
9920 return;
9921 if (!Constructor->isUsed(false))
9922 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00009923 } else if (Constructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00009924 Constructor->isCopyConstructor(TypeQuals)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009925 if (!Constructor->isUsed(false))
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009926 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9927 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009928
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009929 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009930 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009931 if (Destructor->isImplicit() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009932 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009933 if (Destructor->isVirtual())
9934 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009935 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9936 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9937 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009938 if (!MethodDecl->isUsed(false))
Douglas Gregor39957dc2010-05-01 15:04:51 +00009939 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009940 } else if (MethodDecl->isVirtual())
9941 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009942 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00009943 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall15e310a2011-02-19 02:53:41 +00009944 // Recursive functions should be marked when used from another function.
9945 if (CurContext == Function) return;
9946
Mike Stump1eb44332009-09-09 15:08:12 +00009947 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00009948 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00009949 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009950 bool AlreadyInstantiated = false;
9951 if (FunctionTemplateSpecializationInfo *SpecInfo
9952 = Function->getTemplateSpecializationInfo()) {
9953 if (SpecInfo->getPointOfInstantiation().isInvalid())
9954 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009955 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009956 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009957 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009958 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009959 = Function->getMemberSpecializationInfo()) {
9960 if (MSInfo->getPointOfInstantiation().isInvalid())
9961 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009962 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009963 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009964 AlreadyInstantiated = true;
9965 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009966
Douglas Gregor60406be2010-01-16 22:29:39 +00009967 if (!AlreadyInstantiated) {
9968 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9969 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9970 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9971 Loc));
9972 else
Chandler Carruth62c78d52010-08-25 08:44:16 +00009973 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +00009974 }
John McCall15e310a2011-02-19 02:53:41 +00009975 } else {
9976 // Walk redefinitions, as some of them may be instantiable.
Gabor Greif40181c42010-08-28 00:16:06 +00009977 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9978 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +00009979 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +00009980 MarkDeclarationReferenced(Loc, *i);
9981 }
John McCall15e310a2011-02-19 02:53:41 +00009982 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009983
John McCall15e310a2011-02-19 02:53:41 +00009984 // Keep track of used but undefined functions.
9985 if (!Function->isPure() && !Function->hasBody() &&
9986 Function->getLinkage() != ExternalLinkage) {
9987 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9988 if (old.isInvalid()) old = Loc;
9989 }
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +00009990
John McCall15e310a2011-02-19 02:53:41 +00009991 Function->setUsed(true);
Douglas Gregore0762c92009-06-19 23:52:42 +00009992 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009993 }
Mike Stump1eb44332009-09-09 15:08:12 +00009994
Douglas Gregore0762c92009-06-19 23:52:42 +00009995 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00009996 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00009997 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009998 Var->getInstantiatedFromStaticDataMember()) {
9999 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10000 assert(MSInfo && "Missing member specialization information?");
10001 if (MSInfo->getPointOfInstantiation().isInvalid() &&
10002 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
10003 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redlf79a7192011-04-29 08:19:30 +000010004 // This is a modification of an existing AST node. Notify listeners.
10005 if (ASTMutationListener *L = getASTMutationListener())
10006 L->StaticDataMemberInstantiated(Var);
Chandler Carruth62c78d52010-08-25 08:44:16 +000010007 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +000010008 }
10009 }
Mike Stump1eb44332009-09-09 15:08:12 +000010010
John McCall77efc682011-02-21 19:25:48 +000010011 // Keep track of used but undefined variables. We make a hole in
10012 // the warning for static const data members with in-line
10013 // initializers.
John McCall15e310a2011-02-19 02:53:41 +000010014 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall77efc682011-02-21 19:25:48 +000010015 && Var->getLinkage() != ExternalLinkage
10016 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall15e310a2011-02-19 02:53:41 +000010017 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
10018 if (old.isInvalid()) old = Loc;
10019 }
Douglas Gregor7caa6822009-07-24 20:34:43 +000010020
Douglas Gregore0762c92009-06-19 23:52:42 +000010021 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +000010022 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +000010023 }
Douglas Gregore0762c92009-06-19 23:52:42 +000010024}
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010025
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010026namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010027 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010028 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010029 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010030 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10031 Sema &S;
10032 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010033
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010034 public:
10035 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010036
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010037 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010038
10039 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10040 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010041 };
10042}
10043
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010044bool MarkReferencedDecls::TraverseTemplateArgument(
10045 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010046 if (Arg.getKind() == TemplateArgument::Declaration) {
10047 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
10048 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010049
10050 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010051}
10052
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010053bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010054 if (ClassTemplateSpecializationDecl *Spec
10055 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10056 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +000010057 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010058 }
10059
Chandler Carruthe3e210c2010-06-10 10:31:57 +000010060 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010061}
10062
10063void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10064 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +000010065 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000010066}
10067
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010068namespace {
10069 /// \brief Helper class that marks all of the declarations referenced by
10070 /// potentially-evaluated subexpressions as "referenced".
10071 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10072 Sema &S;
10073
10074 public:
10075 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10076
10077 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
10078
10079 void VisitDeclRefExpr(DeclRefExpr *E) {
10080 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10081 }
10082
10083 void VisitMemberExpr(MemberExpr *E) {
10084 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010085 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010086 }
10087
10088 void VisitCXXNewExpr(CXXNewExpr *E) {
10089 if (E->getConstructor())
10090 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
10091 if (E->getOperatorNew())
10092 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
10093 if (E->getOperatorDelete())
10094 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010095 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010096 }
10097
10098 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10099 if (E->getOperatorDelete())
10100 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +000010101 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10102 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10103 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10104 S.MarkDeclarationReferenced(E->getLocStart(),
10105 S.LookupDestructor(Record));
10106 }
10107
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010108 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010109 }
10110
10111 void VisitCXXConstructExpr(CXXConstructExpr *E) {
10112 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +000010113 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010114 }
10115
10116 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
10117 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10118 }
Douglas Gregor102ff972010-10-19 17:17:35 +000010119
10120 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10121 Visit(E->getExpr());
10122 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010123 };
10124}
10125
10126/// \brief Mark any declarations that appear within this expression or any
10127/// potentially-evaluated subexpressions as "referenced".
10128void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
10129 EvaluatedExprMarker(*this).Visit(E);
10130}
10131
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010132/// \brief Emit a diagnostic that describes an effect on the run-time behavior
10133/// of the program being compiled.
10134///
10135/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010136/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010137/// possibility that the code will actually be executable. Code in sizeof()
10138/// expressions, code used only during overload resolution, etc., are not
10139/// potentially evaluated. This routine will suppress such diagnostics or,
10140/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010141/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010142/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010143///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010144/// This routine should be used for all diagnostics that describe the run-time
10145/// behavior of a program, such as passing a non-POD value through an ellipsis.
10146/// Failure to do so will likely result in spurious diagnostics or failures
10147/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek762696f2011-02-23 01:51:43 +000010148bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010149 const PartialDiagnostic &PD) {
10150 switch (ExprEvalContexts.back().Context ) {
10151 case Unevaluated:
10152 // The argument will never be evaluated, so don't complain.
10153 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010154
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010155 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000010156 case PotentiallyEvaluatedIfUsed:
Ted Kremenek351ba912011-02-23 01:52:04 +000010157 if (stmt && getCurFunctionOrMethodDecl()) {
10158 FunctionScopes.back()->PossiblyUnreachableDiags.
10159 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
10160 }
10161 else
10162 Diag(Loc, PD);
10163
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010164 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010165
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +000010166 case PotentiallyPotentiallyEvaluated:
10167 ExprEvalContexts.back().addDiagnostic(Loc, PD);
10168 break;
10169 }
10170
10171 return false;
10172}
10173
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010174bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
10175 CallExpr *CE, FunctionDecl *FD) {
10176 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
10177 return false;
10178
10179 PartialDiagnostic Note =
10180 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
10181 << FD->getDeclName() : PDiag();
10182 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010183
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010184 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010185 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010186 PDiag(diag::err_call_function_incomplete_return)
10187 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000010188 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +000010189 << CE->getSourceRange(),
10190 std::make_pair(NoteLoc, Note)))
10191 return true;
10192
10193 return false;
10194}
10195
Douglas Gregor92c3a042011-01-19 16:50:08 +000010196// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +000010197// will prevent this condition from triggering, which is what we want.
10198void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
10199 SourceLocation Loc;
10200
John McCalla52ef082009-11-11 02:41:58 +000010201 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +000010202 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +000010203
John McCall5a881bb2009-10-12 21:59:07 +000010204 if (isa<BinaryOperator>(E)) {
10205 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +000010206 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +000010207 return;
10208
Douglas Gregor92c3a042011-01-19 16:50:08 +000010209 IsOrAssign = Op->getOpcode() == BO_OrAssign;
10210
John McCallc8d8ac52009-11-12 00:06:05 +000010211 // Greylist some idioms by putting them into a warning subcategory.
10212 if (ObjCMessageExpr *ME
10213 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
10214 Selector Sel = ME->getSelector();
10215
John McCallc8d8ac52009-11-12 00:06:05 +000010216 // self = [<foo> init...]
Douglas Gregor813d8342011-02-18 22:29:55 +000010217 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +000010218 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10219
10220 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +000010221 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +000010222 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10223 }
John McCalla52ef082009-11-11 02:41:58 +000010224
John McCall5a881bb2009-10-12 21:59:07 +000010225 Loc = Op->getOperatorLoc();
10226 } else if (isa<CXXOperatorCallExpr>(E)) {
10227 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +000010228 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +000010229 return;
10230
Douglas Gregor92c3a042011-01-19 16:50:08 +000010231 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +000010232 Loc = Op->getOperatorLoc();
10233 } else {
10234 // Not an assignment.
10235 return;
10236 }
10237
Douglas Gregor55b38842010-04-14 16:09:52 +000010238 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +000010239
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000010240 SourceLocation Open = E->getSourceRange().getBegin();
10241 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
10242 Diag(Loc, diag::note_condition_assign_silence)
10243 << FixItHint::CreateInsertion(Open, "(")
10244 << FixItHint::CreateInsertion(Close, ")");
10245
Douglas Gregor92c3a042011-01-19 16:50:08 +000010246 if (IsOrAssign)
10247 Diag(Loc, diag::note_condition_or_assign_to_comparison)
10248 << FixItHint::CreateReplacement(Loc, "!=");
10249 else
10250 Diag(Loc, diag::note_condition_assign_to_comparison)
10251 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +000010252}
10253
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010254/// \brief Redundant parentheses over an equality comparison can indicate
10255/// that the user intended an assignment used as condition.
10256void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000010257 // Don't warn if the parens came from a macro.
10258 SourceLocation parenLoc = parenE->getLocStart();
10259 if (parenLoc.isInvalid() || parenLoc.isMacroID())
10260 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +000010261 // Don't warn for dependent expressions.
10262 if (parenE->isTypeDependent())
10263 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +000010264
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010265 Expr *E = parenE->IgnoreParens();
10266
10267 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +000010268 if (opE->getOpcode() == BO_EQ &&
10269 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
10270 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010271 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +000010272
Ted Kremenekf7275cd2011-02-02 02:20:30 +000010273 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +000010274 Diag(Loc, diag::note_equality_comparison_silence)
10275 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
10276 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +000010277 Diag(Loc, diag::note_equality_comparison_to_assign)
10278 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010279 }
10280}
10281
John Wiegley429bb272011-04-08 18:41:53 +000010282ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +000010283 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +000010284 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
10285 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +000010286
John McCall864c0412011-04-26 20:42:42 +000010287 ExprResult result = CheckPlaceholderExpr(E);
10288 if (result.isInvalid()) return ExprError();
10289 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +000010290
John McCall864c0412011-04-26 20:42:42 +000010291 if (!E->isTypeDependent()) {
John McCallf6a16482010-12-04 03:47:34 +000010292 if (getLangOptions().CPlusPlus)
10293 return CheckCXXBooleanCondition(E); // C++ 6.4p4
10294
John Wiegley429bb272011-04-08 18:41:53 +000010295 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
10296 if (ERes.isInvalid())
10297 return ExprError();
10298 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +000010299
10300 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +000010301 if (!T->isScalarType()) { // C99 6.8.4.1p1
10302 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
10303 << T << E->getSourceRange();
10304 return ExprError();
10305 }
John McCall5a881bb2009-10-12 21:59:07 +000010306 }
10307
John Wiegley429bb272011-04-08 18:41:53 +000010308 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +000010309}
Douglas Gregor586596f2010-05-06 17:25:47 +000010310
John McCall60d7b3a2010-08-24 06:29:42 +000010311ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
10312 Expr *Sub) {
Douglas Gregoreecf38f2010-05-06 21:39:56 +000010313 if (!Sub)
Douglas Gregor586596f2010-05-06 17:25:47 +000010314 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010315
10316 return CheckBooleanCondition(Sub, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +000010317}
John McCall2a984ca2010-10-12 00:20:44 +000010318
John McCall1de4d4e2011-04-07 08:22:57 +000010319namespace {
John McCall755d8492011-04-12 00:42:48 +000010320 /// A visitor for rebuilding a call to an __unknown_any expression
10321 /// to have an appropriate type.
10322 struct RebuildUnknownAnyFunction
10323 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
10324
10325 Sema &S;
10326
10327 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
10328
10329 ExprResult VisitStmt(Stmt *S) {
10330 llvm_unreachable("unexpected statement!");
10331 return ExprError();
10332 }
10333
10334 ExprResult VisitExpr(Expr *expr) {
10335 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
10336 << expr->getSourceRange();
10337 return ExprError();
10338 }
10339
10340 /// Rebuild an expression which simply semantically wraps another
10341 /// expression which it shares the type and value kind of.
10342 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10343 ExprResult subResult = Visit(expr->getSubExpr());
10344 if (subResult.isInvalid()) return ExprError();
10345
10346 Expr *subExpr = subResult.take();
10347 expr->setSubExpr(subExpr);
10348 expr->setType(subExpr->getType());
10349 expr->setValueKind(subExpr->getValueKind());
10350 assert(expr->getObjectKind() == OK_Ordinary);
10351 return expr;
10352 }
10353
10354 ExprResult VisitParenExpr(ParenExpr *paren) {
10355 return rebuildSugarExpr(paren);
10356 }
10357
10358 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10359 return rebuildSugarExpr(op);
10360 }
10361
10362 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10363 ExprResult subResult = Visit(op->getSubExpr());
10364 if (subResult.isInvalid()) return ExprError();
10365
10366 Expr *subExpr = subResult.take();
10367 op->setSubExpr(subExpr);
10368 op->setType(S.Context.getPointerType(subExpr->getType()));
10369 assert(op->getValueKind() == VK_RValue);
10370 assert(op->getObjectKind() == OK_Ordinary);
10371 return op;
10372 }
10373
10374 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
10375 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
10376
10377 expr->setType(decl->getType());
10378
10379 assert(expr->getValueKind() == VK_RValue);
10380 if (S.getLangOptions().CPlusPlus &&
10381 !(isa<CXXMethodDecl>(decl) &&
10382 cast<CXXMethodDecl>(decl)->isInstance()))
10383 expr->setValueKind(VK_LValue);
10384
10385 return expr;
10386 }
10387
10388 ExprResult VisitMemberExpr(MemberExpr *mem) {
10389 return resolveDecl(mem, mem->getMemberDecl());
10390 }
10391
10392 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
10393 return resolveDecl(ref, ref->getDecl());
10394 }
10395 };
10396}
10397
10398/// Given a function expression of unknown-any type, try to rebuild it
10399/// to have a function type.
10400static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
10401 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
10402 if (result.isInvalid()) return ExprError();
10403 return S.DefaultFunctionArrayConversion(result.take());
10404}
10405
10406namespace {
John McCall379b5152011-04-11 07:02:50 +000010407 /// A visitor for rebuilding an expression of type __unknown_anytype
10408 /// into one which resolves the type directly on the referring
10409 /// expression. Strict preservation of the original source
10410 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +000010411 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +000010412 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +000010413
10414 Sema &S;
10415
10416 /// The current destination type.
10417 QualType DestType;
10418
10419 RebuildUnknownAnyExpr(Sema &S, QualType castType)
10420 : S(S), DestType(castType) {}
10421
John McCalla5fc4722011-04-09 22:50:59 +000010422 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +000010423 llvm_unreachable("unexpected statement!");
John McCalla5fc4722011-04-09 22:50:59 +000010424 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000010425 }
10426
John McCall379b5152011-04-11 07:02:50 +000010427 ExprResult VisitExpr(Expr *expr) {
10428 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10429 << expr->getSourceRange();
10430 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000010431 }
10432
John McCall379b5152011-04-11 07:02:50 +000010433 ExprResult VisitCallExpr(CallExpr *call);
10434 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
10435
John McCalla5fc4722011-04-09 22:50:59 +000010436 /// Rebuild an expression which simply semantically wraps another
10437 /// expression which it shares the type and value kind of.
10438 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10439 ExprResult subResult = Visit(expr->getSubExpr());
John McCall755d8492011-04-12 00:42:48 +000010440 if (subResult.isInvalid()) return ExprError();
John McCalla5fc4722011-04-09 22:50:59 +000010441 Expr *subExpr = subResult.take();
10442 expr->setSubExpr(subExpr);
10443 expr->setType(subExpr->getType());
10444 expr->setValueKind(subExpr->getValueKind());
10445 assert(expr->getObjectKind() == OK_Ordinary);
10446 return expr;
10447 }
John McCall1de4d4e2011-04-07 08:22:57 +000010448
John McCalla5fc4722011-04-09 22:50:59 +000010449 ExprResult VisitParenExpr(ParenExpr *paren) {
10450 return rebuildSugarExpr(paren);
10451 }
10452
10453 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10454 return rebuildSugarExpr(op);
10455 }
10456
John McCall755d8492011-04-12 00:42:48 +000010457 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10458 const PointerType *ptr = DestType->getAs<PointerType>();
10459 if (!ptr) {
10460 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
10461 << op->getSourceRange();
10462 return ExprError();
10463 }
10464 assert(op->getValueKind() == VK_RValue);
10465 assert(op->getObjectKind() == OK_Ordinary);
10466 op->setType(DestType);
10467
10468 // Build the sub-expression as if it were an object of the pointee type.
10469 DestType = ptr->getPointeeType();
10470 ExprResult subResult = Visit(op->getSubExpr());
10471 if (subResult.isInvalid()) return ExprError();
10472 op->setSubExpr(subResult.take());
10473 return op;
10474 }
10475
John McCall379b5152011-04-11 07:02:50 +000010476 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCalla5fc4722011-04-09 22:50:59 +000010477
John McCall755d8492011-04-12 00:42:48 +000010478 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCalla5fc4722011-04-09 22:50:59 +000010479
John McCall755d8492011-04-12 00:42:48 +000010480 ExprResult VisitMemberExpr(MemberExpr *mem) {
10481 return resolveDecl(mem, mem->getMemberDecl());
10482 }
John McCalla5fc4722011-04-09 22:50:59 +000010483
10484 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall379b5152011-04-11 07:02:50 +000010485 return resolveDecl(ref, ref->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +000010486 }
10487 };
10488}
10489
John McCall379b5152011-04-11 07:02:50 +000010490/// Rebuilds a call expression which yielded __unknown_anytype.
10491ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
10492 Expr *callee = call->getCallee();
10493
10494 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +000010495 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +000010496 FK_FunctionPointer,
10497 FK_BlockPointer
10498 };
10499
10500 FnKind kind;
10501 QualType type = callee->getType();
John McCallf5307512011-04-27 00:36:17 +000010502 if (type == S.Context.BoundMemberTy) {
10503 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
10504 kind = FK_MemberFunction;
10505 type = Expr::findBoundMemberType(callee);
John McCall379b5152011-04-11 07:02:50 +000010506 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
10507 type = ptr->getPointeeType();
10508 kind = FK_FunctionPointer;
10509 } else {
10510 type = type->castAs<BlockPointerType>()->getPointeeType();
10511 kind = FK_BlockPointer;
10512 }
10513 const FunctionType *fnType = type->castAs<FunctionType>();
10514
10515 // Verify that this is a legal result type of a function.
10516 if (DestType->isArrayType() || DestType->isFunctionType()) {
10517 unsigned diagID = diag::err_func_returning_array_function;
10518 if (kind == FK_BlockPointer)
10519 diagID = diag::err_block_returning_array_function;
10520
10521 S.Diag(call->getExprLoc(), diagID)
10522 << DestType->isFunctionType() << DestType;
10523 return ExprError();
10524 }
10525
10526 // Otherwise, go ahead and set DestType as the call's result.
10527 call->setType(DestType.getNonLValueExprType(S.Context));
10528 call->setValueKind(Expr::getValueKindForType(DestType));
10529 assert(call->getObjectKind() == OK_Ordinary);
10530
10531 // Rebuild the function type, replacing the result type with DestType.
10532 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
10533 DestType = S.Context.getFunctionType(DestType,
10534 proto->arg_type_begin(),
10535 proto->getNumArgs(),
10536 proto->getExtProtoInfo());
10537 else
10538 DestType = S.Context.getFunctionNoProtoType(DestType,
10539 fnType->getExtInfo());
10540
10541 // Rebuild the appropriate pointer-to-function type.
10542 switch (kind) {
John McCallf5307512011-04-27 00:36:17 +000010543 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +000010544 // Nothing to do.
10545 break;
10546
10547 case FK_FunctionPointer:
10548 DestType = S.Context.getPointerType(DestType);
10549 break;
10550
10551 case FK_BlockPointer:
10552 DestType = S.Context.getBlockPointerType(DestType);
10553 break;
10554 }
10555
10556 // Finally, we can recurse.
10557 ExprResult calleeResult = Visit(callee);
10558 if (!calleeResult.isUsable()) return ExprError();
10559 call->setCallee(calleeResult.take());
10560
10561 // Bind a temporary if necessary.
10562 return S.MaybeBindToTemporary(call);
10563}
10564
10565ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall755d8492011-04-12 00:42:48 +000010566 ObjCMethodDecl *method = msg->getMethodDecl();
10567 assert(method && "__unknown_anytype message without result type?");
John McCall379b5152011-04-11 07:02:50 +000010568
John McCall755d8492011-04-12 00:42:48 +000010569 // Verify that this is a legal result type of a call.
10570 if (DestType->isArrayType() || DestType->isFunctionType()) {
10571 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
10572 << DestType->isFunctionType() << DestType;
10573 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000010574 }
10575
John McCall755d8492011-04-12 00:42:48 +000010576 assert(method->getResultType() == S.Context.UnknownAnyTy);
10577 method->setResultType(DestType);
10578
John McCall379b5152011-04-11 07:02:50 +000010579 // Change the type of the message.
John McCall755d8492011-04-12 00:42:48 +000010580 msg->setType(DestType.getNonReferenceType());
10581 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +000010582
John McCall755d8492011-04-12 00:42:48 +000010583 return S.MaybeBindToTemporary(msg);
John McCall379b5152011-04-11 07:02:50 +000010584}
10585
10586ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall755d8492011-04-12 00:42:48 +000010587 // The only case we should ever see here is a function-to-pointer decay.
John McCall379b5152011-04-11 07:02:50 +000010588 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall379b5152011-04-11 07:02:50 +000010589 assert(ice->getValueKind() == VK_RValue);
10590 assert(ice->getObjectKind() == OK_Ordinary);
10591
John McCall755d8492011-04-12 00:42:48 +000010592 ice->setType(DestType);
10593
John McCall379b5152011-04-11 07:02:50 +000010594 // Rebuild the sub-expression as the pointee (function) type.
10595 DestType = DestType->castAs<PointerType>()->getPointeeType();
10596
10597 ExprResult result = Visit(ice->getSubExpr());
10598 if (!result.isUsable()) return ExprError();
10599
10600 ice->setSubExpr(result.take());
10601 return S.Owned(ice);
10602}
10603
John McCall755d8492011-04-12 00:42:48 +000010604ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall379b5152011-04-11 07:02:50 +000010605 ExprValueKind valueKind = VK_LValue;
John McCall379b5152011-04-11 07:02:50 +000010606 QualType type = DestType;
10607
10608 // We know how to make this work for certain kinds of decls:
10609
10610 // - functions
John McCall755d8492011-04-12 00:42:48 +000010611 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCall379b5152011-04-11 07:02:50 +000010612 // This is true because FunctionDecls must always have function
10613 // type, so we can't be resolving the entire thing at once.
10614 assert(type->isFunctionType());
10615
John McCallf5307512011-04-27 00:36:17 +000010616 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
10617 if (method->isInstance()) {
10618 valueKind = VK_RValue;
10619 type = S.Context.BoundMemberTy;
10620 }
10621
John McCall379b5152011-04-11 07:02:50 +000010622 // Function references aren't l-values in C.
10623 if (!S.getLangOptions().CPlusPlus)
10624 valueKind = VK_RValue;
10625
10626 // - variables
10627 } else if (isa<VarDecl>(decl)) {
John McCall755d8492011-04-12 00:42:48 +000010628 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
10629 type = refTy->getPointeeType();
John McCall379b5152011-04-11 07:02:50 +000010630 } else if (type->isFunctionType()) {
John McCall755d8492011-04-12 00:42:48 +000010631 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
10632 << decl << expr->getSourceRange();
10633 return ExprError();
John McCall379b5152011-04-11 07:02:50 +000010634 }
10635
10636 // - nothing else
10637 } else {
10638 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10639 << decl << expr->getSourceRange();
10640 return ExprError();
10641 }
10642
John McCall755d8492011-04-12 00:42:48 +000010643 decl->setType(DestType);
10644 expr->setType(type);
10645 expr->setValueKind(valueKind);
10646 return S.Owned(expr);
John McCall379b5152011-04-11 07:02:50 +000010647}
10648
John McCall1de4d4e2011-04-07 08:22:57 +000010649/// Check a cast of an unknown-any type. We intentionally only
10650/// trigger this for C-style casts.
John Wiegley429bb272011-04-08 18:41:53 +000010651ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
10652 Expr *castExpr, CastKind &castKind,
10653 ExprValueKind &VK, CXXCastPath &path) {
John McCall1de4d4e2011-04-07 08:22:57 +000010654 // Rewrite the casted expression from scratch.
John McCalla5fc4722011-04-09 22:50:59 +000010655 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
10656 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +000010657
John McCalla5fc4722011-04-09 22:50:59 +000010658 castExpr = result.take();
10659 VK = castExpr->getValueKind();
10660 castKind = CK_NoOp;
10661
10662 return castExpr;
John McCall1de4d4e2011-04-07 08:22:57 +000010663}
10664
10665static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
10666 Expr *orig = e;
John McCall379b5152011-04-11 07:02:50 +000010667 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +000010668 while (true) {
10669 e = e->IgnoreParenImpCasts();
John McCall379b5152011-04-11 07:02:50 +000010670 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall1de4d4e2011-04-07 08:22:57 +000010671 e = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +000010672 diagID = diag::err_uncasted_call_of_unknown_any;
10673 } else {
John McCall1de4d4e2011-04-07 08:22:57 +000010674 break;
John McCall379b5152011-04-11 07:02:50 +000010675 }
John McCall1de4d4e2011-04-07 08:22:57 +000010676 }
10677
John McCall379b5152011-04-11 07:02:50 +000010678 SourceLocation loc;
10679 NamedDecl *d;
10680 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10681 loc = ref->getLocation();
10682 d = ref->getDecl();
10683 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
10684 loc = mem->getMemberLoc();
10685 d = mem->getMemberDecl();
10686 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
10687 diagID = diag::err_uncasted_call_of_unknown_any;
10688 loc = msg->getSelectorLoc();
10689 d = msg->getMethodDecl();
10690 assert(d && "unknown method returning __unknown_any?");
10691 } else {
10692 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10693 << e->getSourceRange();
10694 return ExprError();
10695 }
10696
10697 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +000010698
10699 // Never recoverable.
10700 return ExprError();
10701}
10702
John McCall2a984ca2010-10-12 00:20:44 +000010703/// Check for operands with placeholder types and complain if found.
10704/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +000010705ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall1de4d4e2011-04-07 08:22:57 +000010706 // Placeholder types are always *exactly* the appropriate builtin type.
10707 QualType type = E->getType();
John McCall2a984ca2010-10-12 00:20:44 +000010708
John McCall1de4d4e2011-04-07 08:22:57 +000010709 // Overloaded expressions.
10710 if (type == Context.OverloadTy)
10711 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregordb2eae62011-03-16 19:16:25 +000010712 E->getSourceRange(),
John McCall1de4d4e2011-04-07 08:22:57 +000010713 QualType(),
10714 diag::err_ovl_unresolvable);
10715
John McCall864c0412011-04-26 20:42:42 +000010716 // Bound member functions.
10717 if (type == Context.BoundMemberTy) {
10718 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
10719 << E->getSourceRange();
10720 return ExprError();
10721 }
10722
John McCall1de4d4e2011-04-07 08:22:57 +000010723 // Expressions of unknown type.
10724 if (type == Context.UnknownAnyTy)
10725 return diagnoseUnknownAnyExpr(*this, E);
10726
10727 assert(!type->isPlaceholderType());
10728 return Owned(E);
John McCall2a984ca2010-10-12 00:20:44 +000010729}
Richard Trieubb9b80c2011-04-21 21:44:26 +000010730
10731bool Sema::CheckCaseExpression(Expr *expr) {
10732 if (expr->isTypeDependent())
10733 return true;
10734 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
10735 return expr->getType()->isIntegralOrEnumerationType();
10736 return false;
10737}