blob: a8e7348d41a399d7604d4cb92931f298344b985e [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/ASTContext.h"
Sebastian Redlf79a7192011-04-29 08:19:30 +000019#include "clang/AST/ASTMutationListener.h"
Douglas Gregorcc8a5d52010-04-29 00:18:15 +000020#include "clang/AST/CXXInheritance.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000022#include "clang/AST/DeclTemplate.h"
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +000023#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000024#include "clang/AST/Expr.h"
Chris Lattner04421082008-04-08 04:40:51 +000025#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregorb4eeaff2010-05-07 23:12:07 +000027#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000028#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000029#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000032#include "clang/Lex/LiteralSupport.h"
33#include "clang/Lex/Preprocessor.h"
John McCall19510852010-08-20 18:27:03 +000034#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Designator.h"
36#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000037#include "clang/Sema/ScopeInfo.h"
John McCall19510852010-08-20 18:27:03 +000038#include "clang/Sema/ParsedTemplate.h"
John McCall7cd088e2010-08-24 07:21:54 +000039#include "clang/Sema/Template.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000040using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000041using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000042
David Chisnall0f436562009-08-17 16:35:33 +000043
Douglas Gregor48f3bb92009-02-18 21:56:37 +000044/// \brief Determine whether the use of this declaration is valid, and
45/// emit any corresponding diagnostics.
46///
47/// This routine diagnoses various problems with referencing
48/// declarations that can occur when using a declaration. For example,
49/// it might warn if a deprecated or unavailable declaration is being
50/// used, or produce an error (and return true) if a C++0x deleted
51/// function is being used.
52///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000053/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattner52338262009-10-25 22:31:57 +000054/// decls.
55///
Douglas Gregor48f3bb92009-02-18 21:56:37 +000056/// \returns true if there was an error (this declaration cannot be
57/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +000058///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000059bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +000060 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor9b623632010-10-12 23:32:35 +000061 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
62 // If there were any diagnostics suppressed by template argument deduction,
63 // emit them now.
64 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
65 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
66 if (Pos != SuppressedDiagnostics.end()) {
67 llvm::SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
68 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
69 Diag(Suppressed[I].first, Suppressed[I].second);
70
71 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000072 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-10-12 23:32:35 +000073 // entry from the table, because we want to avoid ever emitting these
74 // diagnostics again.
75 Suppressed.clear();
76 }
77 }
78
Richard Smith34b41d92011-02-20 03:19:35 +000079 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-02-21 20:05:19 +000080 if (ParsingInitForAutoVars.count(D)) {
81 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
82 << D->getDeclName();
83 return true;
Richard Smith34b41d92011-02-20 03:19:35 +000084 }
85
Douglas Gregor48f3bb92009-02-18 21:56:37 +000086 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000087 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000088 if (FD->isDeleted()) {
89 Diag(Loc, diag::err_deleted_function_use);
John McCallf85e1932011-06-15 23:02:42 +000090 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000091 return true;
92 }
Douglas Gregor25d944a2009-02-24 04:26:15 +000093 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +000094
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000095 // See if this declaration is unavailable or deprecated.
96 std::string Message;
97 switch (D->getAvailability(&Message)) {
98 case AR_Available:
99 case AR_NotYetIntroduced:
100 break;
101
102 case AR_Deprecated:
103 EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
104 break;
105
106 case AR_Unavailable:
Argyrios Kyrtzidis12189f52011-06-17 17:28:30 +0000107 if (cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) {
108 if (Message.empty()) {
109 if (!UnknownObjCClass)
110 Diag(Loc, diag::err_unavailable) << D->getDeclName();
111 else
112 Diag(Loc, diag::warn_unavailable_fwdclass_message)
113 << D->getDeclName();
114 }
115 else
116 Diag(Loc, diag::err_unavailable_message)
117 << D->getDeclName() << Message;
118 Diag(D->getLocation(), diag::note_unavailable_here)
119 << isa<FunctionDecl>(D) << false;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000120 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000121 break;
122 }
123
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000124 // Warn if this is used but marked unused.
125 if (D->hasAttr<UnusedAttr>())
126 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
127
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000128 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000129}
130
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000131/// \brief Retrieve the message suffix that should be added to a
132/// diagnostic complaining about the given function being deleted or
133/// unavailable.
134std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
135 // FIXME: C++0x implicitly-deleted special member functions could be
136 // detected here so that we could improve diagnostics to say, e.g.,
137 // "base class 'A' had a deleted copy constructor".
138 if (FD->isDeleted())
139 return std::string();
140
141 std::string Message;
142 if (FD->getAvailability(&Message))
143 return ": " + Message;
144
145 return std::string();
146}
147
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000148/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +0000149/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000150/// attribute. It warns if call does not have the sentinel argument.
151///
152void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000153 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000154 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000155 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000156 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000157
158 // FIXME: In C++0x, if any of the arguments are parameter pack
159 // expansions, we can't check for the sentinel now.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000160 int sentinelPos = attr->getSentinel();
161 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +0000162
Mike Stump390b4cc2009-05-16 07:39:55 +0000163 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
164 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000165 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000166 bool warnNotEnoughArgs = false;
167 int isMethod = 0;
168 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
169 // skip over named parameters.
170 ObjCMethodDecl::param_iterator P, E = MD->param_end();
171 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
172 if (nullPos)
173 --nullPos;
174 else
175 ++i;
176 }
177 warnNotEnoughArgs = (P != E || i >= NumArgs);
178 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000179 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000180 // skip over named parameters.
181 ObjCMethodDecl::param_iterator P, E = FD->param_end();
182 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
183 if (nullPos)
184 --nullPos;
185 else
186 ++i;
187 }
188 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000189 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000190 // block or function pointer call.
191 QualType Ty = V->getType();
192 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000193 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000194 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
195 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000196 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
197 unsigned NumArgsInProto = Proto->getNumArgs();
198 unsigned k;
199 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
200 if (nullPos)
201 --nullPos;
202 else
203 ++i;
204 }
205 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
206 }
207 if (Ty->isBlockPointerType())
208 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000209 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000210 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000211 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000212 return;
213
214 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000215 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000216 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000217 return;
218 }
219 int sentinel = i;
220 while (sentinelPos > 0 && i < NumArgs-1) {
221 --sentinelPos;
222 ++i;
223 }
224 if (sentinelPos > 0) {
225 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000226 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000227 return;
228 }
229 while (i < NumArgs-1) {
230 ++i;
231 ++sentinel;
232 }
233 Expr *sentinelExpr = Args[sentinel];
John McCall8eb662e2010-05-06 23:53:00 +0000234 if (!sentinelExpr) return;
235 if (sentinelExpr->isTypeDependent()) return;
236 if (sentinelExpr->isValueDependent()) return;
Anders Carlsson343e6ff2010-11-05 15:21:33 +0000237
238 // nullptr_t is always treated as null.
239 if (sentinelExpr->getType()->isNullPtrType()) return;
240
Fariborz Jahanian9ccd7252010-07-14 16:37:51 +0000241 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall8eb662e2010-05-06 23:53:00 +0000242 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
243 Expr::NPC_ValueDependentIsNull))
244 return;
245
246 // Unfortunately, __null has type 'int'.
247 if (isa<GNUNullExpr>(sentinelExpr)) return;
248
249 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
250 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000251}
252
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000253SourceRange Sema::getExprRange(ExprTy *E) const {
254 Expr *Ex = (Expr *)E;
255 return Ex? Ex->getSourceRange() : SourceRange();
256}
257
Chris Lattnere7a2e912008-07-25 21:10:04 +0000258//===----------------------------------------------------------------------===//
259// Standard Promotions and Conversions
260//===----------------------------------------------------------------------===//
261
Chris Lattnere7a2e912008-07-25 21:10:04 +0000262/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000263ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000264 QualType Ty = E->getType();
265 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
266
Chris Lattnere7a2e912008-07-25 21:10:04 +0000267 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000268 E = ImpCastExprToType(E, Context.getPointerType(Ty),
269 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000270 else if (Ty->isArrayType()) {
271 // In C90 mode, arrays only promote to pointers if the array expression is
272 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
273 // type 'array of type' is converted to an expression that has type 'pointer
274 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
275 // that has type 'array of type' ...". The relevant change is "an lvalue"
276 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000277 //
278 // C++ 4.2p1:
279 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
280 // T" can be converted to an rvalue of type "pointer to T".
281 //
John McCall7eb0a9e2010-11-24 05:12:34 +0000282 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000283 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
284 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000285 }
John Wiegley429bb272011-04-08 18:41:53 +0000286 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000287}
288
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000289static void CheckForNullPointerDereference(Sema &S, Expr *E) {
290 // Check to see if we are dereferencing a null pointer. If so,
291 // and if not volatile-qualified, this is undefined behavior that the
292 // optimizer will delete, so warn about it. People sometimes try to use this
293 // to get a deterministic trap and are surprised by clang's behavior. This
294 // only handles the pattern "*null", which is a very syntactic check.
295 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
296 if (UO->getOpcode() == UO_Deref &&
297 UO->getSubExpr()->IgnoreParenCasts()->
298 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
299 !UO->getType().isVolatileQualified()) {
300 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
301 S.PDiag(diag::warn_indirection_through_null)
302 << UO->getSubExpr()->getSourceRange());
303 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
304 S.PDiag(diag::note_indirection_through_null));
305 }
306}
307
John Wiegley429bb272011-04-08 18:41:53 +0000308ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000309 // C++ [conv.lval]p1:
310 // A glvalue of a non-function, non-array type T can be
311 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000312 if (!E->isGLValue()) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +0000313
John McCall409fa9a2010-12-06 20:48:59 +0000314 QualType T = E->getType();
315 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000316
John McCall409fa9a2010-12-06 20:48:59 +0000317 // Create a load out of an ObjCProperty l-value, if necessary.
318 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley429bb272011-04-08 18:41:53 +0000319 ExprResult Res = ConvertPropertyForRValue(E);
320 if (Res.isInvalid())
321 return Owned(E);
322 E = Res.take();
John McCall409fa9a2010-12-06 20:48:59 +0000323 if (!E->isGLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000324 return Owned(E);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000325 }
John McCall409fa9a2010-12-06 20:48:59 +0000326
327 // We don't want to throw lvalue-to-rvalue casts on top of
328 // expressions of certain types in C++.
329 if (getLangOptions().CPlusPlus &&
330 (E->getType() == Context.OverloadTy ||
331 T->isDependentType() ||
332 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000333 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000334
335 // The C standard is actually really unclear on this point, and
336 // DR106 tells us what the result should be but not why. It's
337 // generally best to say that void types just doesn't undergo
338 // lvalue-to-rvalue at all. Note that expressions of unqualified
339 // 'void' type are never l-values, but qualified void can be.
340 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000341 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000342
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000343 CheckForNullPointerDereference(*this, E);
344
John McCall409fa9a2010-12-06 20:48:59 +0000345 // C++ [conv.lval]p1:
346 // [...] If T is a non-class type, the type of the prvalue is the
347 // cv-unqualified version of T. Otherwise, the type of the
348 // rvalue is T.
349 //
350 // C99 6.3.2.1p2:
351 // If the lvalue has qualified type, the value has the unqualified
352 // version of the type of the lvalue; otherwise, the value has the
353 // type of the lvalue.
354 if (T.hasQualifiers())
355 T = T.getUnqualifiedType();
356
Ted Kremenek3aea4da2011-03-01 18:41:00 +0000357 CheckArrayAccess(E);
Ted Kremeneka0125d82011-02-16 01:57:07 +0000358
John Wiegley429bb272011-04-08 18:41:53 +0000359 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
360 E, 0, VK_RValue));
John McCall409fa9a2010-12-06 20:48:59 +0000361}
362
John Wiegley429bb272011-04-08 18:41:53 +0000363ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
364 ExprResult Res = DefaultFunctionArrayConversion(E);
365 if (Res.isInvalid())
366 return ExprError();
367 Res = DefaultLvalueConversion(Res.take());
368 if (Res.isInvalid())
369 return ExprError();
370 return move(Res);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000371}
372
373
Chris Lattnere7a2e912008-07-25 21:10:04 +0000374/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000375/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000376/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000377/// apply if the array is an argument to the sizeof or address (&) operators.
378/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000379ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000380 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000381 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
382 if (Res.isInvalid())
383 return Owned(E);
384 E = Res.take();
John McCall0ae287a2010-12-01 04:43:34 +0000385
386 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000387 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCall0ae287a2010-12-01 04:43:34 +0000388
389 // Try to perform integral promotions if the object has a theoretically
390 // promotable type.
391 if (Ty->isIntegralOrUnscopedEnumerationType()) {
392 // C99 6.3.1.1p2:
393 //
394 // The following may be used in an expression wherever an int or
395 // unsigned int may be used:
396 // - an object or expression with an integer type whose integer
397 // conversion rank is less than or equal to the rank of int
398 // and unsigned int.
399 // - A bit-field of type _Bool, int, signed int, or unsigned int.
400 //
401 // If an int can represent all values of the original type, the
402 // value is converted to an int; otherwise, it is converted to an
403 // unsigned int. These are called the integer promotions. All
404 // other types are unchanged by the integer promotions.
405
406 QualType PTy = Context.isPromotableBitField(E);
407 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000408 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
409 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000410 }
411 if (Ty->isPromotableIntegerType()) {
412 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000413 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
414 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000415 }
Eli Friedman04e83572009-08-20 04:21:42 +0000416 }
John Wiegley429bb272011-04-08 18:41:53 +0000417 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000418}
419
Chris Lattner05faf172008-07-25 22:25:12 +0000420/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000421/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000422/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000423ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
424 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000425 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000426
John Wiegley429bb272011-04-08 18:41:53 +0000427 ExprResult Res = UsualUnaryConversions(E);
428 if (Res.isInvalid())
429 return Owned(E);
430 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000431
Chris Lattner05faf172008-07-25 22:25:12 +0000432 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000433 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000434 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
435
436 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000437}
438
Chris Lattner312531a2009-04-12 08:11:20 +0000439/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
440/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley429bb272011-04-08 18:41:53 +0000441/// interfaces passed by value.
442ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000443 FunctionDecl *FDecl) {
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000444 ExprResult ExprRes = CheckPlaceholderExpr(E);
445 if (ExprRes.isInvalid())
446 return ExprError();
447
448 ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000449 if (ExprRes.isInvalid())
450 return ExprError();
451 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000452
Chris Lattner40378332010-05-16 04:01:30 +0000453 // __builtin_va_start takes the second argument as a "varargs" argument, but
454 // it doesn't actually do anything with it. It doesn't need to be non-pod
455 // etc.
456 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
John Wiegley429bb272011-04-08 18:41:53 +0000457 return Owned(E);
Chris Lattner40378332010-05-16 04:01:30 +0000458
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000459 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley429bb272011-04-08 18:41:53 +0000460 if (E->getType()->isObjCObjectType() &&
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000461 DiagRuntimeBehavior(E->getLocStart(), 0,
462 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
463 << E->getType() << CT))
John Wiegley429bb272011-04-08 18:41:53 +0000464 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000465
John McCallf85e1932011-06-15 23:02:42 +0000466 if (!E->getType().isPODType(Context)) {
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000467 // C++0x [expr.call]p7:
468 // Passing a potentially-evaluated argument of class type (Clause 9)
469 // having a non-trivial copy constructor, a non-trivial move constructor,
470 // or a non-trivial destructor, with no corresponding parameter,
471 // is conditionally-supported with implementation-defined semantics.
472 bool TrivialEnough = false;
473 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
474 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
475 if (Record->hasTrivialCopyConstructor() &&
476 Record->hasTrivialMoveConstructor() &&
477 Record->hasTrivialDestructor())
478 TrivialEnough = true;
479 }
480 }
John McCallf85e1932011-06-15 23:02:42 +0000481
482 if (!TrivialEnough &&
483 getLangOptions().ObjCAutoRefCount &&
484 E->getType()->isObjCLifetimeType())
485 TrivialEnough = true;
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000486
487 if (TrivialEnough) {
488 // Nothing to diagnose. This is okay.
489 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000490 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000491 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000492 << CT)) {
493 // Turn this into a trap.
494 CXXScopeSpec SS;
495 UnqualifiedId Name;
496 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
497 E->getLocStart());
498 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
499 if (TrapFn.isInvalid())
500 return ExprError();
501
502 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
503 MultiExprArg(), E->getLocEnd());
504 if (Call.isInvalid())
505 return ExprError();
506
507 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
508 Call.get(), E);
509 if (Comma.isInvalid())
510 return ExprError();
511
512 E = Comma.get();
513 }
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000514 }
515
John Wiegley429bb272011-04-08 18:41:53 +0000516 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000517}
518
Chris Lattnere7a2e912008-07-25 21:10:04 +0000519/// UsualArithmeticConversions - Performs various conversions that are common to
520/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000521/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000522/// responsible for emitting appropriate error diagnostics.
523/// FIXME: verify the conversion rules for "complex int" are consistent with
524/// GCC.
John Wiegley429bb272011-04-08 18:41:53 +0000525QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr, ExprResult &rhsExpr,
Chris Lattnere7a2e912008-07-25 21:10:04 +0000526 bool isCompAssign) {
John Wiegley429bb272011-04-08 18:41:53 +0000527 if (!isCompAssign) {
528 lhsExpr = UsualUnaryConversions(lhsExpr.take());
529 if (lhsExpr.isInvalid())
530 return QualType();
531 }
Eli Friedmanab3a8522009-03-28 01:22:36 +0000532
John Wiegley429bb272011-04-08 18:41:53 +0000533 rhsExpr = UsualUnaryConversions(rhsExpr.take());
534 if (rhsExpr.isInvalid())
535 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000536
Mike Stump1eb44332009-09-09 15:08:12 +0000537 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000538 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000539 QualType lhs =
John Wiegley429bb272011-04-08 18:41:53 +0000540 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000541 QualType rhs =
John Wiegley429bb272011-04-08 18:41:53 +0000542 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000543
544 // If both types are identical, no conversion is needed.
545 if (lhs == rhs)
546 return lhs;
547
548 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
549 // The caller can deal with this (e.g. pointer + int).
550 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
551 return lhs;
552
John McCallcf33b242010-11-13 08:17:45 +0000553 // Apply unary and bitfield promotions to the LHS's type.
554 QualType lhs_unpromoted = lhs;
555 if (lhs->isPromotableIntegerType())
556 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley429bb272011-04-08 18:41:53 +0000557 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +0000558 if (!LHSBitfieldPromoteTy.isNull())
559 lhs = LHSBitfieldPromoteTy;
John McCallcf33b242010-11-13 08:17:45 +0000560 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000561 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000562
John McCallcf33b242010-11-13 08:17:45 +0000563 // If both types are identical, no conversion is needed.
564 if (lhs == rhs)
565 return lhs;
566
567 // At this point, we have two different arithmetic types.
568
569 // Handle complex types first (C99 6.3.1.8p1).
570 bool LHSComplexFloat = lhs->isComplexType();
571 bool RHSComplexFloat = rhs->isComplexType();
572 if (LHSComplexFloat || RHSComplexFloat) {
573 // if we have an integer operand, the result is the complex type.
574
John McCall2bb5d002010-11-13 09:02:35 +0000575 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
576 if (rhs->isIntegerType()) {
577 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000578 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
579 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000580 } else {
581 assert(rhs->isComplexIntegerType());
John Wiegley429bb272011-04-08 18:41:53 +0000582 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000583 }
John McCallcf33b242010-11-13 08:17:45 +0000584 return lhs;
585 }
586
John McCall2bb5d002010-11-13 09:02:35 +0000587 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
588 if (!isCompAssign) {
589 // int -> float -> _Complex float
590 if (lhs->isIntegerType()) {
591 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000592 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_IntegralToFloating);
593 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000594 } else {
595 assert(lhs->isComplexIntegerType());
John Wiegley429bb272011-04-08 18:41:53 +0000596 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000597 }
598 }
John McCallcf33b242010-11-13 08:17:45 +0000599 return rhs;
600 }
601
602 // This handles complex/complex, complex/float, or float/complex.
603 // When both operands are complex, the shorter operand is converted to the
604 // type of the longer, and that is the type of the result. This corresponds
605 // to what is done when combining two real floating-point operands.
606 // The fun begins when size promotion occur across type domains.
607 // From H&S 6.3.4: When one operand is complex and the other is a real
608 // floating-point type, the less precise type is converted, within it's
609 // real or complex domain, to the precision of the other type. For example,
610 // when combining a "long double" with a "double _Complex", the
611 // "double _Complex" is promoted to "long double _Complex".
612 int order = Context.getFloatingTypeOrder(lhs, rhs);
613
614 // If both are complex, just cast to the more precise type.
615 if (LHSComplexFloat && RHSComplexFloat) {
616 if (order > 0) {
617 // _Complex float -> _Complex double
John Wiegley429bb272011-04-08 18:41:53 +0000618 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000619 return lhs;
620
621 } else if (order < 0) {
622 // _Complex float -> _Complex double
623 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000624 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000625 return rhs;
626 }
627 return lhs;
628 }
629
630 // If just the LHS is complex, the RHS needs to be converted,
631 // and the LHS might need to be promoted.
632 if (LHSComplexFloat) {
633 if (order > 0) { // LHS is wider
634 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000635 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000636 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
637 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000638 return lhs;
639 }
640
641 // RHS is at least as wide. Find its corresponding complex type.
642 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
643
644 // double -> _Complex double
John Wiegley429bb272011-04-08 18:41:53 +0000645 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000646
647 // _Complex float -> _Complex double
648 if (!isCompAssign && order < 0)
John Wiegley429bb272011-04-08 18:41:53 +0000649 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000650
651 return result;
652 }
653
654 // Just the RHS is complex, so the LHS needs to be converted
655 // and the RHS might need to be promoted.
656 assert(RHSComplexFloat);
657
658 if (order < 0) { // RHS is wider
659 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000660 if (!isCompAssign) {
Argyrios Kyrtzidise1889332011-01-18 18:49:33 +0000661 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000662 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
663 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000664 }
John McCallcf33b242010-11-13 08:17:45 +0000665 return rhs;
666 }
667
668 // LHS is at least as wide. Find its corresponding complex type.
669 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
670
671 // double -> _Complex double
672 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000673 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000674
675 // _Complex float -> _Complex double
676 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +0000677 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000678
679 return result;
680 }
681
682 // Now handle "real" floating types (i.e. float, double, long double).
683 bool LHSFloat = lhs->isRealFloatingType();
684 bool RHSFloat = rhs->isRealFloatingType();
685 if (LHSFloat || RHSFloat) {
686 // If we have two real floating types, convert the smaller operand
687 // to the bigger result.
688 if (LHSFloat && RHSFloat) {
689 int order = Context.getFloatingTypeOrder(lhs, rhs);
690 if (order > 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000691 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCallcf33b242010-11-13 08:17:45 +0000692 return lhs;
693 }
694
695 assert(order < 0 && "illegal float comparison");
696 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000697 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCallcf33b242010-11-13 08:17:45 +0000698 return rhs;
699 }
700
701 // If we have an integer operand, the result is the real floating type.
702 if (LHSFloat) {
703 if (rhs->isIntegerType()) {
704 // Convert rhs to the lhs floating point type.
John Wiegley429bb272011-04-08 18:41:53 +0000705 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCallcf33b242010-11-13 08:17:45 +0000706 return lhs;
707 }
708
709 // Convert both sides to the appropriate complex float.
710 assert(rhs->isComplexIntegerType());
711 QualType result = Context.getComplexType(lhs);
712
713 // _Complex int -> _Complex float
John Wiegley429bb272011-04-08 18:41:53 +0000714 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000715
716 // float -> _Complex float
717 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000718 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000719
720 return result;
721 }
722
723 assert(RHSFloat);
724 if (lhs->isIntegerType()) {
725 // Convert lhs to the rhs floating point type.
726 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000727 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCallcf33b242010-11-13 08:17:45 +0000728 return rhs;
729 }
730
731 // Convert both sides to the appropriate complex float.
732 assert(lhs->isComplexIntegerType());
733 QualType result = Context.getComplexType(rhs);
734
735 // _Complex int -> _Complex float
736 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000737 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000738
739 // float -> _Complex float
John Wiegley429bb272011-04-08 18:41:53 +0000740 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000741
742 return result;
743 }
744
745 // Handle GCC complex int extension.
746 // FIXME: if the operands are (int, _Complex long), we currently
747 // don't promote the complex. Also, signedness?
748 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
749 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
750 if (lhsComplexInt && rhsComplexInt) {
751 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
752 rhsComplexInt->getElementType());
753 assert(order && "inequal types with equal element ordering");
754 if (order > 0) {
755 // _Complex int -> _Complex long
John Wiegley429bb272011-04-08 18:41:53 +0000756 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000757 return lhs;
758 }
759
760 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000761 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000762 return rhs;
763 } else if (lhsComplexInt) {
764 // int -> _Complex int
John Wiegley429bb272011-04-08 18:41:53 +0000765 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000766 return lhs;
767 } else if (rhsComplexInt) {
768 // int -> _Complex int
769 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000770 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000771 return rhs;
772 }
773
774 // Finally, we have two differing integer types.
775 // The rules for this case are in C99 6.3.1.8
776 int compare = Context.getIntegerTypeOrder(lhs, rhs);
777 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
778 rhsSigned = rhs->hasSignedIntegerRepresentation();
779 if (lhsSigned == rhsSigned) {
780 // Same signedness; use the higher-ranked type
781 if (compare >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000782 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000783 return lhs;
784 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000785 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000786 return rhs;
787 } else if (compare != (lhsSigned ? 1 : -1)) {
788 // The unsigned type has greater than or equal rank to the
789 // signed type, so use the unsigned type
790 if (rhsSigned) {
John Wiegley429bb272011-04-08 18:41:53 +0000791 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000792 return lhs;
793 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000794 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000795 return rhs;
796 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
797 // The two types are different widths; if we are here, that
798 // means the signed type is larger than the unsigned type, so
799 // use the signed type.
800 if (lhsSigned) {
John Wiegley429bb272011-04-08 18:41:53 +0000801 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000802 return lhs;
803 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000804 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000805 return rhs;
806 } else {
807 // The signed type is higher-ranked than the unsigned type,
808 // but isn't actually any bigger (like unsigned int and long
809 // on most 32-bit systems). Use the unsigned type corresponding
810 // to the signed type.
811 QualType result =
812 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley429bb272011-04-08 18:41:53 +0000813 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000814 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000815 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000816 return result;
817 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000818}
819
Chris Lattnere7a2e912008-07-25 21:10:04 +0000820//===----------------------------------------------------------------------===//
821// Semantic Analysis for various Expression Types
822//===----------------------------------------------------------------------===//
823
824
Peter Collingbournef111d932011-04-15 00:35:48 +0000825ExprResult
826Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
827 SourceLocation DefaultLoc,
828 SourceLocation RParenLoc,
829 Expr *ControllingExpr,
830 MultiTypeArg types,
831 MultiExprArg exprs) {
832 unsigned NumAssocs = types.size();
833 assert(NumAssocs == exprs.size());
834
835 ParsedType *ParsedTypes = types.release();
836 Expr **Exprs = exprs.release();
837
838 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
839 for (unsigned i = 0; i < NumAssocs; ++i) {
840 if (ParsedTypes[i])
841 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
842 else
843 Types[i] = 0;
844 }
845
846 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
847 ControllingExpr, Types, Exprs,
848 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +0000849 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +0000850 return ER;
851}
852
853ExprResult
854Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
855 SourceLocation DefaultLoc,
856 SourceLocation RParenLoc,
857 Expr *ControllingExpr,
858 TypeSourceInfo **Types,
859 Expr **Exprs,
860 unsigned NumAssocs) {
861 bool TypeErrorFound = false,
862 IsResultDependent = ControllingExpr->isTypeDependent(),
863 ContainsUnexpandedParameterPack
864 = ControllingExpr->containsUnexpandedParameterPack();
865
866 for (unsigned i = 0; i < NumAssocs; ++i) {
867 if (Exprs[i]->containsUnexpandedParameterPack())
868 ContainsUnexpandedParameterPack = true;
869
870 if (Types[i]) {
871 if (Types[i]->getType()->containsUnexpandedParameterPack())
872 ContainsUnexpandedParameterPack = true;
873
874 if (Types[i]->getType()->isDependentType()) {
875 IsResultDependent = true;
876 } else {
877 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
878 // complete object type other than a variably modified type."
879 unsigned D = 0;
880 if (Types[i]->getType()->isIncompleteType())
881 D = diag::err_assoc_type_incomplete;
882 else if (!Types[i]->getType()->isObjectType())
883 D = diag::err_assoc_type_nonobject;
884 else if (Types[i]->getType()->isVariablyModifiedType())
885 D = diag::err_assoc_type_variably_modified;
886
887 if (D != 0) {
888 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
889 << Types[i]->getTypeLoc().getSourceRange()
890 << Types[i]->getType();
891 TypeErrorFound = true;
892 }
893
894 // C1X 6.5.1.1p2 "No two generic associations in the same generic
895 // selection shall specify compatible types."
896 for (unsigned j = i+1; j < NumAssocs; ++j)
897 if (Types[j] && !Types[j]->getType()->isDependentType() &&
898 Context.typesAreCompatible(Types[i]->getType(),
899 Types[j]->getType())) {
900 Diag(Types[j]->getTypeLoc().getBeginLoc(),
901 diag::err_assoc_compatible_types)
902 << Types[j]->getTypeLoc().getSourceRange()
903 << Types[j]->getType()
904 << Types[i]->getType();
905 Diag(Types[i]->getTypeLoc().getBeginLoc(),
906 diag::note_compat_assoc)
907 << Types[i]->getTypeLoc().getSourceRange()
908 << Types[i]->getType();
909 TypeErrorFound = true;
910 }
911 }
912 }
913 }
914 if (TypeErrorFound)
915 return ExprError();
916
917 // If we determined that the generic selection is result-dependent, don't
918 // try to compute the result expression.
919 if (IsResultDependent)
920 return Owned(new (Context) GenericSelectionExpr(
921 Context, KeyLoc, ControllingExpr,
922 Types, Exprs, NumAssocs, DefaultLoc,
923 RParenLoc, ContainsUnexpandedParameterPack));
924
925 llvm::SmallVector<unsigned, 1> CompatIndices;
926 unsigned DefaultIndex = -1U;
927 for (unsigned i = 0; i < NumAssocs; ++i) {
928 if (!Types[i])
929 DefaultIndex = i;
930 else if (Context.typesAreCompatible(ControllingExpr->getType(),
931 Types[i]->getType()))
932 CompatIndices.push_back(i);
933 }
934
935 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
936 // type compatible with at most one of the types named in its generic
937 // association list."
938 if (CompatIndices.size() > 1) {
939 // We strip parens here because the controlling expression is typically
940 // parenthesized in macro definitions.
941 ControllingExpr = ControllingExpr->IgnoreParens();
942 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
943 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
944 << (unsigned) CompatIndices.size();
945 for (llvm::SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
946 E = CompatIndices.end(); I != E; ++I) {
947 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
948 diag::note_compat_assoc)
949 << Types[*I]->getTypeLoc().getSourceRange()
950 << Types[*I]->getType();
951 }
952 return ExprError();
953 }
954
955 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
956 // its controlling expression shall have type compatible with exactly one of
957 // the types named in its generic association list."
958 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
959 // We strip parens here because the controlling expression is typically
960 // parenthesized in macro definitions.
961 ControllingExpr = ControllingExpr->IgnoreParens();
962 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
963 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
964 return ExprError();
965 }
966
967 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
968 // type name that is compatible with the type of the controlling expression,
969 // then the result expression of the generic selection is the expression
970 // in that generic association. Otherwise, the result expression of the
971 // generic selection is the expression in the default generic association."
972 unsigned ResultIndex =
973 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
974
975 return Owned(new (Context) GenericSelectionExpr(
976 Context, KeyLoc, ControllingExpr,
977 Types, Exprs, NumAssocs, DefaultLoc,
978 RParenLoc, ContainsUnexpandedParameterPack,
979 ResultIndex));
980}
981
Steve Narofff69936d2007-09-16 03:34:24 +0000982/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000983/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
984/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
985/// multiple tokens. However, the common case is that StringToks points to one
986/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000987///
John McCall60d7b3a2010-08-24 06:29:42 +0000988ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +0000989Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000990 assert(NumStringToks && "Must have at least one string!");
991
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000992 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000993 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000994 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000995
996 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
997 for (unsigned i = 0; i != NumStringToks; ++i)
998 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000999
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001000 QualType StrTy = Context.CharTy;
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001001 if (Literal.AnyWide)
1002 StrTy = Context.getWCharType();
1003 else if (Literal.Pascal)
1004 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001005
1006 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +00001007 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001008 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001009
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001010 // Get an array type for the string, according to C99 6.4.5. This includes
1011 // the nul terminator character as well as the string length for pascal
1012 // strings.
1013 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001014 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001015 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001016
Reid Spencer5f016e22007-07-11 17:01:13 +00001017 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +00001018 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Anders Carlsson3e2193c2011-04-14 00:40:03 +00001019 Literal.AnyWide, Literal.Pascal, StrTy,
Sean Hunt6cf75022010-08-30 17:47:05 +00001020 &StringTokLocs[0],
1021 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001022}
1023
John McCall469a1eb2011-02-02 13:00:07 +00001024enum CaptureResult {
1025 /// No capture is required.
1026 CR_NoCapture,
1027
1028 /// A capture is required.
1029 CR_Capture,
1030
John McCall6b5a61b2011-02-07 10:33:21 +00001031 /// A by-ref capture is required.
1032 CR_CaptureByRef,
1033
John McCall469a1eb2011-02-02 13:00:07 +00001034 /// An error occurred when trying to capture the given variable.
1035 CR_Error
1036};
1037
1038/// Diagnose an uncapturable value reference.
Chris Lattner639e2d32008-10-20 05:16:36 +00001039///
John McCall469a1eb2011-02-02 13:00:07 +00001040/// \param var - the variable referenced
1041/// \param DC - the context which we couldn't capture through
1042static CaptureResult
John McCall6b5a61b2011-02-07 10:33:21 +00001043diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001044 VarDecl *var, DeclContext *DC) {
1045 switch (S.ExprEvalContexts.back().Context) {
1046 case Sema::Unevaluated:
1047 // The argument will never be evaluated, so don't complain.
1048 return CR_NoCapture;
Mike Stump1eb44332009-09-09 15:08:12 +00001049
John McCall469a1eb2011-02-02 13:00:07 +00001050 case Sema::PotentiallyEvaluated:
1051 case Sema::PotentiallyEvaluatedIfUsed:
1052 break;
Chris Lattner639e2d32008-10-20 05:16:36 +00001053
John McCall469a1eb2011-02-02 13:00:07 +00001054 case Sema::PotentiallyPotentiallyEvaluated:
1055 // FIXME: delay these!
1056 break;
Chris Lattner17f3a6d2009-04-21 22:26:47 +00001057 }
Mike Stump1eb44332009-09-09 15:08:12 +00001058
John McCall469a1eb2011-02-02 13:00:07 +00001059 // Don't diagnose about capture if we're not actually in code right
1060 // now; in general, there are more appropriate places that will
1061 // diagnose this.
1062 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1063
John McCall4f38f412011-03-22 23:15:50 +00001064 // Certain madnesses can happen with parameter declarations, which
1065 // we want to ignore.
1066 if (isa<ParmVarDecl>(var)) {
1067 // - If the parameter still belongs to the translation unit, then
1068 // we're actually just using one parameter in the declaration of
1069 // the next. This is useful in e.g. VLAs.
1070 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1071 return CR_NoCapture;
1072
1073 // - This particular madness can happen in ill-formed default
1074 // arguments; claim it's okay and let downstream code handle it.
1075 if (S.CurContext == var->getDeclContext()->getParent())
1076 return CR_NoCapture;
1077 }
John McCall469a1eb2011-02-02 13:00:07 +00001078
1079 DeclarationName functionName;
1080 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1081 functionName = fn->getDeclName();
1082 // FIXME: variable from enclosing block that we couldn't capture from!
1083
1084 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1085 << var->getIdentifier() << functionName;
1086 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1087 << var->getIdentifier();
1088
1089 return CR_Error;
Mike Stump1eb44332009-09-09 15:08:12 +00001090}
1091
John McCall6b5a61b2011-02-07 10:33:21 +00001092/// There is a well-formed capture at a particular scope level;
1093/// propagate it through all the nested blocks.
1094static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1095 const BlockDecl::Capture &capture) {
1096 VarDecl *var = capture.getVariable();
1097
1098 // Update all the inner blocks with the capture information.
1099 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1100 i != e; ++i) {
1101 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1102 innerBlock->Captures.push_back(
1103 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1104 /*nested*/ true, capture.getCopyExpr()));
1105 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1106 }
1107
1108 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1109}
1110
1111/// shouldCaptureValueReference - Determine if a reference to the
John McCall469a1eb2011-02-02 13:00:07 +00001112/// given value in the current context requires a variable capture.
1113///
1114/// This also keeps the captures set in the BlockScopeInfo records
1115/// up-to-date.
John McCall6b5a61b2011-02-07 10:33:21 +00001116static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001117 ValueDecl *value) {
1118 // Only variables ever require capture.
1119 VarDecl *var = dyn_cast<VarDecl>(value);
John McCall76a40212011-02-09 01:13:10 +00001120 if (!var) return CR_NoCapture;
John McCall469a1eb2011-02-02 13:00:07 +00001121
1122 // Fast path: variables from the current context never require capture.
1123 DeclContext *DC = S.CurContext;
1124 if (var->getDeclContext() == DC) return CR_NoCapture;
1125
1126 // Only variables with local storage require capture.
1127 // FIXME: What about 'const' variables in C++?
1128 if (!var->hasLocalStorage()) return CR_NoCapture;
1129
1130 // Otherwise, we need to capture.
1131
1132 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCall469a1eb2011-02-02 13:00:07 +00001133 do {
1134 // Only blocks (and eventually C++0x closures) can capture; other
1135 // scopes don't work.
1136 if (!isa<BlockDecl>(DC))
John McCall6b5a61b2011-02-07 10:33:21 +00001137 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCall469a1eb2011-02-02 13:00:07 +00001138
1139 BlockScopeInfo *blockScope =
1140 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1141 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1142
John McCall6b5a61b2011-02-07 10:33:21 +00001143 // Check whether we've already captured it in this block. If so,
1144 // we're done.
1145 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1146 return propagateCapture(S, functionScopesIndex,
1147 blockScope->Captures[indexPlus1 - 1]);
John McCall469a1eb2011-02-02 13:00:07 +00001148
1149 functionScopesIndex--;
1150 DC = cast<BlockDecl>(DC)->getDeclContext();
1151 } while (var->getDeclContext() != DC);
1152
John McCall6b5a61b2011-02-07 10:33:21 +00001153 // Okay, we descended all the way to the block that defines the variable.
1154 // Actually try to capture it.
1155 QualType type = var->getType();
1156
1157 // Prohibit variably-modified types.
1158 if (type->isVariablyModifiedType()) {
1159 S.Diag(loc, diag::err_ref_vm_type);
1160 S.Diag(var->getLocation(), diag::note_declared_at);
1161 return CR_Error;
1162 }
1163
1164 // Prohibit arrays, even in __block variables, but not references to
1165 // them.
1166 if (type->isArrayType()) {
1167 S.Diag(loc, diag::err_ref_array_type);
1168 S.Diag(var->getLocation(), diag::note_declared_at);
1169 return CR_Error;
1170 }
1171
1172 S.MarkDeclarationReferenced(loc, var);
1173
1174 // The BlocksAttr indicates the variable is bound by-reference.
1175 bool byRef = var->hasAttr<BlocksAttr>();
1176
1177 // Build a copy expression.
1178 Expr *copyExpr = 0;
John McCall642a75f2011-04-28 02:15:35 +00001179 const RecordType *rtype;
1180 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1181 (rtype = type->getAs<RecordType>())) {
1182
1183 // The capture logic needs the destructor, so make sure we mark it.
1184 // Usually this is unnecessary because most local variables have
1185 // their destructors marked at declaration time, but parameters are
1186 // an exception because it's technically only the call site that
1187 // actually requires the destructor.
1188 if (isa<ParmVarDecl>(var))
1189 S.FinalizeVarWithDestructor(var, rtype);
1190
John McCall6b5a61b2011-02-07 10:33:21 +00001191 // According to the blocks spec, the capture of a variable from
1192 // the stack requires a const copy constructor. This is not true
1193 // of the copy/move done to move a __block variable to the heap.
1194 type.addConst();
1195
1196 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1197 ExprResult result =
1198 S.PerformCopyInitialization(
1199 InitializedEntity::InitializeBlock(var->getLocation(),
1200 type, false),
1201 loc, S.Owned(declRef));
1202
1203 // Build a full-expression copy expression if initialization
1204 // succeeded and used a non-trivial constructor. Recover from
1205 // errors by pretending that the copy isn't necessary.
1206 if (!result.isInvalid() &&
1207 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1208 result = S.MaybeCreateExprWithCleanups(result);
1209 copyExpr = result.take();
1210 }
1211 }
1212
1213 // We're currently at the declarer; go back to the closure.
1214 functionScopesIndex++;
1215 BlockScopeInfo *blockScope =
1216 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1217
1218 // Build a valid capture in this scope.
1219 blockScope->Captures.push_back(
1220 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1221 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1222
1223 // Propagate that to inner captures if necessary.
1224 return propagateCapture(S, functionScopesIndex,
1225 blockScope->Captures.back());
1226}
1227
1228static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1229 const DeclarationNameInfo &NameInfo,
1230 bool byRef) {
1231 assert(isa<VarDecl>(vd) && "capturing non-variable");
1232
1233 VarDecl *var = cast<VarDecl>(vd);
1234 assert(var->hasLocalStorage() && "capturing non-local");
1235 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1236
1237 QualType exprType = var->getType().getNonReferenceType();
1238
1239 BlockDeclRefExpr *BDRE;
1240 if (!byRef) {
1241 // The variable will be bound by copy; make it const within the
1242 // closure, but record that this was done in the expression.
1243 bool constAdded = !exprType.isConstQualified();
1244 exprType.addConst();
1245
1246 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1247 NameInfo.getLoc(), false,
1248 constAdded);
1249 } else {
1250 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1251 NameInfo.getLoc(), true);
1252 }
1253
1254 return S.Owned(BDRE);
John McCall469a1eb2011-02-02 13:00:07 +00001255}
Chris Lattner639e2d32008-10-20 05:16:36 +00001256
John McCall60d7b3a2010-08-24 06:29:42 +00001257ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001258Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001259 SourceLocation Loc,
1260 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001261 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001262 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001263}
1264
John McCall76a40212011-02-09 01:13:10 +00001265/// BuildDeclRefExpr - Build an expression that references a
1266/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001267ExprResult
John McCall76a40212011-02-09 01:13:10 +00001268Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001269 const DeclarationNameInfo &NameInfo,
1270 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001271 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +00001272
John McCall7eb0a9e2010-11-24 05:12:34 +00001273 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +00001274 SS? SS->getWithLocInContext(Context)
1275 : NestedNameSpecifierLoc(),
John McCall7eb0a9e2010-11-24 05:12:34 +00001276 D, NameInfo, Ty, VK);
1277
1278 // Just in case we're building an illegal pointer-to-member.
1279 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1280 E->setObjectKind(OK_BitField);
1281
1282 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001283}
1284
Abramo Bagnara25777432010-08-11 22:01:17 +00001285/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001286/// possibly a list of template arguments.
1287///
1288/// If this produces template arguments, it is permitted to call
1289/// DecomposeTemplateName.
1290///
1291/// This actually loses a lot of source location information for
1292/// non-standard name kinds; we should consider preserving that in
1293/// some way.
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001294void Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1295 TemplateArgumentListInfo &Buffer,
1296 DeclarationNameInfo &NameInfo,
1297 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001298 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1299 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1300 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1301
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001302 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall129e2df2009-11-30 22:42:35 +00001303 Id.TemplateId->getTemplateArgs(),
1304 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001305 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001306 TemplateArgsPtr.release();
1307
John McCall2b5289b2010-08-23 07:28:44 +00001308 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001309 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001310 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001311 TemplateArgs = &Buffer;
1312 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001313 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001314 TemplateArgs = 0;
1315 }
1316}
1317
John McCall578b69b2009-12-16 08:11:27 +00001318/// Diagnose an empty lookup.
1319///
1320/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001321bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1322 CorrectTypoContext CTC) {
John McCall578b69b2009-12-16 08:11:27 +00001323 DeclarationName Name = R.getLookupName();
1324
John McCall578b69b2009-12-16 08:11:27 +00001325 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001326 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001327 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1328 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001329 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001330 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001331 diagnostic_suggest = diag::err_undeclared_use_suggest;
1332 }
John McCall578b69b2009-12-16 08:11:27 +00001333
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001334 // If the original lookup was an unqualified lookup, fake an
1335 // unqualified lookup. This is useful when (for example) the
1336 // original lookup would not have found something because it was a
1337 // dependent name.
Nick Lewycky03d98c52010-07-06 19:51:49 +00001338 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001339 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +00001340 if (isa<CXXRecordDecl>(DC)) {
1341 LookupQualifiedName(R, DC);
1342
1343 if (!R.empty()) {
1344 // Don't give errors about ambiguities in this lookup.
1345 R.suppressDiagnostics();
1346
1347 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1348 bool isInstance = CurMethod &&
1349 CurMethod->isInstance() &&
1350 DC == CurMethod->getParent();
1351
1352 // Give a code modification hint to insert 'this->'.
1353 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1354 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +00001355 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001356 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1357 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001358 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001359 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001360 if (DepMethod) {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001361 Diag(R.getNameLoc(), diagnostic) << Name
1362 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1363 QualType DepThisType = DepMethod->getThisType(Context);
1364 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1365 R.getNameLoc(), DepThisType, false);
1366 TemplateArgumentListInfo TList;
1367 if (ULE->hasExplicitTemplateArgs())
1368 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001369
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001370 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00001371 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001372 CXXDependentScopeMemberExpr *DepExpr =
1373 CXXDependentScopeMemberExpr::Create(
1374 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001375 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001376 R.getLookupNameInfo(), &TList);
1377 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001378 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001379 // FIXME: we should be able to handle this case too. It is correct
1380 // to add this-> here. This is a workaround for PR7947.
1381 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001382 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001383 } else {
John McCall578b69b2009-12-16 08:11:27 +00001384 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001385 }
John McCall578b69b2009-12-16 08:11:27 +00001386
1387 // Do we really want to note all of these?
1388 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1389 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1390
1391 // Tell the callee to try to recover.
1392 return false;
1393 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001394
1395 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001396 }
1397 }
1398
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001399 // We didn't find anything, so try to correct for a typo.
Douglas Gregoraaf87162010-04-14 20:04:41 +00001400 DeclarationName Corrected;
Daniel Dunbardc32cdf2010-06-02 15:46:52 +00001401 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001402 if (!R.empty()) {
1403 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1404 if (SS.isEmpty())
1405 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1406 << FixItHint::CreateReplacement(R.getNameLoc(),
1407 R.getLookupName().getAsString());
1408 else
1409 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1410 << Name << computeDeclContext(SS, false) << R.getLookupName()
1411 << SS.getRange()
1412 << FixItHint::CreateReplacement(R.getNameLoc(),
1413 R.getLookupName().getAsString());
1414 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1415 Diag(ND->getLocation(), diag::note_previous_decl)
1416 << ND->getDeclName();
1417
1418 // Tell the callee to try to recover.
1419 return false;
1420 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001421
Douglas Gregoraaf87162010-04-14 20:04:41 +00001422 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1423 // FIXME: If we ended up with a typo for a type name or
1424 // Objective-C class name, we're in trouble because the parser
1425 // is in the wrong place to recover. Suggest the typo
1426 // correction, but don't make it a fix-it since we're not going
1427 // to recover well anyway.
1428 if (SS.isEmpty())
1429 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1430 else
1431 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1432 << Name << computeDeclContext(SS, false) << R.getLookupName()
1433 << SS.getRange();
1434
1435 // Don't try to recover; it won't work.
1436 return true;
1437 }
1438 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001439 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001440 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001441 if (SS.isEmpty())
Douglas Gregoraaf87162010-04-14 20:04:41 +00001442 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001443 else
Douglas Gregord203a162010-01-01 00:15:04 +00001444 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001445 << Name << computeDeclContext(SS, false) << Corrected
1446 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001447 return true;
1448 }
Douglas Gregord203a162010-01-01 00:15:04 +00001449 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001450 }
1451
1452 // Emit a special diagnostic for failed member lookups.
1453 // FIXME: computing the declaration context might fail here (?)
1454 if (!SS.isEmpty()) {
1455 Diag(R.getNameLoc(), diag::err_no_member)
1456 << Name << computeDeclContext(SS, false)
1457 << SS.getRange();
1458 return true;
1459 }
1460
John McCall578b69b2009-12-16 08:11:27 +00001461 // Give up, we can't recover.
1462 Diag(R.getNameLoc(), diagnostic) << Name;
1463 return true;
1464}
1465
Douglas Gregorca45da02010-11-02 20:36:02 +00001466ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1467 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001468 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1469 if (!IDecl)
1470 return 0;
1471 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1472 if (!ClassImpDecl)
1473 return 0;
Douglas Gregorca45da02010-11-02 20:36:02 +00001474 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001475 if (!property)
1476 return 0;
1477 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregorca45da02010-11-02 20:36:02 +00001478 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1479 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001480 return 0;
1481 return property;
1482}
1483
Douglas Gregorca45da02010-11-02 20:36:02 +00001484bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1485 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1486 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1487 if (!IDecl)
1488 return false;
1489 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1490 if (!ClassImpDecl)
1491 return false;
1492 if (ObjCPropertyImplDecl *PIDecl
1493 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1494 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1495 PIDecl->getPropertyIvarDecl())
1496 return false;
1497
1498 return true;
1499}
1500
Douglas Gregor312eadb2011-04-24 05:37:28 +00001501ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1502 IdentifierInfo *II,
1503 SourceLocation NameLoc) {
1504 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001505 bool LookForIvars;
1506 if (Lookup.empty())
1507 LookForIvars = true;
1508 else if (CurMeth->isClassMethod())
1509 LookForIvars = false;
1510 else
1511 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahaniand0fbadd2011-01-26 00:57:01 +00001512 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1513 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001514 if (!LookForIvars)
1515 return 0;
1516
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001517 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1518 if (!IDecl)
1519 return 0;
1520 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001521 if (!ClassImpDecl)
1522 return 0;
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001523 bool DynamicImplSeen = false;
Douglas Gregor312eadb2011-04-24 05:37:28 +00001524 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001525 if (!property)
1526 return 0;
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001527 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001528 DynamicImplSeen =
1529 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001530 // property implementation has a designated ivar. No need to assume a new
1531 // one.
1532 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1533 return 0;
1534 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001535 if (!DynamicImplSeen) {
Douglas Gregor312eadb2011-04-24 05:37:28 +00001536 QualType PropType = Context.getCanonicalType(property->getType());
1537 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001538 NameLoc, NameLoc,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001539 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian75049662010-12-15 23:29:04 +00001540 ObjCIvarDecl::Private,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001541 (Expr *)0, true);
1542 ClassImpDecl->addDecl(Ivar);
1543 IDecl->makeDeclVisibleInContext(Ivar, false);
1544 property->setPropertyIvarDecl(Ivar);
1545 return Ivar;
1546 }
1547 return 0;
1548}
1549
John McCall60d7b3a2010-08-24 06:29:42 +00001550ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001551 CXXScopeSpec &SS,
1552 UnqualifiedId &Id,
1553 bool HasTrailingLParen,
1554 bool isAddressOfOperand) {
John McCallf7a1a742009-11-24 19:00:30 +00001555 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1556 "cannot be direct & operand and have a trailing lparen");
1557
1558 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001559 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001560
John McCall129e2df2009-11-30 22:42:35 +00001561 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001562
1563 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001564 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001565 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001566 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001567
Abramo Bagnara25777432010-08-11 22:01:17 +00001568 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001569 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001570 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001571
John McCallf7a1a742009-11-24 19:00:30 +00001572 // C++ [temp.dep.expr]p3:
1573 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001574 // -- an identifier that was declared with a dependent type,
1575 // (note: handled after lookup)
1576 // -- a template-id that is dependent,
1577 // (note: handled in BuildTemplateIdExpr)
1578 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001579 // -- a nested-name-specifier that contains a class-name that
1580 // names a dependent type.
1581 // Determine whether this is a member of an unknown specialization;
1582 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001583 bool DependentID = false;
1584 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1585 Name.getCXXNameType()->isDependentType()) {
1586 DependentID = true;
1587 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001588 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001589 if (RequireCompleteDeclContext(SS, DC))
1590 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001591 } else {
1592 DependentID = true;
1593 }
1594 }
1595
Chris Lattner337e5502011-02-18 01:27:55 +00001596 if (DependentID)
Abramo Bagnara25777432010-08-11 22:01:17 +00001597 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001598 TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001599
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001600 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001601 // Perform the required lookup.
Abramo Bagnara25777432010-08-11 22:01:17 +00001602 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001603 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001604 // Lookup the template name again to correctly establish the context in
1605 // which it was found. This is really unfortunate as we already did the
1606 // lookup to determine that it was a template name in the first place. If
1607 // this becomes a performance hit, we can work harder to preserve those
1608 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001609 bool MemberOfUnknownSpecialization;
1610 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1611 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001612
1613 if (MemberOfUnknownSpecialization ||
1614 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1615 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1616 TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001617 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001618 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001619 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001620
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001621 // If the result might be in a dependent base class, this is a dependent
1622 // id-expression.
1623 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1624 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1625 TemplateArgs);
1626
John McCallf7a1a742009-11-24 19:00:30 +00001627 // If this reference is in an Objective-C method, then we need to do
1628 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001629 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001630 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001631 if (E.isInvalid())
1632 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Chris Lattner337e5502011-02-18 01:27:55 +00001634 if (Expr *Ex = E.takeAs<Expr>())
1635 return Owned(Ex);
1636
1637 // Synthesize ivars lazily.
Fariborz Jahaniane776f882011-01-03 18:08:02 +00001638 if (getLangOptions().ObjCDefaultSynthProperties &&
1639 getLangOptions().ObjCNonFragileABI2) {
Douglas Gregor312eadb2011-04-24 05:37:28 +00001640 if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
Fariborz Jahaniande267602010-11-17 19:41:23 +00001641 if (const ObjCPropertyDecl *Property =
1642 canSynthesizeProvisionalIvar(II)) {
1643 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1644 Diag(Property->getLocation(), diag::note_property_declare);
1645 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001646 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1647 isAddressOfOperand);
Fariborz Jahaniande267602010-11-17 19:41:23 +00001648 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001649 }
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001650 // for further use, this must be set to false if in class method.
1651 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001652 }
Chris Lattner8a934232008-03-31 00:36:02 +00001653 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001654
John McCallf7a1a742009-11-24 19:00:30 +00001655 if (R.isAmbiguous())
1656 return ExprError();
1657
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001658 // Determine whether this name might be a candidate for
1659 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001660 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001661
John McCallf7a1a742009-11-24 19:00:30 +00001662 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001663 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001664 // in C90, extension in C99, forbidden in C++).
1665 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1666 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1667 if (D) R.addDecl(D);
1668 }
1669
1670 // If this name wasn't predeclared and if this is not a function
1671 // call, diagnose the problem.
1672 if (R.empty()) {
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001673 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001674 return ExprError();
1675
1676 assert(!R.empty() &&
1677 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001678
1679 // If we found an Objective-C instance variable, let
1680 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001681 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001682 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1683 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001684 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001685 assert(E.isInvalid() || E.get());
1686 return move(E);
1687 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001688 }
1689 }
Mike Stump1eb44332009-09-09 15:08:12 +00001690
John McCallf7a1a742009-11-24 19:00:30 +00001691 // This is guaranteed from this point on.
1692 assert(!R.empty() || ADL);
1693
John McCallaa81e162009-12-01 22:10:20 +00001694 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001695 // C++ [class.mfct.non-static]p3:
1696 // When an id-expression that is not part of a class member access
1697 // syntax and not used to form a pointer to member is used in the
1698 // body of a non-static member function of class X, if name lookup
1699 // resolves the name in the id-expression to a non-static non-type
1700 // member of some class C, the id-expression is transformed into a
1701 // class member access expression using (*this) as the
1702 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001703 //
1704 // But we don't actually need to do this for '&' operands if R
1705 // resolved to a function or overloaded function set, because the
1706 // expression is ill-formed if it actually works out to be a
1707 // non-static member function:
1708 //
1709 // C++ [expr.ref]p4:
1710 // Otherwise, if E1.E2 refers to a non-static member function. . .
1711 // [t]he expression can be used only as the left-hand operand of a
1712 // member function call.
1713 //
1714 // There are other safeguards against such uses, but it's important
1715 // to get this right here so that we don't end up making a
1716 // spuriously dependent expression if we're inside a dependent
1717 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001718 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001719 bool MightBeImplicitMember;
1720 if (!isAddressOfOperand)
1721 MightBeImplicitMember = true;
1722 else if (!SS.isEmpty())
1723 MightBeImplicitMember = false;
1724 else if (R.isOverloadedResult())
1725 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001726 else if (R.isUnresolvableResult())
1727 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001728 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001729 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1730 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001731
1732 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00001733 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001734 }
1735
John McCallf7a1a742009-11-24 19:00:30 +00001736 if (TemplateArgs)
1737 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001738
John McCallf7a1a742009-11-24 19:00:30 +00001739 return BuildDeclarationNameExpr(SS, R, ADL);
1740}
1741
John McCall129e2df2009-11-30 22:42:35 +00001742/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1743/// declaration name, generally during template instantiation.
1744/// There's a large number of things which don't need to be done along
1745/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001746ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001747Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001748 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001749 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001750 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00001751 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00001752
John McCall77bb1aa2010-05-01 00:40:08 +00001753 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001754 return ExprError();
1755
Abramo Bagnara25777432010-08-11 22:01:17 +00001756 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001757 LookupQualifiedName(R, DC);
1758
1759 if (R.isAmbiguous())
1760 return ExprError();
1761
1762 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001763 Diag(NameInfo.getLoc(), diag::err_no_member)
1764 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001765 return ExprError();
1766 }
1767
1768 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1769}
1770
1771/// LookupInObjCMethod - The parser has read a name in, and Sema has
1772/// detected that we're currently inside an ObjC method. Perform some
1773/// additional lookup.
1774///
1775/// Ideally, most of this would be done by lookup, but there's
1776/// actually quite a lot of extra work involved.
1777///
1778/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001779ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001780Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001781 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001782 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001783 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001784
John McCallf7a1a742009-11-24 19:00:30 +00001785 // There are two cases to handle here. 1) scoped lookup could have failed,
1786 // in which case we should look for an ivar. 2) scoped lookup could have
1787 // found a decl, but that decl is outside the current instance method (i.e.
1788 // a global variable). In these two cases, we do a lookup for an ivar with
1789 // this name, if the lookup sucedes, we replace it our current decl.
1790
1791 // If we're in a class method, we don't normally want to look for
1792 // ivars. But if we don't find anything else, and there's an
1793 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001794 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001795
1796 bool LookForIvars;
1797 if (Lookup.empty())
1798 LookForIvars = true;
1799 else if (IsClassMethod)
1800 LookForIvars = false;
1801 else
1802 LookForIvars = (Lookup.isSingleResult() &&
1803 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001804 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001805 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001806 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001807 ObjCInterfaceDecl *ClassDeclared;
1808 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1809 // Diagnose using an ivar in a class method.
1810 if (IsClassMethod)
1811 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1812 << IV->getDeclName());
1813
1814 // If we're referencing an invalid decl, just return this as a silent
1815 // error node. The error diagnostic was already emitted on the decl.
1816 if (IV->isInvalidDecl())
1817 return ExprError();
1818
1819 // Check if referencing a field with __attribute__((deprecated)).
1820 if (DiagnoseUseOfDecl(IV, Loc))
1821 return ExprError();
1822
1823 // Diagnose the use of an ivar outside of the declaring class.
1824 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1825 ClassDeclared != IFace)
1826 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1827
1828 // FIXME: This should use a new expr for a direct reference, don't
1829 // turn this into Self->ivar, just return a BareIVarExpr or something.
1830 IdentifierInfo &II = Context.Idents.get("self");
1831 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001832 SelfName.setIdentifier(&II, SourceLocation());
John McCallf7a1a742009-11-24 19:00:30 +00001833 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00001834 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001835 SelfName, false, false);
1836 if (SelfExpr.isInvalid())
1837 return ExprError();
1838
John Wiegley429bb272011-04-08 18:41:53 +00001839 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1840 if (SelfExpr.isInvalid())
1841 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00001842
John McCallf7a1a742009-11-24 19:00:30 +00001843 MarkDeclarationReferenced(Loc, IV);
Fariborz Jahanianb8f17ab2011-04-12 23:39:33 +00001844 Expr *base = SelfExpr.take();
1845 base = base->IgnoreParenImpCasts();
1846 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(base)) {
1847 const NamedDecl *ND = DE->getDecl();
1848 if (!isa<ImplicitParamDecl>(ND)) {
Fariborz Jahanianeefa76e2011-04-15 17:04:42 +00001849 // relax the rule such that it is allowed to have a shadow 'self'
1850 // where stand-alone ivar can be found in this 'self' object.
1851 // This is to match gcc's behavior.
1852 ObjCInterfaceDecl *selfIFace = 0;
1853 if (const ObjCObjectPointerType *OPT =
1854 base->getType()->getAsObjCInterfacePointerType())
1855 selfIFace = OPT->getInterfaceDecl();
1856 if (!selfIFace ||
1857 !selfIFace->lookupInstanceVariable(IV->getIdentifier())) {
Fariborz Jahanianb8f17ab2011-04-12 23:39:33 +00001858 Diag(Loc, diag::error_implicit_ivar_access)
1859 << IV->getDeclName();
1860 Diag(ND->getLocation(), diag::note_declared_at);
1861 return ExprError();
1862 }
Fariborz Jahanianeefa76e2011-04-15 17:04:42 +00001863 }
Fariborz Jahanianb8f17ab2011-04-12 23:39:33 +00001864 }
John McCallf7a1a742009-11-24 19:00:30 +00001865 return Owned(new (Context)
1866 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley429bb272011-04-08 18:41:53 +00001867 SelfExpr.take(), true, true));
John McCallf7a1a742009-11-24 19:00:30 +00001868 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001869 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001870 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00001871 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001872 ObjCInterfaceDecl *ClassDeclared;
1873 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1874 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1875 IFace == ClassDeclared)
1876 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1877 }
1878 }
1879
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001880 if (Lookup.empty() && II && AllowBuiltinCreation) {
1881 // FIXME. Consolidate this with similar code in LookupName.
1882 if (unsigned BuiltinID = II->getBuiltinID()) {
1883 if (!(getLangOptions().CPlusPlus &&
1884 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1885 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1886 S, Lookup.isForRedeclaration(),
1887 Lookup.getNameLoc());
1888 if (D) Lookup.addDecl(D);
1889 }
1890 }
1891 }
John McCallf7a1a742009-11-24 19:00:30 +00001892 // Sentinel value saying that we didn't do anything special.
1893 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001894}
John McCallba135432009-11-21 08:51:07 +00001895
John McCall6bb80172010-03-30 21:47:33 +00001896/// \brief Cast a base object to a member's actual type.
1897///
1898/// Logically this happens in three phases:
1899///
1900/// * First we cast from the base type to the naming class.
1901/// The naming class is the class into which we were looking
1902/// when we found the member; it's the qualifier type if a
1903/// qualifier was provided, and otherwise it's the base type.
1904///
1905/// * Next we cast from the naming class to the declaring class.
1906/// If the member we found was brought into a class's scope by
1907/// a using declaration, this is that class; otherwise it's
1908/// the class declaring the member.
1909///
1910/// * Finally we cast from the declaring class to the "true"
1911/// declaring class of the member. This conversion does not
1912/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00001913ExprResult
1914Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001915 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00001916 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001917 NamedDecl *Member) {
1918 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1919 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00001920 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001921
Douglas Gregor5fccd362010-03-03 23:55:11 +00001922 QualType DestRecordType;
1923 QualType DestType;
1924 QualType FromRecordType;
1925 QualType FromType = From->getType();
1926 bool PointerConversions = false;
1927 if (isa<FieldDecl>(Member)) {
1928 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001929
Douglas Gregor5fccd362010-03-03 23:55:11 +00001930 if (FromType->getAs<PointerType>()) {
1931 DestType = Context.getPointerType(DestRecordType);
1932 FromRecordType = FromType->getPointeeType();
1933 PointerConversions = true;
1934 } else {
1935 DestType = DestRecordType;
1936 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001937 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001938 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1939 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00001940 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001941
Douglas Gregor5fccd362010-03-03 23:55:11 +00001942 DestType = Method->getThisType(Context);
1943 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001944
Douglas Gregor5fccd362010-03-03 23:55:11 +00001945 if (FromType->getAs<PointerType>()) {
1946 FromRecordType = FromType->getPointeeType();
1947 PointerConversions = true;
1948 } else {
1949 FromRecordType = FromType;
1950 DestType = DestRecordType;
1951 }
1952 } else {
1953 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00001954 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00001955 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001956
Douglas Gregor5fccd362010-03-03 23:55:11 +00001957 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00001958 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001959
Douglas Gregor5fccd362010-03-03 23:55:11 +00001960 // If the unqualified types are the same, no conversion is necessary.
1961 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00001962 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001963
John McCall6bb80172010-03-30 21:47:33 +00001964 SourceRange FromRange = From->getSourceRange();
1965 SourceLocation FromLoc = FromRange.getBegin();
1966
John McCall5baba9d2010-08-25 10:28:54 +00001967 ExprValueKind VK = CastCategory(From);
Sebastian Redl906082e2010-07-20 04:20:21 +00001968
Douglas Gregor5fccd362010-03-03 23:55:11 +00001969 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001970 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00001971 // class name.
1972 //
1973 // If the member was a qualified name and the qualified referred to a
1974 // specific base subobject type, we'll cast to that intermediate type
1975 // first and then to the object in which the member is declared. That allows
1976 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1977 //
1978 // class Base { public: int x; };
1979 // class Derived1 : public Base { };
1980 // class Derived2 : public Base { };
1981 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1982 //
1983 // void VeryDerived::f() {
1984 // x = 17; // error: ambiguous base subobjects
1985 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1986 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001987 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00001988 QualType QType = QualType(Qualifier->getAsType(), 0);
1989 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1990 assert(QType->isRecordType() && "lookup done with non-record type");
1991
1992 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1993
1994 // In C++98, the qualifier type doesn't actually have to be a base
1995 // type of the object type, in which case we just ignore it.
1996 // Otherwise build the appropriate casts.
1997 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00001998 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00001999 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002000 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002001 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002002
Douglas Gregor5fccd362010-03-03 23:55:11 +00002003 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002004 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002005 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2006 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002007
2008 FromType = QType;
2009 FromRecordType = QRecordType;
2010
2011 // If the qualifier type was the same as the destination type,
2012 // we're done.
2013 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002014 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002015 }
2016 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002017
John McCall6bb80172010-03-30 21:47:33 +00002018 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002019
John McCall6bb80172010-03-30 21:47:33 +00002020 // If we actually found the member through a using declaration, cast
2021 // down to the using declaration's type.
2022 //
2023 // Pointer equality is fine here because only one declaration of a
2024 // class ever has member declarations.
2025 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2026 assert(isa<UsingShadowDecl>(FoundDecl));
2027 QualType URecordType = Context.getTypeDeclType(
2028 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2029
2030 // We only need to do this if the naming-class to declaring-class
2031 // conversion is non-trivial.
2032 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2033 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002034 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002035 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002036 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002037 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002038
John McCall6bb80172010-03-30 21:47:33 +00002039 QualType UType = URecordType;
2040 if (PointerConversions)
2041 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002042 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2043 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002044 FromType = UType;
2045 FromRecordType = URecordType;
2046 }
2047
2048 // We don't do access control for the conversion from the
2049 // declaring class to the true declaring class.
2050 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002051 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002052
John McCallf871d0c2010-08-07 06:22:56 +00002053 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002054 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2055 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002056 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002057 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002058
John Wiegley429bb272011-04-08 18:41:53 +00002059 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2060 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002061}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002062
John McCallf7a1a742009-11-24 19:00:30 +00002063bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002064 const LookupResult &R,
2065 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002066 // Only when used directly as the postfix-expression of a call.
2067 if (!HasTrailingLParen)
2068 return false;
2069
2070 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002071 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002072 return false;
2073
2074 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002075 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002076 return false;
2077
2078 // Turn off ADL when we find certain kinds of declarations during
2079 // normal lookup:
2080 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2081 NamedDecl *D = *I;
2082
2083 // C++0x [basic.lookup.argdep]p3:
2084 // -- a declaration of a class member
2085 // Since using decls preserve this property, we check this on the
2086 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002087 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002088 return false;
2089
2090 // C++0x [basic.lookup.argdep]p3:
2091 // -- a block-scope function declaration that is not a
2092 // using-declaration
2093 // NOTE: we also trigger this for function templates (in fact, we
2094 // don't check the decl type at all, since all other decl types
2095 // turn off ADL anyway).
2096 if (isa<UsingShadowDecl>(D))
2097 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2098 else if (D->getDeclContext()->isFunctionOrMethod())
2099 return false;
2100
2101 // C++0x [basic.lookup.argdep]p3:
2102 // -- a declaration that is neither a function or a function
2103 // template
2104 // And also for builtin functions.
2105 if (isa<FunctionDecl>(D)) {
2106 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2107
2108 // But also builtin functions.
2109 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2110 return false;
2111 } else if (!isa<FunctionTemplateDecl>(D))
2112 return false;
2113 }
2114
2115 return true;
2116}
2117
2118
John McCallba135432009-11-21 08:51:07 +00002119/// Diagnoses obvious problems with the use of the given declaration
2120/// as an expression. This is only actually called for lookups that
2121/// were not overloaded, and it doesn't promise that the declaration
2122/// will in fact be used.
2123static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002124 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002125 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2126 return true;
2127 }
2128
2129 if (isa<ObjCInterfaceDecl>(D)) {
2130 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2131 return true;
2132 }
2133
2134 if (isa<NamespaceDecl>(D)) {
2135 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2136 return true;
2137 }
2138
2139 return false;
2140}
2141
John McCall60d7b3a2010-08-24 06:29:42 +00002142ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002143Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002144 LookupResult &R,
2145 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002146 // If this is a single, fully-resolved result and we don't need ADL,
2147 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002148 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002149 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2150 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002151
2152 // We only need to check the declaration if there's exactly one
2153 // result, because in the overloaded case the results can only be
2154 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002155 if (R.isSingleResult() &&
2156 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002157 return ExprError();
2158
John McCallc373d482010-01-27 01:50:18 +00002159 // Otherwise, just build an unresolved lookup expression. Suppress
2160 // any lookup-related diagnostics; we'll hash these out later, when
2161 // we've picked a target.
2162 R.suppressDiagnostics();
2163
John McCallba135432009-11-21 08:51:07 +00002164 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002165 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002166 SS.getWithLocInContext(Context),
2167 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002168 NeedsADL, R.isOverloadedResult(),
2169 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002170
2171 return Owned(ULE);
2172}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002173
John McCallba135432009-11-21 08:51:07 +00002174/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002175ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002176Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002177 const DeclarationNameInfo &NameInfo,
2178 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002179 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002180 assert(!isa<FunctionTemplateDecl>(D) &&
2181 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002182
Abramo Bagnara25777432010-08-11 22:01:17 +00002183 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002184 if (CheckDeclInExpr(*this, Loc, D))
2185 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002186
Douglas Gregor9af2f522009-12-01 16:58:18 +00002187 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2188 // Specifically diagnose references to class templates that are missing
2189 // a template argument list.
2190 Diag(Loc, diag::err_template_decl_ref)
2191 << Template << SS.getRange();
2192 Diag(Template->getLocation(), diag::note_template_decl_here);
2193 return ExprError();
2194 }
2195
2196 // Make sure that we're referring to a value.
2197 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2198 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002199 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002200 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002201 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002202 return ExprError();
2203 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002204
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002205 // Check whether this declaration can be used. Note that we suppress
2206 // this check when we're going to perform argument-dependent lookup
2207 // on this function name, because this might not be the function
2208 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002209 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002210 return ExprError();
2211
Steve Naroffdd972f22008-09-05 22:11:13 +00002212 // Only create DeclRefExpr's for valid Decl's.
2213 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002214 return ExprError();
2215
John McCall5808ce42011-02-03 08:15:49 +00002216 // Handle members of anonymous structs and unions. If we got here,
2217 // and the reference is to a class member indirect field, then this
2218 // must be the subject of a pointer-to-member expression.
2219 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2220 if (!indirectField->isCXXClassMember())
2221 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2222 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002223
Chris Lattner639e2d32008-10-20 05:16:36 +00002224 // If the identifier reference is inside a block, and it refers to a value
2225 // that is outside the block, create a BlockDeclRefExpr instead of a
2226 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2227 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002228 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002229 // We do not do this for things like enum constants, global variables, etc,
2230 // as they do not get snapshotted.
2231 //
John McCall6b5a61b2011-02-07 10:33:21 +00002232 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCall469a1eb2011-02-02 13:00:07 +00002233 case CR_Error:
2234 return ExprError();
Mike Stump0d6fd572010-01-05 02:56:35 +00002235
John McCall469a1eb2011-02-02 13:00:07 +00002236 case CR_Capture:
John McCall6b5a61b2011-02-07 10:33:21 +00002237 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2238 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2239
2240 case CR_CaptureByRef:
2241 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2242 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCall76a40212011-02-09 01:13:10 +00002243
2244 case CR_NoCapture: {
2245 // If this reference is not in a block or if the referenced
2246 // variable is within the block, create a normal DeclRefExpr.
2247
2248 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002249 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002250
2251 switch (D->getKind()) {
2252 // Ignore all the non-ValueDecl kinds.
2253#define ABSTRACT_DECL(kind)
2254#define VALUE(type, base)
2255#define DECL(type, base) \
2256 case Decl::type:
2257#include "clang/AST/DeclNodes.inc"
2258 llvm_unreachable("invalid value decl kind");
2259 return ExprError();
2260
2261 // These shouldn't make it here.
2262 case Decl::ObjCAtDefsField:
2263 case Decl::ObjCIvar:
2264 llvm_unreachable("forming non-member reference to ivar?");
2265 return ExprError();
2266
2267 // Enum constants are always r-values and never references.
2268 // Unresolved using declarations are dependent.
2269 case Decl::EnumConstant:
2270 case Decl::UnresolvedUsingValue:
2271 valueKind = VK_RValue;
2272 break;
2273
2274 // Fields and indirect fields that got here must be for
2275 // pointer-to-member expressions; we just call them l-values for
2276 // internal consistency, because this subexpression doesn't really
2277 // exist in the high-level semantics.
2278 case Decl::Field:
2279 case Decl::IndirectField:
2280 assert(getLangOptions().CPlusPlus &&
2281 "building reference to field in C?");
2282
2283 // These can't have reference type in well-formed programs, but
2284 // for internal consistency we do this anyway.
2285 type = type.getNonReferenceType();
2286 valueKind = VK_LValue;
2287 break;
2288
2289 // Non-type template parameters are either l-values or r-values
2290 // depending on the type.
2291 case Decl::NonTypeTemplateParm: {
2292 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2293 type = reftype->getPointeeType();
2294 valueKind = VK_LValue; // even if the parameter is an r-value reference
2295 break;
2296 }
2297
2298 // For non-references, we need to strip qualifiers just in case
2299 // the template parameter was declared as 'const int' or whatever.
2300 valueKind = VK_RValue;
2301 type = type.getUnqualifiedType();
2302 break;
2303 }
2304
2305 case Decl::Var:
2306 // In C, "extern void blah;" is valid and is an r-value.
2307 if (!getLangOptions().CPlusPlus &&
2308 !type.hasQualifiers() &&
2309 type->isVoidType()) {
2310 valueKind = VK_RValue;
2311 break;
2312 }
2313 // fallthrough
2314
2315 case Decl::ImplicitParam:
2316 case Decl::ParmVar:
2317 // These are always l-values.
2318 valueKind = VK_LValue;
2319 type = type.getNonReferenceType();
2320 break;
2321
2322 case Decl::Function: {
John McCall755d8492011-04-12 00:42:48 +00002323 const FunctionType *fty = type->castAs<FunctionType>();
2324
2325 // If we're referring to a function with an __unknown_anytype
2326 // result type, make the entire expression __unknown_anytype.
2327 if (fty->getResultType() == Context.UnknownAnyTy) {
2328 type = Context.UnknownAnyTy;
2329 valueKind = VK_RValue;
2330 break;
2331 }
2332
John McCall76a40212011-02-09 01:13:10 +00002333 // Functions are l-values in C++.
2334 if (getLangOptions().CPlusPlus) {
2335 valueKind = VK_LValue;
2336 break;
2337 }
2338
2339 // C99 DR 316 says that, if a function type comes from a
2340 // function definition (without a prototype), that type is only
2341 // used for checking compatibility. Therefore, when referencing
2342 // the function, we pretend that we don't have the full function
2343 // type.
John McCall755d8492011-04-12 00:42:48 +00002344 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2345 isa<FunctionProtoType>(fty))
2346 type = Context.getFunctionNoProtoType(fty->getResultType(),
2347 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002348
2349 // Functions are r-values in C.
2350 valueKind = VK_RValue;
2351 break;
2352 }
2353
2354 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002355 // If we're referring to a method with an __unknown_anytype
2356 // result type, make the entire expression __unknown_anytype.
2357 // This should only be possible with a type written directly.
2358 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(VD->getType()))
2359 if (proto->getResultType() == Context.UnknownAnyTy) {
2360 type = Context.UnknownAnyTy;
2361 valueKind = VK_RValue;
2362 break;
2363 }
2364
John McCall76a40212011-02-09 01:13:10 +00002365 // C++ methods are l-values if static, r-values if non-static.
2366 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2367 valueKind = VK_LValue;
2368 break;
2369 }
2370 // fallthrough
2371
2372 case Decl::CXXConversion:
2373 case Decl::CXXDestructor:
2374 case Decl::CXXConstructor:
2375 valueKind = VK_RValue;
2376 break;
2377 }
2378
2379 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2380 }
2381
John McCall469a1eb2011-02-02 13:00:07 +00002382 }
John McCallf89e55a2010-11-18 06:31:45 +00002383
John McCall6b5a61b2011-02-07 10:33:21 +00002384 llvm_unreachable("unknown capture result");
2385 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002386}
2387
John McCall755d8492011-04-12 00:42:48 +00002388ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002389 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002390
Reid Spencer5f016e22007-07-11 17:01:13 +00002391 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00002392 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002393 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2394 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2395 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002396 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002397
Chris Lattnerfa28b302008-01-12 08:14:25 +00002398 // Pre-defined identifiers are of type char[x], where x is the length of the
2399 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002400
Anders Carlsson3a082d82009-09-08 18:24:21 +00002401 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002402 if (!currentDecl && getCurBlock())
2403 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002404 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002405 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002406 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002407 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002408
Anders Carlsson773f3972009-09-11 01:22:35 +00002409 QualType ResTy;
2410 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2411 ResTy = Context.DependentTy;
2412 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002413 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002414
Anders Carlsson773f3972009-09-11 01:22:35 +00002415 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002416 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002417 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2418 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002419 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002420}
2421
John McCall60d7b3a2010-08-24 06:29:42 +00002422ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002423 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002424 bool Invalid = false;
2425 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2426 if (Invalid)
2427 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002428
Benjamin Kramerddeea562010-02-27 13:44:12 +00002429 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2430 PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00002431 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002432 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002433
Chris Lattnere8337df2009-12-30 21:19:39 +00002434 QualType Ty;
2435 if (!getLangOptions().CPlusPlus)
2436 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2437 else if (Literal.isWide())
2438 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002439 else if (Literal.isMultiChar())
2440 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002441 else
2442 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002443
Sebastian Redle91b3bc2009-01-20 22:23:13 +00002444 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2445 Literal.isWide(),
Chris Lattnere8337df2009-12-30 21:19:39 +00002446 Ty, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002447}
2448
John McCall60d7b3a2010-08-24 06:29:42 +00002449ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002450 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002451 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2452 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002453 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00002454 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002455 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002456 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002457 }
Ted Kremenek28396602009-01-13 23:19:12 +00002458
Reid Spencer5f016e22007-07-11 17:01:13 +00002459 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002460 // Add padding so that NumericLiteralParser can overread by one character.
2461 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002462 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002463
Reid Spencer5f016e22007-07-11 17:01:13 +00002464 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002465 bool Invalid = false;
2466 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2467 if (Invalid)
2468 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002469
Mike Stump1eb44332009-09-09 15:08:12 +00002470 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002471 Tok.getLocation(), PP);
2472 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002473 return ExprError();
2474
Chris Lattner5d661452007-08-26 03:42:43 +00002475 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002476
Chris Lattner5d661452007-08-26 03:42:43 +00002477 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002478 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002479 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002480 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002481 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002482 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002483 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002484 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002485
2486 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2487
John McCall94c939d2009-12-24 09:08:04 +00002488 using llvm::APFloat;
2489 APFloat Val(Format);
2490
2491 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002492
2493 // Overflow is always an error, but underflow is only an error if
2494 // we underflowed to zero (APFloat reports denormals as underflow).
2495 if ((result & APFloat::opOverflow) ||
2496 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002497 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002498 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002499 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002500 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002501 APFloat::getLargest(Format).toString(buffer);
2502 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002503 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002504 APFloat::getSmallest(Format).toString(buffer);
2505 }
2506
2507 Diag(Tok.getLocation(), diagnostic)
2508 << Ty
2509 << llvm::StringRef(buffer.data(), buffer.size());
2510 }
2511
2512 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002513 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002514
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002515 if (Ty == Context.DoubleTy) {
2516 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002517 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002518 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2519 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002520 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002521 }
2522 }
Chris Lattner5d661452007-08-26 03:42:43 +00002523 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002524 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002525 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002526 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002527
Neil Boothb9449512007-08-29 22:00:19 +00002528 // long long is a C99 feature.
2529 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00002530 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00002531 Diag(Tok.getLocation(), diag::ext_longlong);
2532
Reid Spencer5f016e22007-07-11 17:01:13 +00002533 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00002534 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002535
Reid Spencer5f016e22007-07-11 17:01:13 +00002536 if (Literal.GetIntegerValue(ResultVal)) {
2537 // If this value didn't fit into uintmax_t, warn and force to ull.
2538 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002539 Ty = Context.UnsignedLongLongTy;
2540 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002541 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002542 } else {
2543 // If this value fits into a ULL, try to figure out what else it fits into
2544 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002545
Reid Spencer5f016e22007-07-11 17:01:13 +00002546 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2547 // be an unsigned int.
2548 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2549
2550 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002551 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002552 if (!Literal.isLong && !Literal.isLongLong) {
2553 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002554 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002555
Reid Spencer5f016e22007-07-11 17:01:13 +00002556 // Does it fit in a unsigned int?
2557 if (ResultVal.isIntN(IntSize)) {
2558 // Does it fit in a signed int?
2559 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002560 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002561 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002562 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002563 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002564 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002565 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002566
Reid Spencer5f016e22007-07-11 17:01:13 +00002567 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002568 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002569 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002570
Reid Spencer5f016e22007-07-11 17:01:13 +00002571 // Does it fit in a unsigned long?
2572 if (ResultVal.isIntN(LongSize)) {
2573 // Does it fit in a signed long?
2574 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002575 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002576 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002577 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002578 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002579 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002580 }
2581
Reid Spencer5f016e22007-07-11 17:01:13 +00002582 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002583 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002584 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002585
Reid Spencer5f016e22007-07-11 17:01:13 +00002586 // Does it fit in a unsigned long long?
2587 if (ResultVal.isIntN(LongLongSize)) {
2588 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002589 // To be compatible with MSVC, hex integer literals ending with the
2590 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002591 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2592 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002593 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002594 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002595 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002596 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002597 }
2598 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002599
Reid Spencer5f016e22007-07-11 17:01:13 +00002600 // If we still couldn't decide a type, we probably have something that
2601 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002602 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002603 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002604 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002605 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002606 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002607
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002608 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002609 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002610 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002611 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002612 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002613
Chris Lattner5d661452007-08-26 03:42:43 +00002614 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2615 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002616 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002617 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002618
2619 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002620}
2621
John McCall60d7b3a2010-08-24 06:29:42 +00002622ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCall9ae2f072010-08-23 23:25:46 +00002623 SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002624 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002625 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002626}
2627
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002628static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2629 SourceLocation Loc,
2630 SourceRange ArgRange) {
2631 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2632 // scalar or vector data type argument..."
2633 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2634 // type (C99 6.2.5p18) or void.
2635 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2636 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2637 << T << ArgRange;
2638 return true;
2639 }
2640
2641 assert((T->isVoidType() || !T->isIncompleteType()) &&
2642 "Scalar types should always be complete");
2643 return false;
2644}
2645
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002646static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2647 SourceLocation Loc,
2648 SourceRange ArgRange,
2649 UnaryExprOrTypeTrait TraitKind) {
2650 // C99 6.5.3.4p1:
2651 if (T->isFunctionType()) {
2652 // alignof(function) is allowed as an extension.
2653 if (TraitKind == UETT_SizeOf)
2654 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2655 return false;
2656 }
2657
2658 // Allow sizeof(void)/alignof(void) as an extension.
2659 if (T->isVoidType()) {
2660 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2661 return false;
2662 }
2663
2664 return true;
2665}
2666
2667static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2668 SourceLocation Loc,
2669 SourceRange ArgRange,
2670 UnaryExprOrTypeTrait TraitKind) {
2671 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2672 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2673 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2674 << T << (TraitKind == UETT_SizeOf)
2675 << ArgRange;
2676 return true;
2677 }
2678
2679 return false;
2680}
2681
Chandler Carruth9d342d02011-05-26 08:53:10 +00002682/// \brief Check the constrains on expression operands to unary type expression
2683/// and type traits.
2684///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002685/// Completes any types necessary and validates the constraints on the operand
2686/// expression. The logic mostly mirrors the type-based overload, but may modify
2687/// the expression as it completes the type for that expression through template
2688/// instantiation, etc.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002689bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op,
2690 UnaryExprOrTypeTrait ExprKind) {
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002691 QualType ExprTy = Op->getType();
2692
2693 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2694 // the result is the size of the referenced type."
2695 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2696 // result shall be the alignment of the referenced type."
2697 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2698 ExprTy = Ref->getPointeeType();
2699
2700 if (ExprKind == UETT_VecStep)
2701 return CheckVecStepTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2702 Op->getSourceRange());
2703
2704 // Whitelist some types as extensions
2705 if (!CheckExtensionTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2706 Op->getSourceRange(), ExprKind))
2707 return false;
2708
2709 if (RequireCompleteExprType(Op,
2710 PDiag(diag::err_sizeof_alignof_incomplete_type)
2711 << ExprKind << Op->getSourceRange(),
2712 std::make_pair(SourceLocation(), PDiag(0))))
2713 return true;
2714
2715 // Completeing the expression's type may have changed it.
2716 ExprTy = Op->getType();
2717 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2718 ExprTy = Ref->getPointeeType();
2719
2720 if (CheckObjCTraitOperandConstraints(*this, ExprTy, Op->getExprLoc(),
2721 Op->getSourceRange(), ExprKind))
2722 return true;
2723
Nico Webercf739922011-06-15 02:47:03 +00002724 if (ExprKind == UETT_SizeOf) {
2725 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Op->IgnoreParens())) {
2726 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2727 QualType OType = PVD->getOriginalType();
2728 QualType Type = PVD->getType();
2729 if (Type->isPointerType() && OType->isArrayType()) {
2730 Diag(Op->getExprLoc(), diag::warn_sizeof_array_param)
2731 << Type << OType;
2732 Diag(PVD->getLocation(), diag::note_declared_at);
2733 }
2734 }
2735 }
2736 }
2737
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002738 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00002739}
2740
2741/// \brief Check the constraints on operands to unary expression and type
2742/// traits.
2743///
2744/// This will complete any types necessary, and validate the various constraints
2745/// on those operands.
2746///
Reid Spencer5f016e22007-07-11 17:01:13 +00002747/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002748/// C99 6.3.2.1p[2-4] all state:
2749/// Except when it is the operand of the sizeof operator ...
2750///
2751/// C++ [expr.sizeof]p4
2752/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2753/// standard conversions are not applied to the operand of sizeof.
2754///
2755/// This policy is followed for all of the unary trait expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002756bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2757 SourceLocation OpLoc,
2758 SourceRange ExprRange,
2759 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl28507842009-02-26 14:39:58 +00002760 if (exprType->isDependentType())
2761 return false;
2762
Sebastian Redl5d484e82009-11-23 17:18:46 +00002763 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2764 // the result is the size of the referenced type."
2765 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2766 // result shall be the alignment of the referenced type."
2767 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2768 exprType = Ref->getPointeeType();
2769
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002770 if (ExprKind == UETT_VecStep)
2771 return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002772
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002773 // Whitelist some types as extensions
2774 if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange,
2775 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00002776 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002777
Chris Lattner1efaa952009-04-24 00:30:45 +00002778 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002779 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002780 << ExprKind << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002781 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002782
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002783 if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange,
2784 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00002785 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002786
Chris Lattner1efaa952009-04-24 00:30:45 +00002787 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002788}
2789
Chandler Carruth9d342d02011-05-26 08:53:10 +00002790static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00002791 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002792
Mike Stump1eb44332009-09-09 15:08:12 +00002793 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002794 if (isa<DeclRefExpr>(E))
2795 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002796
2797 // Cannot know anything else if the expression is dependent.
2798 if (E->isTypeDependent())
2799 return false;
2800
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002801 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002802 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2803 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002804 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002805 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002806
2807 // Alignment of a field access is always okay, so long as it isn't a
2808 // bit-field.
2809 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002810 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002811 return false;
2812
Chandler Carruth9d342d02011-05-26 08:53:10 +00002813 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002814}
2815
Chandler Carruth9d342d02011-05-26 08:53:10 +00002816bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002817 E = E->IgnoreParens();
2818
2819 // Cannot know anything else if the expression is dependent.
2820 if (E->isTypeDependent())
2821 return false;
2822
Chandler Carruth9d342d02011-05-26 08:53:10 +00002823 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00002824}
2825
Douglas Gregorba498172009-03-13 21:01:28 +00002826/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002827ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002828Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2829 SourceLocation OpLoc,
2830 UnaryExprOrTypeTrait ExprKind,
2831 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002832 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002833 return ExprError();
2834
John McCalla93c9342009-12-07 02:54:59 +00002835 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002836
Douglas Gregorba498172009-03-13 21:01:28 +00002837 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002838 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00002839 return ExprError();
2840
2841 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002842 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2843 Context.getSizeType(),
2844 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002845}
2846
2847/// \brief Build a sizeof or alignof expression given an expression
2848/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002849ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002850Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2851 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00002852 ExprResult PE = CheckPlaceholderExpr(E);
2853 if (PE.isInvalid())
2854 return ExprError();
2855
2856 E = PE.get();
2857
Douglas Gregorba498172009-03-13 21:01:28 +00002858 // Verify that the operand is valid.
2859 bool isInvalid = false;
2860 if (E->isTypeDependent()) {
2861 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002862 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002863 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002864 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002865 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002866 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002867 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00002868 isInvalid = true;
2869 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002870 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00002871 }
2872
2873 if (isInvalid)
2874 return ExprError();
2875
2876 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002877 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002878 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002879 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002880}
2881
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002882/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2883/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00002884/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00002885ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002886Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2887 UnaryExprOrTypeTrait ExprKind, bool isType,
2888 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002889 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002890 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002891
Sebastian Redl05189992008-11-11 17:56:53 +00002892 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00002893 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00002894 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002895 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00002896 }
Sebastian Redl05189992008-11-11 17:56:53 +00002897
Douglas Gregorba498172009-03-13 21:01:28 +00002898 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002899 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregorba498172009-03-13 21:01:28 +00002900 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002901}
2902
John Wiegley429bb272011-04-08 18:41:53 +00002903static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall09431682010-11-18 19:01:18 +00002904 bool isReal) {
John Wiegley429bb272011-04-08 18:41:53 +00002905 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00002906 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002907
John McCallf6a16482010-12-04 03:47:34 +00002908 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00002909 if (V.get()->getObjectKind() != OK_Ordinary) {
2910 V = S.DefaultLvalueConversion(V.take());
2911 if (V.isInvalid())
2912 return QualType();
2913 }
John McCallf6a16482010-12-04 03:47:34 +00002914
Chris Lattnercc26ed72007-08-26 05:39:26 +00002915 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00002916 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00002917 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002918
Chris Lattnercc26ed72007-08-26 05:39:26 +00002919 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00002920 if (V.get()->getType()->isArithmeticType())
2921 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002922
John McCall2cd11fe2010-10-12 02:09:17 +00002923 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00002924 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00002925 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00002926 if (PR.get() != V.get()) {
2927 V = move(PR);
John McCall09431682010-11-18 19:01:18 +00002928 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall2cd11fe2010-10-12 02:09:17 +00002929 }
2930
Chris Lattnercc26ed72007-08-26 05:39:26 +00002931 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00002932 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattnerba27e2a2009-02-17 08:12:06 +00002933 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00002934 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00002935}
2936
2937
Reid Spencer5f016e22007-07-11 17:01:13 +00002938
John McCall60d7b3a2010-08-24 06:29:42 +00002939ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00002940Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00002941 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00002942 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00002943 switch (Kind) {
2944 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00002945 case tok::plusplus: Opc = UO_PostInc; break;
2946 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002947 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002948
John McCall9ae2f072010-08-23 23:25:46 +00002949 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00002950}
2951
John McCall60d7b3a2010-08-24 06:29:42 +00002952ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002953Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2954 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00002955 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00002956 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00002957 if (Result.isInvalid()) return ExprError();
2958 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00002959
John McCall9ae2f072010-08-23 23:25:46 +00002960 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00002961
Douglas Gregor337c6b92008-11-19 17:17:41 +00002962 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002963 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002964 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00002965 Context.DependentTy,
2966 VK_LValue, OK_Ordinary,
2967 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002968 }
2969
Mike Stump1eb44332009-09-09 15:08:12 +00002970 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00002971 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00002972 LHSExp->getType()->isEnumeralType() ||
2973 RHSExp->getType()->isRecordType() ||
2974 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00002975 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00002976 }
2977
John McCall9ae2f072010-08-23 23:25:46 +00002978 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00002979}
2980
2981
John McCall60d7b3a2010-08-24 06:29:42 +00002982ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00002983Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2984 Expr *Idx, SourceLocation RLoc) {
2985 Expr *LHSExp = Base;
2986 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00002987
Chris Lattner12d9ff62007-07-16 00:14:47 +00002988 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00002989 if (!LHSExp->getType()->getAs<VectorType>()) {
2990 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
2991 if (Result.isInvalid())
2992 return ExprError();
2993 LHSExp = Result.take();
2994 }
2995 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
2996 if (Result.isInvalid())
2997 return ExprError();
2998 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00002999
Chris Lattner12d9ff62007-07-16 00:14:47 +00003000 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003001 ExprValueKind VK = VK_LValue;
3002 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003003
Reid Spencer5f016e22007-07-11 17:01:13 +00003004 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003005 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003006 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003007 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003008 Expr *BaseExpr, *IndexExpr;
3009 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003010 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3011 BaseExpr = LHSExp;
3012 IndexExpr = RHSExp;
3013 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003014 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003015 BaseExpr = LHSExp;
3016 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003017 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003018 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00003019 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00003020 BaseExpr = RHSExp;
3021 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003022 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003023 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003024 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003025 BaseExpr = LHSExp;
3026 IndexExpr = RHSExp;
3027 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003028 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003029 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003030 // Handle the uncommon case of "123[Ptr]".
3031 BaseExpr = RHSExp;
3032 IndexExpr = LHSExp;
3033 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003034 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003035 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003036 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003037 VK = LHSExp->getValueKind();
3038 if (VK != VK_RValue)
3039 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003040
Chris Lattner12d9ff62007-07-16 00:14:47 +00003041 // FIXME: need to deal with const...
3042 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003043 } else if (LHSTy->isArrayType()) {
3044 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003045 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003046 // wasn't promoted because of the C90 rule that doesn't
3047 // allow promoting non-lvalue arrays. Warn, then
3048 // force the promotion here.
3049 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3050 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003051 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3052 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003053 LHSTy = LHSExp->getType();
3054
3055 BaseExpr = LHSExp;
3056 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003057 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003058 } else if (RHSTy->isArrayType()) {
3059 // Same as previous, except for 123[f().a] case
3060 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3061 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003062 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3063 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003064 RHSTy = RHSExp->getType();
3065
3066 BaseExpr = RHSExp;
3067 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003068 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003069 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003070 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3071 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003072 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003073 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003074 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003075 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3076 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003077
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003078 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003079 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3080 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003081 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3082
Douglas Gregore7450f52009-03-24 19:52:54 +00003083 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003084 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3085 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003086 // incomplete types are not object types.
3087 if (ResultType->isFunctionType()) {
3088 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3089 << ResultType << BaseExpr->getSourceRange();
3090 return ExprError();
3091 }
Mike Stump1eb44332009-09-09 15:08:12 +00003092
Abramo Bagnara46358452010-09-13 06:50:07 +00003093 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3094 // GNU extension: subscripting on pointer to void
3095 Diag(LLoc, diag::ext_gnu_void_ptr)
3096 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003097
3098 // C forbids expressions of unqualified void type from being l-values.
3099 // See IsCForbiddenLValueType.
3100 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003101 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003102 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003103 PDiag(diag::err_subscript_incomplete_type)
3104 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003105 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003106
Chris Lattner1efaa952009-04-24 00:30:45 +00003107 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003108 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003109 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3110 << ResultType << BaseExpr->getSourceRange();
3111 return ExprError();
3112 }
Mike Stump1eb44332009-09-09 15:08:12 +00003113
John McCall09431682010-11-18 19:01:18 +00003114 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003115 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003116
Mike Stumpeed9cac2009-02-19 03:04:26 +00003117 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003118 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003119}
3120
John McCall60d7b3a2010-08-24 06:29:42 +00003121ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003122 FunctionDecl *FD,
3123 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003124 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003125 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003126 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003127 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003128 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003129 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003130 return ExprError();
3131 }
3132
3133 if (Param->hasUninstantiatedDefaultArg()) {
3134 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003135
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003136 // Instantiate the expression.
3137 MultiLevelTemplateArgumentList ArgList
3138 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003139
Nico Weber08e41a62010-11-29 18:19:25 +00003140 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003141 = ArgList.getInnermost();
3142 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3143 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003144
Nico Weber08e41a62010-11-29 18:19:25 +00003145 ExprResult Result;
3146 {
3147 // C++ [dcl.fct.default]p5:
3148 // The names in the [default argument] expression are bound, and
3149 // the semantic constraints are checked, at the point where the
3150 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003151 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00003152 Result = SubstExpr(UninstExpr, ArgList);
3153 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003154 if (Result.isInvalid())
3155 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003156
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003157 // Check the expression as an initializer for the parameter.
3158 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003159 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003160 InitializationKind Kind
3161 = InitializationKind::CreateCopy(Param->getLocation(),
3162 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3163 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003164
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003165 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3166 Result = InitSeq.Perform(*this, Entity, Kind,
3167 MultiExprArg(*this, &ResultE, 1));
3168 if (Result.isInvalid())
3169 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003170
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003171 // Build the default argument expression.
3172 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3173 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003174 }
3175
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003176 // If the default expression creates temporaries, we need to
3177 // push them to the current stack of expression temporaries so they'll
3178 // be properly destroyed.
3179 // FIXME: We should really be rebuilding the default argument with new
3180 // bound temporaries; see the comment in PR5810.
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003181 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3182 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3183 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3184 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3185 ExprTemporaries.push_back(Temporary);
John McCallf85e1932011-06-15 23:02:42 +00003186 ExprNeedsCleanups = true;
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003187 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003188
3189 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003190 // Just mark all of the declarations in this potentially-evaluated expression
3191 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003192 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00003193 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003194}
3195
Douglas Gregor88a35142008-12-22 05:46:06 +00003196/// ConvertArgumentsForCall - Converts the arguments specified in
3197/// Args/NumArgs to the parameter types of the function FDecl with
3198/// function prototype Proto. Call is the call expression itself, and
3199/// Fn is the function expression. For a C++ member function, this
3200/// routine does not attempt to convert the object argument. Returns
3201/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003202bool
3203Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003204 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003205 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003206 Expr **Args, unsigned NumArgs,
3207 SourceLocation RParenLoc) {
John McCall8e10f3b2011-02-26 05:39:39 +00003208 // Bail out early if calling a builtin with custom typechecking.
3209 // We don't need to do this in the
3210 if (FDecl)
3211 if (unsigned ID = FDecl->getBuiltinID())
3212 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3213 return false;
3214
Mike Stumpeed9cac2009-02-19 03:04:26 +00003215 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003216 // assignment, to the types of the corresponding parameter, ...
3217 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003218 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003219
Douglas Gregor88a35142008-12-22 05:46:06 +00003220 // If too few arguments are available (and we don't have default
3221 // arguments for the remaining parameters), don't make the call.
3222 if (NumArgs < NumArgsInProto) {
3223 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3224 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003225 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00003226 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00003227 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003228 }
3229
3230 // If too many are passed and not variadic, error on the extras and drop
3231 // them.
3232 if (NumArgs > NumArgsInProto) {
3233 if (!Proto->isVariadic()) {
3234 Diag(Args[NumArgsInProto]->getLocStart(),
3235 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003236 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00003237 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00003238 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3239 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003240
3241 // Emit the location of the prototype.
3242 if (FDecl && !FDecl->getBuiltinID())
3243 Diag(FDecl->getLocStart(),
3244 diag::note_typecheck_call_too_many_args)
3245 << FDecl;
3246
Douglas Gregor88a35142008-12-22 05:46:06 +00003247 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003248 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003249 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003250 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003251 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003252 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003253 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003254 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3255 if (Fn->getType()->isBlockPointerType())
3256 CallType = VariadicBlock; // Block
3257 else if (isa<MemberExpr>(Fn))
3258 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003259 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003260 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003261 if (Invalid)
3262 return true;
3263 unsigned TotalNumArgs = AllArgs.size();
3264 for (unsigned i = 0; i < TotalNumArgs; ++i)
3265 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003266
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003267 return false;
3268}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003269
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003270bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3271 FunctionDecl *FDecl,
3272 const FunctionProtoType *Proto,
3273 unsigned FirstProtoArg,
3274 Expr **Args, unsigned NumArgs,
3275 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003276 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003277 unsigned NumArgsInProto = Proto->getNumArgs();
3278 unsigned NumArgsToCheck = NumArgs;
3279 bool Invalid = false;
3280 if (NumArgs != NumArgsInProto)
3281 // Use default arguments for missing arguments
3282 NumArgsToCheck = NumArgsInProto;
3283 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003284 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003285 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003286 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003287
Douglas Gregor88a35142008-12-22 05:46:06 +00003288 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003289 if (ArgIx < NumArgs) {
3290 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003291
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003292 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3293 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003294 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003295 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003296 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003297
Douglas Gregora188ff22009-12-22 16:09:06 +00003298 // Pass the argument
3299 ParmVarDecl *Param = 0;
3300 if (FDecl && i < FDecl->getNumParams())
3301 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003302
Douglas Gregora188ff22009-12-22 16:09:06 +00003303 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003304 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00003305 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3306 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003307 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003308 SourceLocation(),
3309 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00003310 if (ArgE.isInvalid())
3311 return true;
3312
3313 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003314 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003315 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003316
John McCall60d7b3a2010-08-24 06:29:42 +00003317 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003318 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003319 if (ArgExpr.isInvalid())
3320 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003321
Anders Carlsson56c5e332009-08-25 03:49:14 +00003322 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003323 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003324 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003325 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003326
Douglas Gregor88a35142008-12-22 05:46:06 +00003327 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003328 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003329
3330 // Assume that extern "C" functions with variadic arguments that
3331 // return __unknown_anytype aren't *really* variadic.
3332 if (Proto->getResultType() == Context.UnknownAnyTy &&
3333 FDecl && FDecl->isExternC()) {
3334 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3335 ExprResult arg;
3336 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3337 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3338 else
3339 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3340 Invalid |= arg.isInvalid();
3341 AllArgs.push_back(arg.take());
3342 }
3343
3344 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3345 } else {
3346 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3347 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3348 Invalid |= Arg.isInvalid();
3349 AllArgs.push_back(Arg.take());
3350 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003351 }
3352 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003353 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003354}
3355
John McCall755d8492011-04-12 00:42:48 +00003356/// Given a function expression of unknown-any type, try to rebuild it
3357/// to have a function type.
3358static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3359
Steve Narofff69936d2007-09-16 03:34:24 +00003360/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003361/// This provides the location of the left/right parens and a list of comma
3362/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003363ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003364Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003365 MultiExprArg args, SourceLocation RParenLoc,
3366 Expr *ExecConfig) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00003367 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003368
3369 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003370 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003371 if (Result.isInvalid()) return ExprError();
3372 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003373
John McCall9ae2f072010-08-23 23:25:46 +00003374 Expr **Args = args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003375
Douglas Gregor88a35142008-12-22 05:46:06 +00003376 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003377 // If this is a pseudo-destructor expression, build the call immediately.
3378 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3379 if (NumArgs > 0) {
3380 // Pseudo-destructor calls should not have any arguments.
3381 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003382 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00003383 SourceRange(Args[0]->getLocStart(),
3384 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003385
Douglas Gregora71d8192009-09-04 17:36:40 +00003386 NumArgs = 0;
3387 }
Mike Stump1eb44332009-09-09 15:08:12 +00003388
Douglas Gregora71d8192009-09-04 17:36:40 +00003389 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00003390 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003391 }
Mike Stump1eb44332009-09-09 15:08:12 +00003392
Douglas Gregor17330012009-02-04 15:01:18 +00003393 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003394 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003395 // FIXME: Will need to cache the results of name lookup (including ADL) in
3396 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003397 bool Dependent = false;
3398 if (Fn->isTypeDependent())
3399 Dependent = true;
3400 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3401 Dependent = true;
3402
Peter Collingbournee08ce652011-02-09 21:07:24 +00003403 if (Dependent) {
3404 if (ExecConfig) {
3405 return Owned(new (Context) CUDAKernelCallExpr(
3406 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3407 Context.DependentTy, VK_RValue, RParenLoc));
3408 } else {
3409 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3410 Context.DependentTy, VK_RValue,
3411 RParenLoc));
3412 }
3413 }
Douglas Gregor17330012009-02-04 15:01:18 +00003414
3415 // Determine whether this is a call to an object (C++ [over.call.object]).
3416 if (Fn->getType()->isRecordType())
3417 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003418 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003419
John McCall755d8492011-04-12 00:42:48 +00003420 if (Fn->getType() == Context.UnknownAnyTy) {
3421 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3422 if (result.isInvalid()) return ExprError();
3423 Fn = result.take();
3424 }
3425
John McCall864c0412011-04-26 20:42:42 +00003426 if (Fn->getType() == Context.BoundMemberTy) {
John McCallaa81e162009-12-01 22:10:20 +00003427 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003428 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003429 }
John McCall864c0412011-04-26 20:42:42 +00003430 }
John McCall129e2df2009-11-30 22:42:35 +00003431
John McCall864c0412011-04-26 20:42:42 +00003432 // Check for overloaded calls. This can happen even in C due to extensions.
3433 if (Fn->getType() == Context.OverloadTy) {
3434 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3435
3436 // We aren't supposed to apply this logic if there's an '&' involved.
3437 if (!find.IsAddressOfOperand) {
3438 OverloadExpr *ovl = find.Expression;
3439 if (isa<UnresolvedLookupExpr>(ovl)) {
3440 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3441 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3442 RParenLoc, ExecConfig);
3443 } else {
John McCallaa81e162009-12-01 22:10:20 +00003444 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003445 RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003446 }
3447 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003448 }
3449
Douglas Gregorfa047642009-02-04 00:32:51 +00003450 // If we're directly calling a function, get the appropriate declaration.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003451
Eli Friedmanefa42f72009-12-26 03:35:45 +00003452 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00003453
John McCall3b4294e2009-12-16 12:17:52 +00003454 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00003455 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3456 if (UnOp->getOpcode() == UO_AddrOf)
3457 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3458
John McCall3b4294e2009-12-16 12:17:52 +00003459 if (isa<DeclRefExpr>(NakedFn))
3460 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00003461 else if (isa<MemberExpr>(NakedFn))
3462 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00003463
Peter Collingbournee08ce652011-02-09 21:07:24 +00003464 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3465 ExecConfig);
3466}
3467
3468ExprResult
3469Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3470 MultiExprArg execConfig, SourceLocation GGGLoc) {
3471 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3472 if (!ConfigDecl)
3473 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3474 << "cudaConfigureCall");
3475 QualType ConfigQTy = ConfigDecl->getType();
3476
3477 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3478 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3479
3480 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCallaa81e162009-12-01 22:10:20 +00003481}
3482
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003483/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3484///
3485/// __builtin_astype( value, dst type )
3486///
3487ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty,
3488 SourceLocation BuiltinLoc,
3489 SourceLocation RParenLoc) {
3490 ExprValueKind VK = VK_RValue;
3491 ExprObjectKind OK = OK_Ordinary;
3492 QualType DstTy = GetTypeFromParser(destty);
3493 QualType SrcTy = expr->getType();
3494 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3495 return ExprError(Diag(BuiltinLoc,
3496 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00003497 << DstTy
3498 << SrcTy
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003499 << expr->getSourceRange());
3500 return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc, RParenLoc));
3501}
3502
John McCall3b4294e2009-12-16 12:17:52 +00003503/// BuildResolvedCallExpr - Build a call to a resolved expression,
3504/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003505/// unary-convert to an expression of function-pointer or
3506/// block-pointer type.
3507///
3508/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00003509ExprResult
John McCallaa81e162009-12-01 22:10:20 +00003510Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3511 SourceLocation LParenLoc,
3512 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003513 SourceLocation RParenLoc,
3514 Expr *Config) {
John McCallaa81e162009-12-01 22:10:20 +00003515 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3516
Chris Lattner04421082008-04-08 04:40:51 +00003517 // Promote the function operand.
John Wiegley429bb272011-04-08 18:41:53 +00003518 ExprResult Result = UsualUnaryConversions(Fn);
3519 if (Result.isInvalid())
3520 return ExprError();
3521 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00003522
Chris Lattner925e60d2007-12-28 05:29:59 +00003523 // Make the call expr early, before semantic checks. This guarantees cleanup
3524 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00003525 CallExpr *TheCall;
3526 if (Config) {
3527 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3528 cast<CallExpr>(Config),
3529 Args, NumArgs,
3530 Context.BoolTy,
3531 VK_RValue,
3532 RParenLoc);
3533 } else {
3534 TheCall = new (Context) CallExpr(Context, Fn,
3535 Args, NumArgs,
3536 Context.BoolTy,
3537 VK_RValue,
3538 RParenLoc);
3539 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003540
John McCall8e10f3b2011-02-26 05:39:39 +00003541 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3542
3543 // Bail out early if calling a builtin with custom typechecking.
3544 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3545 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3546
John McCall1de4d4e2011-04-07 08:22:57 +00003547 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00003548 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00003549 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00003550 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3551 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00003552 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00003553 if (FuncT == 0)
3554 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3555 << Fn->getType() << Fn->getSourceRange());
3556 } else if (const BlockPointerType *BPT =
3557 Fn->getType()->getAs<BlockPointerType>()) {
3558 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3559 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00003560 // Handle calls to expressions of unknown-any type.
3561 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00003562 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003563 if (rewrite.isInvalid()) return ExprError();
3564 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00003565 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003566 goto retry;
3567 }
3568
Sebastian Redl0eb23302009-01-19 00:08:26 +00003569 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3570 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00003571 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003572
Peter Collingbourne0423fc62011-02-23 01:53:29 +00003573 if (getLangOptions().CUDA) {
3574 if (Config) {
3575 // CUDA: Kernel calls must be to global functions
3576 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3577 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3578 << FDecl->getName() << Fn->getSourceRange());
3579
3580 // CUDA: Kernel function must have 'void' return type
3581 if (!FuncT->getResultType()->isVoidType())
3582 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3583 << Fn->getType() << Fn->getSourceRange());
3584 }
3585 }
3586
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003587 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003588 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00003589 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003590 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003591 return ExprError();
3592
Chris Lattner925e60d2007-12-28 05:29:59 +00003593 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003594 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00003595 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003596
Douglas Gregor72564e72009-02-26 23:50:07 +00003597 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00003598 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003599 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003600 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003601 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003602 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003603
Douglas Gregor74734d52009-04-02 15:37:10 +00003604 if (FDecl) {
3605 // Check if we have too few/too many template arguments, based
3606 // on our knowledge of the function definition.
3607 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00003608 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00003609 const FunctionProtoType *Proto
3610 = Def->getType()->getAs<FunctionProtoType>();
3611 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003612 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3613 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003614 }
Douglas Gregor46542412010-10-25 20:39:23 +00003615
3616 // If the function we're calling isn't a function prototype, but we have
3617 // a function prototype from a prior declaratiom, use that prototype.
3618 if (!FDecl->hasPrototype())
3619 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00003620 }
3621
Steve Naroffb291ab62007-08-28 23:30:39 +00003622 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003623 for (unsigned i = 0; i != NumArgs; i++) {
3624 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00003625
3626 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00003627 InitializedEntity Entity
3628 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00003629 Proto->getArgType(i),
3630 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00003631 ExprResult ArgE = PerformCopyInitialization(Entity,
3632 SourceLocation(),
3633 Owned(Arg));
3634 if (ArgE.isInvalid())
3635 return true;
3636
3637 Arg = ArgE.takeAs<Expr>();
3638
3639 } else {
John Wiegley429bb272011-04-08 18:41:53 +00003640 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3641
3642 if (ArgE.isInvalid())
3643 return true;
3644
3645 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00003646 }
3647
Douglas Gregor0700bbf2010-10-26 05:45:40 +00003648 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3649 Arg->getType(),
3650 PDiag(diag::err_call_incomplete_argument)
3651 << Arg->getSourceRange()))
3652 return ExprError();
3653
Chris Lattner925e60d2007-12-28 05:29:59 +00003654 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003655 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003656 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003657
Douglas Gregor88a35142008-12-22 05:46:06 +00003658 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3659 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003660 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3661 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003662
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003663 // Check for sentinels
3664 if (NDecl)
3665 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003666
Chris Lattner59907c42007-08-10 20:18:51 +00003667 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003668 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003669 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003670 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003671
John McCall8e10f3b2011-02-26 05:39:39 +00003672 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00003673 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00003674 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003675 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003676 return ExprError();
3677 }
Chris Lattner59907c42007-08-10 20:18:51 +00003678
John McCall9ae2f072010-08-23 23:25:46 +00003679 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00003680}
3681
John McCall60d7b3a2010-08-24 06:29:42 +00003682ExprResult
John McCallb3d87482010-08-24 05:47:05 +00003683Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00003684 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003685 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00003686 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003687 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00003688
3689 TypeSourceInfo *TInfo;
3690 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3691 if (!TInfo)
3692 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3693
John McCall9ae2f072010-08-23 23:25:46 +00003694 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00003695}
3696
John McCall60d7b3a2010-08-24 06:29:42 +00003697ExprResult
John McCall42f56b52010-01-18 19:35:47 +00003698Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCall9ae2f072010-08-23 23:25:46 +00003699 SourceLocation RParenLoc, Expr *literalExpr) {
John McCall42f56b52010-01-18 19:35:47 +00003700 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00003701
Eli Friedman6223c222008-05-20 05:22:08 +00003702 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00003703 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3704 PDiag(diag::err_illegal_decl_array_incomplete_type)
3705 << SourceRange(LParenLoc,
3706 literalExpr->getSourceRange().getEnd())))
3707 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003708 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003709 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3710 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003711 } else if (!literalType->isDependentType() &&
3712 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003713 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003714 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003715 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003716 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003717
Douglas Gregor99a2e602009-12-16 01:38:02 +00003718 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00003719 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003720 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00003721 = InitializationKind::CreateCStyleCast(LParenLoc,
3722 SourceRange(LParenLoc, RParenLoc));
Eli Friedman08544622009-12-22 02:35:53 +00003723 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00003724 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00003725 MultiExprArg(*this, &literalExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00003726 &literalType);
3727 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003728 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00003729 literalExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00003730
Chris Lattner371f2582008-12-04 23:50:19 +00003731 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003732 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003733 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003734 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003735 }
Eli Friedman08544622009-12-22 02:35:53 +00003736
John McCallf89e55a2010-11-18 06:31:45 +00003737 // In C, compound literals are l-values for some reason.
3738 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3739
Douglas Gregor751ec9b2011-06-17 04:59:12 +00003740 return MaybeBindToTemporary(
3741 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
3742 VK, literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003743}
3744
John McCall60d7b3a2010-08-24 06:29:42 +00003745ExprResult
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003746Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003747 SourceLocation RBraceLoc) {
3748 unsigned NumInit = initlist.size();
John McCall9ae2f072010-08-23 23:25:46 +00003749 Expr **InitList = initlist.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003750
Steve Naroff08d92e42007-09-15 18:49:24 +00003751 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003752 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003753
Ted Kremenek709210f2010-04-13 23:39:13 +00003754 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3755 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003756 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003757 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003758}
3759
John McCallf3ea8cf2010-11-14 08:17:51 +00003760/// Prepares for a scalar cast, performing all the necessary stages
3761/// except the final cast and returning the kind required.
John Wiegley429bb272011-04-08 18:41:53 +00003762static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00003763 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3764 // Also, callers should have filtered out the invalid cases with
3765 // pointers. Everything else should be possible.
3766
John Wiegley429bb272011-04-08 18:41:53 +00003767 QualType SrcTy = Src.get()->getType();
John McCallf3ea8cf2010-11-14 08:17:51 +00003768 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00003769 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00003770
John McCalldaa8e4e2010-11-15 09:13:47 +00003771 switch (SrcTy->getScalarTypeKind()) {
3772 case Type::STK_MemberPointer:
3773 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003774
John McCalldaa8e4e2010-11-15 09:13:47 +00003775 case Type::STK_Pointer:
3776 switch (DestTy->getScalarTypeKind()) {
3777 case Type::STK_Pointer:
3778 return DestTy->isObjCObjectPointerType() ?
John McCallf3ea8cf2010-11-14 08:17:51 +00003779 CK_AnyPointerToObjCPointerCast :
3780 CK_BitCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003781 case Type::STK_Bool:
3782 return CK_PointerToBoolean;
3783 case Type::STK_Integral:
3784 return CK_PointerToIntegral;
3785 case Type::STK_Floating:
3786 case Type::STK_FloatingComplex:
3787 case Type::STK_IntegralComplex:
3788 case Type::STK_MemberPointer:
3789 llvm_unreachable("illegal cast from pointer");
3790 }
3791 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003792
John McCalldaa8e4e2010-11-15 09:13:47 +00003793 case Type::STK_Bool: // casting from bool is like casting from an integer
3794 case Type::STK_Integral:
3795 switch (DestTy->getScalarTypeKind()) {
3796 case Type::STK_Pointer:
John Wiegley429bb272011-04-08 18:41:53 +00003797 if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00003798 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00003799 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00003800 case Type::STK_Bool:
3801 return CK_IntegralToBoolean;
3802 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00003803 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003804 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00003805 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00003806 case Type::STK_IntegralComplex:
John Wiegley429bb272011-04-08 18:41:53 +00003807 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3808 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00003809 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003810 case Type::STK_FloatingComplex:
John Wiegley429bb272011-04-08 18:41:53 +00003811 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3812 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00003813 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003814 case Type::STK_MemberPointer:
3815 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003816 }
3817 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003818
John McCalldaa8e4e2010-11-15 09:13:47 +00003819 case Type::STK_Floating:
3820 switch (DestTy->getScalarTypeKind()) {
3821 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00003822 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003823 case Type::STK_Bool:
3824 return CK_FloatingToBoolean;
3825 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00003826 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00003827 case Type::STK_FloatingComplex:
John Wiegley429bb272011-04-08 18:41:53 +00003828 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3829 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00003830 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003831 case Type::STK_IntegralComplex:
John Wiegley429bb272011-04-08 18:41:53 +00003832 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
3833 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00003834 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003835 case Type::STK_Pointer:
3836 llvm_unreachable("valid float->pointer cast?");
3837 case Type::STK_MemberPointer:
3838 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003839 }
3840 break;
3841
John McCalldaa8e4e2010-11-15 09:13:47 +00003842 case Type::STK_FloatingComplex:
3843 switch (DestTy->getScalarTypeKind()) {
3844 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003845 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003846 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003847 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00003848 case Type::STK_Floating: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003849 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00003850 if (S.Context.hasSameType(ET, DestTy))
3851 return CK_FloatingComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00003852 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00003853 return CK_FloatingCast;
3854 }
John McCalldaa8e4e2010-11-15 09:13:47 +00003855 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00003856 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00003857 case Type::STK_Integral:
John Wiegley429bb272011-04-08 18:41:53 +00003858 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
3859 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00003860 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00003861 case Type::STK_Pointer:
3862 llvm_unreachable("valid complex float->pointer cast?");
3863 case Type::STK_MemberPointer:
3864 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003865 }
3866 break;
3867
John McCalldaa8e4e2010-11-15 09:13:47 +00003868 case Type::STK_IntegralComplex:
3869 switch (DestTy->getScalarTypeKind()) {
3870 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003871 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003872 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003873 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00003874 case Type::STK_Integral: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003875 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00003876 if (S.Context.hasSameType(ET, DestTy))
3877 return CK_IntegralComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00003878 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00003879 return CK_IntegralCast;
3880 }
John McCalldaa8e4e2010-11-15 09:13:47 +00003881 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00003882 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00003883 case Type::STK_Floating:
John Wiegley429bb272011-04-08 18:41:53 +00003884 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
3885 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00003886 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00003887 case Type::STK_Pointer:
3888 llvm_unreachable("valid complex int->pointer cast?");
3889 case Type::STK_MemberPointer:
3890 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003891 }
3892 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00003893 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003894
John McCallf3ea8cf2010-11-14 08:17:51 +00003895 llvm_unreachable("Unhandled scalar cast");
3896 return CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00003897}
3898
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003899/// CheckCastTypes - Check type constraints for casting between types.
John McCallf85e1932011-06-15 23:02:42 +00003900ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyR,
3901 QualType castType, Expr *castExpr,
3902 CastKind& Kind, ExprValueKind &VK,
John Wiegley429bb272011-04-08 18:41:53 +00003903 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall1de4d4e2011-04-07 08:22:57 +00003904 if (castExpr->getType() == Context.UnknownAnyTy)
3905 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
3906
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003907 if (getLangOptions().CPlusPlus)
John McCallf85e1932011-06-15 23:02:42 +00003908 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Douglas Gregor40749ee2010-11-03 00:35:38 +00003909 castExpr->getLocEnd()),
John McCallf89e55a2010-11-18 06:31:45 +00003910 castType, VK, castExpr, Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003911 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003912
John McCallfb8721c2011-04-10 19:13:55 +00003913 assert(!castExpr->getType()->isPlaceholderType());
3914
John McCallf89e55a2010-11-18 06:31:45 +00003915 // We only support r-value casts in C.
3916 VK = VK_RValue;
3917
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003918 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3919 // type needs to be scalar.
3920 if (castType->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +00003921 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley429bb272011-04-08 18:41:53 +00003922 ExprResult castExprRes = IgnoredValueConversions(castExpr);
3923 if (castExprRes.isInvalid())
3924 return ExprError();
3925 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00003926
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003927 // Cast to void allows any expr type.
John McCall2de56d12010-08-25 11:45:40 +00003928 Kind = CK_ToVoid;
John Wiegley429bb272011-04-08 18:41:53 +00003929 return Owned(castExpr);
Anders Carlssonebeaf202009-10-16 02:35:04 +00003930 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003931
John Wiegley429bb272011-04-08 18:41:53 +00003932 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
3933 if (castExprRes.isInvalid())
3934 return ExprError();
3935 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00003936
Eli Friedman8d438082010-07-17 20:43:49 +00003937 if (RequireCompleteType(TyR.getBegin(), castType,
3938 diag::err_typecheck_cast_to_incomplete))
John Wiegley429bb272011-04-08 18:41:53 +00003939 return ExprError();
Eli Friedman8d438082010-07-17 20:43:49 +00003940
Anders Carlssonebeaf202009-10-16 02:35:04 +00003941 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003942 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003943 (castType->isStructureType() || castType->isUnionType())) {
3944 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003945 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003946 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3947 << castType << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003948 Kind = CK_NoOp;
John Wiegley429bb272011-04-08 18:41:53 +00003949 return Owned(castExpr);
Anders Carlssonc3516322009-10-16 02:48:28 +00003950 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003951
Anders Carlssonc3516322009-10-16 02:48:28 +00003952 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003953 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00003954 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003955 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003956 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003957 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003958 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara8c4bfe52010-10-07 21:20:44 +00003959 castExpr->getType()) &&
3960 !Field->isUnnamedBitfield()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003961 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3962 << castExpr->getSourceRange();
3963 break;
3964 }
3965 }
John Wiegley429bb272011-04-08 18:41:53 +00003966 if (Field == FieldEnd) {
3967 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003968 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003969 return ExprError();
3970 }
John McCall2de56d12010-08-25 11:45:40 +00003971 Kind = CK_ToUnion;
John Wiegley429bb272011-04-08 18:41:53 +00003972 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003973 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003974
Anders Carlssonc3516322009-10-16 02:48:28 +00003975 // Reject any other conversions to non-scalar types.
John Wiegley429bb272011-04-08 18:41:53 +00003976 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlssonc3516322009-10-16 02:48:28 +00003977 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003978 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00003979 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003980
John McCallf3ea8cf2010-11-14 08:17:51 +00003981 // The type we're casting to is known to be a scalar or vector.
3982
3983 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003984 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00003985 !castExpr->getType()->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00003986 Diag(castExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003987 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003988 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003989 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00003990 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003991
3992 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00003993 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003994
Anton Yartsevd06fea82011-03-27 09:32:40 +00003995 if (castType->isVectorType()) {
3996 if (castType->getAs<VectorType>()->getVectorKind() ==
3997 VectorType::AltiVecVector &&
3998 (castExpr->getType()->isIntegerType() ||
3999 castExpr->getType()->isFloatingType())) {
4000 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004001 return Owned(castExpr);
4002 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
4003 return ExprError();
Anton Yartsevd06fea82011-03-27 09:32:40 +00004004 } else
John Wiegley429bb272011-04-08 18:41:53 +00004005 return Owned(castExpr);
Anton Yartsevd06fea82011-03-27 09:32:40 +00004006 }
John Wiegley429bb272011-04-08 18:41:53 +00004007 if (castExpr->getType()->isVectorType()) {
4008 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
4009 return ExprError();
4010 else
4011 return Owned(castExpr);
4012 }
Anders Carlssonc3516322009-10-16 02:48:28 +00004013
John McCallf3ea8cf2010-11-14 08:17:51 +00004014 // The source and target types are both scalars, i.e.
4015 // - arithmetic types (fundamental, enum, and complex)
4016 // - all kinds of pointers
4017 // Note that member pointers were filtered out with C++, above.
4018
John Wiegley429bb272011-04-08 18:41:53 +00004019 if (isa<ObjCSelectorExpr>(castExpr)) {
4020 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
4021 return ExprError();
4022 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004023
John McCallf3ea8cf2010-11-14 08:17:51 +00004024 // If either type is a pointer, the other type has to be either an
4025 // integer or a pointer.
John McCallf85e1932011-06-15 23:02:42 +00004026 QualType castExprType = castExpr->getType();
Anders Carlssonc3516322009-10-16 02:48:28 +00004027 if (!castType->isArithmeticType()) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00004028 if (!castExprType->isIntegralType(Context) &&
John Wiegley429bb272011-04-08 18:41:53 +00004029 castExprType->isArithmeticType()) {
4030 Diag(castExpr->getLocStart(),
4031 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00004032 << castExprType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004033 return ExprError();
4034 }
Eli Friedman41826bb2009-05-01 02:23:58 +00004035 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004036 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
4037 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00004038 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004039 return ExprError();
4040 }
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004041 }
Anders Carlsson82debc72009-10-18 18:12:03 +00004042
John McCallf85e1932011-06-15 23:02:42 +00004043 if (getLangOptions().ObjCAutoRefCount) {
4044 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
4045 CheckObjCARCConversion(SourceRange(CastStartLoc, castExpr->getLocEnd()),
4046 castType, castExpr, CCK_CStyleCast);
4047
4048 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
4049 if (const PointerType *ExprPtr = castExprType->getAs<PointerType>()) {
4050 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4051 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4052 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4053 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4054 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
4055 Diag(castExpr->getLocStart(),
4056 diag::err_typecheck_incompatible_lifetime)
4057 << castExprType << castType << AA_Casting
4058 << castExpr->getSourceRange();
4059
4060 return ExprError();
4061 }
4062 }
4063 }
4064 }
4065
John Wiegley429bb272011-04-08 18:41:53 +00004066 castExprRes = Owned(castExpr);
4067 Kind = PrepareScalarCast(*this, castExprRes, castType);
4068 if (castExprRes.isInvalid())
4069 return ExprError();
4070 castExpr = castExprRes.take();
John McCallb7f4ffe2010-08-12 21:44:57 +00004071
John McCallf3ea8cf2010-11-14 08:17:51 +00004072 if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00004073 CheckCastAlign(castExpr, castType, TyR);
4074
John Wiegley429bb272011-04-08 18:41:53 +00004075 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004076}
4077
Anders Carlssonc3516322009-10-16 02:48:28 +00004078bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004079 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004080 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004081
Anders Carlssona64db8f2007-11-27 05:51:55 +00004082 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004083 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004084 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004085 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004086 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004087 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004088 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004089 } else
4090 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004091 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004092 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004093
John McCall2de56d12010-08-25 11:45:40 +00004094 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004095 return false;
4096}
4097
John Wiegley429bb272011-04-08 18:41:53 +00004098ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4099 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004100 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004101
Anders Carlsson16a89042009-10-16 05:23:41 +00004102 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004103
Nate Begeman9b10da62009-06-27 22:05:55 +00004104 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4105 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00004106 if (SrcTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004107 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
4108 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004109 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004110 return ExprError();
4111 }
John McCall2de56d12010-08-25 11:45:40 +00004112 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004113 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004114 }
4115
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004116 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004117 // conversion will take place first from scalar to elt type, and then
4118 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004119 if (SrcTy->isPointerType())
4120 return Diag(R.getBegin(),
4121 diag::err_invalid_conversion_between_vector_and_scalar)
4122 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004123
4124 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004125 ExprResult CastExprRes = Owned(CastExpr);
4126 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4127 if (CastExprRes.isInvalid())
4128 return ExprError();
4129 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004130
John McCall2de56d12010-08-25 11:45:40 +00004131 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004132 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004133}
4134
John McCall60d7b3a2010-08-24 06:29:42 +00004135ExprResult
John McCallb3d87482010-08-24 05:47:05 +00004136Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004137 SourceLocation RParenLoc, Expr *castExpr) {
4138 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004139 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004140
John McCall9d125032010-01-15 18:39:57 +00004141 TypeSourceInfo *castTInfo;
4142 QualType castType = GetTypeFromParser(Ty, &castTInfo);
4143 if (!castTInfo)
John McCall42f56b52010-01-18 19:35:47 +00004144 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00004145
Nate Begeman2ef13e52009-08-10 23:49:36 +00004146 // If the Expr being casted is a ParenListExpr, handle it specially.
4147 if (isa<ParenListExpr>(castExpr))
John McCall9ae2f072010-08-23 23:25:46 +00004148 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCall42f56b52010-01-18 19:35:47 +00004149 castTInfo);
John McCallb042fdf2010-01-15 18:56:44 +00004150
John McCall9ae2f072010-08-23 23:25:46 +00004151 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004152}
4153
John McCall60d7b3a2010-08-24 06:29:42 +00004154ExprResult
John McCallb042fdf2010-01-15 18:56:44 +00004155Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004156 SourceLocation RParenLoc, Expr *castExpr) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004157 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +00004158 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +00004159 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +00004160 ExprResult CastResult =
John McCallf85e1932011-06-15 23:02:42 +00004161 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
4162 castExpr, Kind, VK, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +00004163 if (CastResult.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004164 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004165 castExpr = CastResult.take();
Anders Carlsson0aebc812009-09-09 21:33:21 +00004166
John McCallf871d0c2010-08-07 06:22:56 +00004167 return Owned(CStyleCastExpr::Create(Context,
John Wiegley429bb272011-04-08 18:41:53 +00004168 Ty->getType().getNonLValueExprType(Context),
John McCallf89e55a2010-11-18 06:31:45 +00004169 VK, Kind, castExpr, &BasePath, Ty,
John McCallf871d0c2010-08-07 06:22:56 +00004170 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00004171}
4172
Nate Begeman2ef13e52009-08-10 23:49:36 +00004173/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4174/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004175ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004176Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004177 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4178 if (!E)
4179 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00004180
John McCall60d7b3a2010-08-24 06:29:42 +00004181 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004182
Nate Begeman2ef13e52009-08-10 23:49:36 +00004183 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004184 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4185 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004186
John McCall9ae2f072010-08-23 23:25:46 +00004187 if (Result.isInvalid()) return ExprError();
4188
4189 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004190}
4191
John McCall60d7b3a2010-08-24 06:29:42 +00004192ExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00004193Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00004194 SourceLocation RParenLoc, Expr *Op,
John McCall42f56b52010-01-18 19:35:47 +00004195 TypeSourceInfo *TInfo) {
John McCall9ae2f072010-08-23 23:25:46 +00004196 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCall42f56b52010-01-18 19:35:47 +00004197 QualType Ty = TInfo->getType();
Anton Yartsevd06fea82011-03-27 09:32:40 +00004198 bool isVectorLiteral = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004199
Anton Yartsevd06fea82011-03-27 09:32:40 +00004200 // Check for an altivec or OpenCL literal,
John Thompson8bb59a82010-06-30 22:55:51 +00004201 // i.e. all the elements are integer constants.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004202 if (getLangOptions().AltiVec && Ty->isVectorType()) {
4203 if (PE->getNumExprs() == 0) {
4204 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
4205 return ExprError();
4206 }
John Thompson8bb59a82010-06-30 22:55:51 +00004207 if (PE->getNumExprs() == 1) {
4208 if (!PE->getExpr(0)->getType()->isVectorType())
Anton Yartsevd06fea82011-03-27 09:32:40 +00004209 isVectorLiteral = true;
John Thompson8bb59a82010-06-30 22:55:51 +00004210 }
4211 else
Anton Yartsevd06fea82011-03-27 09:32:40 +00004212 isVectorLiteral = true;
John Thompson8bb59a82010-06-30 22:55:51 +00004213 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00004214
Anton Yartsevd06fea82011-03-27 09:32:40 +00004215 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
John Thompson8bb59a82010-06-30 22:55:51 +00004216 // then handle it as such.
Anton Yartsevd06fea82011-03-27 09:32:40 +00004217 if (isVectorLiteral) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004218 llvm::SmallVector<Expr *, 8> initExprs;
Anton Yartsevd06fea82011-03-27 09:32:40 +00004219 // '(...)' form of vector initialization in AltiVec: the number of
4220 // initializers must be one or must match the size of the vector.
4221 // If a single value is specified in the initializer then it will be
4222 // replicated to all the components of the vector
4223 if (Ty->getAs<VectorType>()->getVectorKind() ==
4224 VectorType::AltiVecVector) {
4225 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4226 // The number of initializers must be one or must match the size of the
4227 // vector. If a single value is specified in the initializer then it will
4228 // be replicated to all the components of the vector
4229 if (PE->getNumExprs() == 1) {
4230 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004231 ExprResult Literal = Owned(PE->getExpr(0));
4232 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4233 PrepareScalarCast(*this, Literal, ElemTy));
4234 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
Anton Yartsevd06fea82011-03-27 09:32:40 +00004235 }
4236 else if (PE->getNumExprs() < numElems) {
4237 Diag(PE->getExprLoc(),
4238 diag::err_incorrect_number_of_vector_initializers);
4239 return ExprError();
4240 }
4241 else
4242 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4243 initExprs.push_back(PE->getExpr(i));
4244 }
4245 else
4246 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4247 initExprs.push_back(PE->getExpr(i));
Nate Begeman2ef13e52009-08-10 23:49:36 +00004248
4249 // FIXME: This means that pretty-printing the final AST will produce curly
4250 // braces instead of the original commas.
Ted Kremenek709210f2010-04-13 23:39:13 +00004251 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
4252 &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00004253 initExprs.size(), RParenLoc);
4254 E->setType(Ty);
John McCall9ae2f072010-08-23 23:25:46 +00004255 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004256 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004257 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00004258 // sequence of BinOp comma operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004259 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCall9ae2f072010-08-23 23:25:46 +00004260 if (Result.isInvalid()) return ExprError();
4261 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004262 }
4263}
4264
John McCall60d7b3a2010-08-24 06:29:42 +00004265ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00004266 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004267 MultiExprArg Val,
John McCallb3d87482010-08-24 05:47:05 +00004268 ParsedType TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004269 unsigned nexprs = Val.size();
4270 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004271 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4272 Expr *expr;
4273 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4274 expr = new (Context) ParenExpr(L, R, exprs[0]);
4275 else
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004276 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4277 exprs[nexprs-1]->getType());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004278 return Owned(expr);
4279}
4280
Chandler Carruth82214a82011-02-18 23:54:50 +00004281/// \brief Emit a specialized diagnostic when one expression is a null pointer
4282/// constant and the other is not a pointer.
4283bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
4284 SourceLocation QuestionLoc) {
4285 Expr *NullExpr = LHS;
4286 Expr *NonPointerExpr = RHS;
4287 Expr::NullPointerConstantKind NullKind =
4288 NullExpr->isNullPointerConstant(Context,
4289 Expr::NPC_ValueDependentIsNotNull);
4290
4291 if (NullKind == Expr::NPCK_NotNull) {
4292 NullExpr = RHS;
4293 NonPointerExpr = LHS;
4294 NullKind =
4295 NullExpr->isNullPointerConstant(Context,
4296 Expr::NPC_ValueDependentIsNotNull);
4297 }
4298
4299 if (NullKind == Expr::NPCK_NotNull)
4300 return false;
4301
4302 if (NullKind == Expr::NPCK_ZeroInteger) {
4303 // In this case, check to make sure that we got here from a "NULL"
4304 // string in the source code.
4305 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004306 SourceLocation loc = NullExpr->getExprLoc();
4307 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004308 return false;
4309 }
4310
4311 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4312 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4313 << NonPointerExpr->getType() << DiagType
4314 << NonPointerExpr->getSourceRange();
4315 return true;
4316}
4317
Sebastian Redl28507842009-02-26 14:39:58 +00004318/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4319/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004320/// C99 6.5.15
John Wiegley429bb272011-04-08 18:41:53 +00004321QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCall56ca35d2011-02-17 10:25:35 +00004322 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004323 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00004324
John McCallfb8721c2011-04-10 19:13:55 +00004325 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00004326 if (!lhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004327 LHS = move(lhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004328
John McCallfb8721c2011-04-10 19:13:55 +00004329 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00004330 if (!rhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004331 RHS = move(rhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004332
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004333 // C++ is sufficiently different to merit its own checker.
4334 if (getLangOptions().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00004335 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004336
4337 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004338 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004339
John Wiegley429bb272011-04-08 18:41:53 +00004340 Cond = UsualUnaryConversions(Cond.take());
4341 if (Cond.isInvalid())
4342 return QualType();
4343 LHS = UsualUnaryConversions(LHS.take());
4344 if (LHS.isInvalid())
4345 return QualType();
4346 RHS = UsualUnaryConversions(RHS.take());
4347 if (RHS.isInvalid())
4348 return QualType();
4349
4350 QualType CondTy = Cond.get()->getType();
4351 QualType LHSTy = LHS.get()->getType();
4352 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004353
Reid Spencer5f016e22007-07-11 17:01:13 +00004354 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004355 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begeman6155d732010-09-20 22:41:17 +00004356 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4357 // Throw an error if its not either.
4358 if (getLangOptions().OpenCL) {
4359 if (!CondTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004360 Diag(Cond.get()->getLocStart(),
Nate Begeman6155d732010-09-20 22:41:17 +00004361 diag::err_typecheck_cond_expect_scalar_or_vector)
4362 << CondTy;
4363 return QualType();
4364 }
4365 }
4366 else {
John Wiegley429bb272011-04-08 18:41:53 +00004367 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00004368 << CondTy;
4369 return QualType();
4370 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004371 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004372
Chris Lattner70d67a92008-01-06 22:42:25 +00004373 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004374 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4375 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00004376
Nate Begeman6155d732010-09-20 22:41:17 +00004377 // OpenCL: If the condition is a vector, and both operands are scalar,
4378 // attempt to implicity convert them to the vector type to act like the
4379 // built in select.
4380 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
4381 // Both operands should be of scalar type.
4382 if (!LHSTy->isScalarType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004383 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00004384 << CondTy;
4385 return QualType();
4386 }
4387 if (!RHSTy->isScalarType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004388 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00004389 << CondTy;
4390 return QualType();
4391 }
4392 // Implicity convert these scalars to the type of the condition.
John Wiegley429bb272011-04-08 18:41:53 +00004393 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4394 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begeman6155d732010-09-20 22:41:17 +00004395 }
4396
Chris Lattner70d67a92008-01-06 22:42:25 +00004397 // If both operands have arithmetic type, do the usual arithmetic conversions
4398 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004399 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4400 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004401 if (LHS.isInvalid() || RHS.isInvalid())
4402 return QualType();
4403 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004404 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004405
Chris Lattner70d67a92008-01-06 22:42:25 +00004406 // If both operands are the same structure or union type, the result is that
4407 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004408 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4409 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004410 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004411 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004412 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004413 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004414 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004415 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004416
Chris Lattner70d67a92008-01-06 22:42:25 +00004417 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004418 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004419 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4420 if (!LHSTy->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +00004421 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4422 << RHS.get()->getSourceRange();
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004423 if (!RHSTy->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +00004424 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4425 << LHS.get()->getSourceRange();
4426 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
4427 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00004428 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00004429 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00004430 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4431 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004432 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
John Wiegley429bb272011-04-08 18:41:53 +00004433 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004434 // promote the null to a pointer.
John Wiegley429bb272011-04-08 18:41:53 +00004435 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004436 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004437 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004438 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
John Wiegley429bb272011-04-08 18:41:53 +00004439 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4440 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004441 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004442 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004443
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004444 // All objective-c pointer type analysis is done here.
4445 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4446 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00004447 if (LHS.isInvalid() || RHS.isInvalid())
4448 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004449 if (!compositeType.isNull())
4450 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004451
4452
Steve Naroff7154a772009-07-01 14:36:47 +00004453 // Handle block pointer types.
4454 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4455 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4456 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4457 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00004458 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4459 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004460 return destType;
4461 }
4462 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00004463 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00004464 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004465 }
Steve Naroff7154a772009-07-01 14:36:47 +00004466 // We have 2 block pointer types.
4467 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4468 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004469 return LHSTy;
4470 }
Steve Naroff7154a772009-07-01 14:36:47 +00004471 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00004472 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4473 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004474
Steve Naroff7154a772009-07-01 14:36:47 +00004475 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4476 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00004477 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00004478 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004479 // In this situation, we assume void* type. No especially good
4480 // reason, but this is what gcc does, and we do have to pick
4481 // to get a consistent AST.
4482 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00004483 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4484 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00004485 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004486 }
Steve Naroff7154a772009-07-01 14:36:47 +00004487 // The block pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00004488 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4489 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00004490 return LHSTy;
4491 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004492
Steve Naroff7154a772009-07-01 14:36:47 +00004493 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4494 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4495 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00004496 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4497 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00004498
4499 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4500 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4501 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00004502 QualType destPointee
4503 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004504 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004505 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004506 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004507 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004508 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004509 return destType;
4510 }
4511 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00004512 QualType destPointee
4513 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004514 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004515 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004516 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004517 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004518 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004519 return destType;
4520 }
4521
4522 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4523 // Two identical pointer types are always compatible.
4524 return LHSTy;
4525 }
4526 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4527 rhptee.getUnqualifiedType())) {
4528 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00004529 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00004530 // In this situation, we assume void* type. No especially good
4531 // reason, but this is what gcc does, and we do have to pick
4532 // to get a consistent AST.
4533 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00004534 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4535 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004536 return incompatTy;
4537 }
4538 // The pointer types are compatible.
4539 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4540 // differently qualified versions of compatible types, the result type is
4541 // a pointer to an appropriately qualified version of the *composite*
4542 // type.
4543 // FIXME: Need to calculate the composite type.
4544 // FIXME: Need to add qualifiers
John Wiegley429bb272011-04-08 18:41:53 +00004545 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4546 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004547 return LHSTy;
4548 }
Mike Stump1eb44332009-09-09 15:08:12 +00004549
John McCall404cd162010-11-13 01:35:44 +00004550 // GCC compatibility: soften pointer/integer mismatch. Note that
4551 // null pointers have been filtered out by this point.
Steve Naroff7154a772009-07-01 14:36:47 +00004552 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4553 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley429bb272011-04-08 18:41:53 +00004554 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4555 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004556 return RHSTy;
4557 }
4558 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4559 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley429bb272011-04-08 18:41:53 +00004560 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4561 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004562 return LHSTy;
4563 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004564
Chandler Carruth82214a82011-02-18 23:54:50 +00004565 // Emit a better diagnostic if one of the expressions is a null pointer
4566 // constant and the other is not a pointer type. In this case, the user most
4567 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00004568 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00004569 return QualType();
4570
Chris Lattner70d67a92008-01-06 22:42:25 +00004571 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004572 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00004573 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004574 return QualType();
4575}
4576
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004577/// FindCompositeObjCPointerType - Helper method to find composite type of
4578/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00004579QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004580 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00004581 QualType LHSTy = LHS.get()->getType();
4582 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004583
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004584 // Handle things like Class and struct objc_class*. Here we case the result
4585 // to the pseudo-builtin, because that will be implicitly cast back to the
4586 // redefinition type if an attempt is made to access its fields.
4587 if (LHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00004588 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00004589 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004590 return LHSTy;
4591 }
4592 if (RHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00004593 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00004594 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004595 return RHSTy;
4596 }
4597 // And the same for struct objc_object* / id
4598 if (LHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00004599 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00004600 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004601 return LHSTy;
4602 }
4603 if (RHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00004604 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00004605 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004606 return RHSTy;
4607 }
4608 // And the same for struct objc_selector* / SEL
4609 if (Context.isObjCSelType(LHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00004610 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00004611 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004612 return LHSTy;
4613 }
4614 if (Context.isObjCSelType(RHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00004615 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00004616 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004617 return RHSTy;
4618 }
4619 // Check constraints for Objective-C object pointers types.
4620 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004621
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004622 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4623 // Two identical object pointer types are always compatible.
4624 return LHSTy;
4625 }
4626 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4627 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4628 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004629
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004630 // If both operands are interfaces and either operand can be
4631 // assigned to the other, use that type as the composite
4632 // type. This allows
4633 // xxx ? (A*) a : (B*) b
4634 // where B is a subclass of A.
4635 //
4636 // Additionally, as for assignment, if either type is 'id'
4637 // allow silent coercion. Finally, if the types are
4638 // incompatible then make sure to use 'id' as the composite
4639 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004640
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004641 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4642 // It could return the composite type.
4643 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4644 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4645 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4646 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4647 } else if ((LHSTy->isObjCQualifiedIdType() ||
4648 RHSTy->isObjCQualifiedIdType()) &&
4649 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4650 // Need to handle "id<xx>" explicitly.
4651 // GCC allows qualified id and any Objective-C type to devolve to
4652 // id. Currently localizing to here until clear this should be
4653 // part of ObjCQualifiedIdTypesAreCompatible.
4654 compositeType = Context.getObjCIdType();
4655 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4656 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004657 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004658 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4659 ;
4660 else {
4661 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4662 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00004663 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004664 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00004665 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4666 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004667 return incompatTy;
4668 }
4669 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00004670 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4671 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004672 return compositeType;
4673 }
4674 // Check Objective-C object pointer types and 'void *'
4675 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4676 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4677 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4678 QualType destPointee
4679 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4680 QualType destType = Context.getPointerType(destPointee);
4681 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004682 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004683 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004684 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004685 return destType;
4686 }
4687 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4688 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4689 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4690 QualType destPointee
4691 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4692 QualType destType = Context.getPointerType(destPointee);
4693 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004694 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004695 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004696 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004697 return destType;
4698 }
4699 return QualType();
4700}
4701
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004702/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004703/// ParenRange in parentheses.
4704static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004705 const PartialDiagnostic &Note,
4706 SourceRange ParenRange) {
4707 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4708 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4709 EndLoc.isValid()) {
4710 Self.Diag(Loc, Note)
4711 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4712 << FixItHint::CreateInsertion(EndLoc, ")");
4713 } else {
4714 // We can't display the parentheses, so just show the bare note.
4715 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004716 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004717}
4718
4719static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4720 return Opc >= BO_Mul && Opc <= BO_Shr;
4721}
4722
Hans Wennborg2f072b42011-06-09 17:06:51 +00004723/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4724/// expression, either using a built-in or overloaded operator,
4725/// and sets *OpCode to the opcode and *RHS to the right-hand side expression.
4726static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
4727 Expr **RHS) {
4728 E = E->IgnoreParenImpCasts();
4729 E = E->IgnoreConversionOperator();
4730 E = E->IgnoreParenImpCasts();
4731
4732 // Built-in binary operator.
4733 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4734 if (IsArithmeticOp(OP->getOpcode())) {
4735 *Opcode = OP->getOpcode();
4736 *RHS = OP->getRHS();
4737 return true;
4738 }
4739 }
4740
4741 // Overloaded operator.
4742 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4743 if (Call->getNumArgs() != 2)
4744 return false;
4745
4746 // Make sure this is really a binary operator that is safe to pass into
4747 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4748 OverloadedOperatorKind OO = Call->getOperator();
4749 if (OO < OO_Plus || OO > OO_Arrow)
4750 return false;
4751
4752 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4753 if (IsArithmeticOp(OpKind)) {
4754 *Opcode = OpKind;
4755 *RHS = Call->getArg(1);
4756 return true;
4757 }
4758 }
4759
4760 return false;
4761}
4762
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004763static bool IsLogicOp(BinaryOperatorKind Opc) {
4764 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4765}
4766
Hans Wennborg2f072b42011-06-09 17:06:51 +00004767/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4768/// or is a logical expression such as (x==y) which has int type, but is
4769/// commonly interpreted as boolean.
4770static bool ExprLooksBoolean(Expr *E) {
4771 E = E->IgnoreParenImpCasts();
4772
4773 if (E->getType()->isBooleanType())
4774 return true;
4775 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4776 return IsLogicOp(OP->getOpcode());
4777 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4778 return OP->getOpcode() == UO_LNot;
4779
4780 return false;
4781}
4782
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004783/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4784/// and binary operator are mixed in a way that suggests the programmer assumed
4785/// the conditional operator has higher precedence, for example:
4786/// "int x = a + someBinaryCondition ? 1 : 2".
4787static void DiagnoseConditionalPrecedence(Sema &Self,
4788 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00004789 Expr *Condition,
4790 Expr *LHS,
4791 Expr *RHS) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00004792 BinaryOperatorKind CondOpcode;
4793 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004794
Chandler Carruth43bc78d2011-06-16 01:05:08 +00004795 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00004796 return;
4797 if (!ExprLooksBoolean(CondRHS))
4798 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004799
Hans Wennborg2f072b42011-06-09 17:06:51 +00004800 // The condition is an arithmetic binary expression, with a right-
4801 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004802
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004803 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00004804 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00004805 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004806
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004807 SuggestParentheses(Self, OpLoc,
4808 Self.PDiag(diag::note_precedence_conditional_silence)
4809 << BinaryOperator::getOpcodeStr(CondOpcode),
4810 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00004811
4812 SuggestParentheses(Self, OpLoc,
4813 Self.PDiag(diag::note_precedence_conditional_first),
4814 SourceRange(CondRHS->getLocStart(), RHS->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004815}
4816
Steve Narofff69936d2007-09-16 03:34:24 +00004817/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00004818/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00004819ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00004820 SourceLocation ColonLoc,
4821 Expr *CondExpr, Expr *LHSExpr,
4822 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00004823 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4824 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00004825 OpaqueValueExpr *opaqueValue = 0;
4826 Expr *commonExpr = 0;
4827 if (LHSExpr == 0) {
4828 commonExpr = CondExpr;
4829
4830 // We usually want to apply unary conversions *before* saving, except
4831 // in the special case of a C++ l-value conditional.
4832 if (!(getLangOptions().CPlusPlus
4833 && !commonExpr->isTypeDependent()
4834 && commonExpr->getValueKind() == RHSExpr->getValueKind()
4835 && commonExpr->isGLValue()
4836 && commonExpr->isOrdinaryOrBitFieldObject()
4837 && RHSExpr->isOrdinaryOrBitFieldObject()
4838 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004839 ExprResult commonRes = UsualUnaryConversions(commonExpr);
4840 if (commonRes.isInvalid())
4841 return ExprError();
4842 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00004843 }
4844
4845 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
4846 commonExpr->getType(),
4847 commonExpr->getValueKind(),
4848 commonExpr->getObjectKind());
4849 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004850 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004851
John McCallf89e55a2010-11-18 06:31:45 +00004852 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004853 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00004854 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
4855 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00004856 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00004857 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
4858 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004859 return ExprError();
4860
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004861 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
4862 RHS.get());
4863
John McCall56ca35d2011-02-17 10:25:35 +00004864 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00004865 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
4866 LHS.take(), ColonLoc,
4867 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00004868
4869 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00004870 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
4871 RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00004872}
4873
John McCalle4be87e2011-01-31 23:13:11 +00004874// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00004875// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00004876// routine is it effectively iqnores the qualifiers on the top level pointee.
4877// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4878// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00004879static Sema::AssignConvertType
4880checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
4881 assert(lhsType.isCanonical() && "LHS not canonicalized!");
4882 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004883
Reid Spencer5f016e22007-07-11 17:01:13 +00004884 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00004885 const Type *lhptee, *rhptee;
4886 Qualifiers lhq, rhq;
4887 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
4888 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004889
John McCalle4be87e2011-01-31 23:13:11 +00004890 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004891
4892 // C99 6.5.16.1p1: This following citation is common to constraints
4893 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4894 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00004895 Qualifiers lq;
4896
John McCallf85e1932011-06-15 23:02:42 +00004897 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
4898 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
4899 lhq.compatiblyIncludesObjCLifetime(rhq)) {
4900 // Ignore lifetime for further calculation.
4901 lhq.removeObjCLifetime();
4902 rhq.removeObjCLifetime();
4903 }
4904
John McCall86c05f32011-02-01 00:10:29 +00004905 if (!lhq.compatiblyIncludes(rhq)) {
4906 // Treat address-space mismatches as fatal. TODO: address subspaces
4907 if (lhq.getAddressSpace() != rhq.getAddressSpace())
4908 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
4909
John McCallf85e1932011-06-15 23:02:42 +00004910 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00004911 // and from void*.
John McCallf85e1932011-06-15 23:02:42 +00004912 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
4913 .compatiblyIncludes(
4914 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall22348732011-03-26 02:56:45 +00004915 && (lhptee->isVoidType() || rhptee->isVoidType()))
4916 ; // keep old
4917
John McCallf85e1932011-06-15 23:02:42 +00004918 // Treat lifetime mismatches as fatal.
4919 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
4920 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
4921
John McCall86c05f32011-02-01 00:10:29 +00004922 // For GCC compatibility, other qualifier mismatches are treated
4923 // as still compatible in C.
4924 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
4925 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004926
Mike Stumpeed9cac2009-02-19 03:04:26 +00004927 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4928 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00004929 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004930 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004931 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004932 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004933
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004934 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004935 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00004936 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004937 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004938
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004939 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004940 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004941 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004942
4943 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004944 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00004945 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004946 }
John McCall86c05f32011-02-01 00:10:29 +00004947
Mike Stumpeed9cac2009-02-19 03:04:26 +00004948 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00004949 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00004950 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
4951 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004952 // Check if the pointee types are compatible ignoring the sign.
4953 // We explicitly check for char so that we catch "char" vs
4954 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00004955 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00004956 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00004957 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00004958 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004959
Chris Lattner6a2b9262009-10-17 20:33:28 +00004960 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00004961 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00004962 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00004963 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004964
John McCall86c05f32011-02-01 00:10:29 +00004965 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004966 // Types are compatible ignoring the sign. Qualifier incompatibility
4967 // takes priority over sign incompatibility because the sign
4968 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00004969 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004970 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00004971
John McCalle4be87e2011-01-31 23:13:11 +00004972 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004973 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004974
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004975 // If we are a multi-level pointer, it's possible that our issue is simply
4976 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4977 // the eventual target type is the same and the pointers have the same
4978 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00004979 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004980 do {
John McCall86c05f32011-02-01 00:10:29 +00004981 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
4982 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00004983 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004984
John McCall86c05f32011-02-01 00:10:29 +00004985 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00004986 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004987 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004988
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004989 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00004990 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004991 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00004992 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004993}
4994
John McCalle4be87e2011-01-31 23:13:11 +00004995/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00004996/// block pointer types are compatible or whether a block and normal pointer
4997/// are compatible. It is more restrict than comparing two function pointer
4998// types.
John McCalle4be87e2011-01-31 23:13:11 +00004999static Sema::AssignConvertType
5000checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5001 QualType rhsType) {
5002 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5003 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5004
Steve Naroff1c7d0672008-09-04 15:10:53 +00005005 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005006
Steve Naroff1c7d0672008-09-04 15:10:53 +00005007 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCalle4be87e2011-01-31 23:13:11 +00005008 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5009 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005010
John McCalle4be87e2011-01-31 23:13:11 +00005011 // In C++, the types have to match exactly.
5012 if (S.getLangOptions().CPlusPlus)
5013 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005014
John McCalle4be87e2011-01-31 23:13:11 +00005015 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005016
Steve Naroff1c7d0672008-09-04 15:10:53 +00005017 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005018 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5019 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005020
John McCalle4be87e2011-01-31 23:13:11 +00005021 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5022 return Sema::IncompatibleBlockPointer;
5023
Steve Naroff1c7d0672008-09-04 15:10:53 +00005024 return ConvTy;
5025}
5026
John McCalle4be87e2011-01-31 23:13:11 +00005027/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005028/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005029static Sema::AssignConvertType
5030checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5031 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5032 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5033
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005034 if (lhsType->isObjCBuiltinType()) {
5035 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005036 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5037 !rhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005038 return Sema::IncompatiblePointer;
5039 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005040 }
5041 if (rhsType->isObjCBuiltinType()) {
5042 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005043 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5044 !lhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005045 return Sema::IncompatiblePointer;
5046 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005047 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005048 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005049 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005050 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005051 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005052
John McCalle4be87e2011-01-31 23:13:11 +00005053 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5054 return Sema::CompatiblePointerDiscardsQualifiers;
5055
5056 if (S.Context.typesAreCompatible(lhsType, rhsType))
5057 return Sema::Compatible;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005058 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005059 return Sema::IncompatibleObjCQualifiedId;
5060 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005061}
5062
John McCall1c23e912010-11-16 02:32:08 +00005063Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005064Sema::CheckAssignmentConstraints(SourceLocation Loc,
5065 QualType lhsType, QualType rhsType) {
John McCall1c23e912010-11-16 02:32:08 +00005066 // Fake up an opaque expression. We don't actually care about what
5067 // cast operations are required, so if CheckAssignmentConstraints
5068 // adds casts to this they'll be wasted, but fortunately that doesn't
5069 // usually happen on valid code.
Douglas Gregorb608b982011-01-28 02:26:04 +00005070 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00005071 ExprResult rhsPtr = &rhs;
John McCall1c23e912010-11-16 02:32:08 +00005072 CastKind K = CK_Invalid;
5073
5074 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5075}
5076
Mike Stumpeed9cac2009-02-19 03:04:26 +00005077/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5078/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005079/// pointers. Here are some objectionable examples that GCC considers warnings:
5080///
5081/// int a, *pint;
5082/// short *pshort;
5083/// struct foo *pfoo;
5084///
5085/// pint = pshort; // warning: assignment from incompatible pointer type
5086/// a = pint; // warning: assignment makes integer from pointer without a cast
5087/// pint = a; // warning: assignment makes pointer from integer without a cast
5088/// pint = pfoo; // warning: assignment from incompatible pointer type
5089///
5090/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005091/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005092///
John McCalldaa8e4e2010-11-15 09:13:47 +00005093/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005094Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00005095Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCalldaa8e4e2010-11-15 09:13:47 +00005096 CastKind &Kind) {
John Wiegley429bb272011-04-08 18:41:53 +00005097 QualType rhsType = rhs.get()->getType();
John McCall1c23e912010-11-16 02:32:08 +00005098
Chris Lattnerfc144e22008-01-04 23:18:45 +00005099 // Get canonical types. We're not formatting these types, just comparing
5100 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00005101 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5102 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005103
John McCallb6cfa242011-01-31 22:28:28 +00005104 // Common case: no conversion required.
John McCalldaa8e4e2010-11-15 09:13:47 +00005105 if (lhsType == rhsType) {
5106 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005107 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005108 }
5109
Douglas Gregor9d293df2008-10-28 00:22:11 +00005110 // If the left-hand side is a reference type, then we are in a
5111 // (rare!) case where we've allowed the use of references in C,
5112 // e.g., as a parameter type in a built-in function. In this case,
5113 // just make sure that the type referenced is compatible with the
5114 // right-hand side type. The caller is responsible for adjusting
5115 // lhsType so that the resulting expression does not have reference
5116 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005117 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005118 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5119 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005120 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005121 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005122 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005123 }
John McCallb6cfa242011-01-31 22:28:28 +00005124
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005125 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5126 // to the same ExtVector type.
5127 if (lhsType->isExtVectorType()) {
5128 if (rhsType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005129 return Incompatible;
5130 if (rhsType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005131 // CK_VectorSplat does T -> vector T, so first cast to the
5132 // element type.
5133 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5134 if (elType != rhsType) {
5135 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley429bb272011-04-08 18:41:53 +00005136 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005137 }
5138 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005139 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005140 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005141 }
Mike Stump1eb44332009-09-09 15:08:12 +00005142
John McCallb6cfa242011-01-31 22:28:28 +00005143 // Conversions to or from vector type.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005144 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor255210e2010-08-06 10:14:59 +00005145 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005146 // Allow assignments of an AltiVec vector type to an equivalent GCC
5147 // vector type and vice versa
5148 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5149 Kind = CK_BitCast;
5150 return Compatible;
5151 }
5152
Douglas Gregor255210e2010-08-06 10:14:59 +00005153 // If we are allowing lax vector conversions, and LHS and RHS are both
5154 // vectors, the total size only needs to be the same. This is a bitcast;
5155 // no bits are changed but the result type is different.
5156 if (getLangOptions().LaxVectorConversions &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005157 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005158 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005159 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005160 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005161 }
5162 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005163 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005164
John McCallb6cfa242011-01-31 22:28:28 +00005165 // Arithmetic conversions.
Douglas Gregor88623ad2010-05-23 21:53:47 +00005166 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005167 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall1c23e912010-11-16 02:32:08 +00005168 Kind = PrepareScalarCast(*this, rhs, lhsType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005169 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005170 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005171
John McCallb6cfa242011-01-31 22:28:28 +00005172 // Conversions to normal pointers.
5173 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5174 // U* -> T*
John McCalldaa8e4e2010-11-15 09:13:47 +00005175 if (isa<PointerType>(rhsType)) {
5176 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00005177 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005178 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005179
John McCallb6cfa242011-01-31 22:28:28 +00005180 // int -> T*
5181 if (rhsType->isIntegerType()) {
5182 Kind = CK_IntegralToPointer; // FIXME: null?
5183 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005184 }
John McCallb6cfa242011-01-31 22:28:28 +00005185
5186 // C pointers are not compatible with ObjC object pointers,
5187 // with two exceptions:
5188 if (isa<ObjCObjectPointerType>(rhsType)) {
5189 // - conversions to void*
5190 if (lhsPointer->getPointeeType()->isVoidType()) {
5191 Kind = CK_AnyPointerToObjCPointerCast;
5192 return Compatible;
5193 }
5194
5195 // - conversions from 'Class' to the redefinition type
5196 if (rhsType->isObjCClassType() &&
5197 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005198 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005199 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005200 }
Steve Naroffb4406862008-09-29 18:10:17 +00005201
John McCallb6cfa242011-01-31 22:28:28 +00005202 Kind = CK_BitCast;
5203 return IncompatiblePointer;
5204 }
5205
5206 // U^ -> void*
5207 if (rhsType->getAs<BlockPointerType>()) {
5208 if (lhsPointer->getPointeeType()->isVoidType()) {
5209 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005210 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005211 }
Steve Naroffb4406862008-09-29 18:10:17 +00005212 }
John McCallb6cfa242011-01-31 22:28:28 +00005213
Steve Naroff1c7d0672008-09-04 15:10:53 +00005214 return Incompatible;
5215 }
5216
John McCallb6cfa242011-01-31 22:28:28 +00005217 // Conversions to block pointers.
Steve Naroff1c7d0672008-09-04 15:10:53 +00005218 if (isa<BlockPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005219 // U^ -> T^
5220 if (rhsType->isBlockPointerType()) {
5221 Kind = CK_AnyPointerToBlockPointerCast;
John McCalle4be87e2011-01-31 23:13:11 +00005222 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00005223 }
5224
5225 // int or null -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00005226 if (rhsType->isIntegerType()) {
5227 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005228 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005229 }
5230
John McCallb6cfa242011-01-31 22:28:28 +00005231 // id -> T^
5232 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5233 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005234 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005235 }
Steve Naroffb4406862008-09-29 18:10:17 +00005236
John McCallb6cfa242011-01-31 22:28:28 +00005237 // void* -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00005238 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005239 if (RHSPT->getPointeeType()->isVoidType()) {
5240 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005241 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005242 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005243
Chris Lattnerfc144e22008-01-04 23:18:45 +00005244 return Incompatible;
5245 }
5246
John McCallb6cfa242011-01-31 22:28:28 +00005247 // Conversions to Objective-C pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00005248 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005249 // A* -> B*
5250 if (rhsType->isObjCObjectPointerType()) {
5251 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00005252 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00005253 }
5254
5255 // int or null -> A*
John McCalldaa8e4e2010-11-15 09:13:47 +00005256 if (rhsType->isIntegerType()) {
5257 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005258 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005259 }
5260
John McCallb6cfa242011-01-31 22:28:28 +00005261 // In general, C pointers are not compatible with ObjC object pointers,
5262 // with two exceptions:
Steve Naroff14108da2009-07-10 23:34:53 +00005263 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005264 // - conversions from 'void*'
5265 if (rhsType->isVoidPointerType()) {
5266 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005267 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005268 }
5269
5270 // - conversions to 'Class' from its redefinition type
5271 if (lhsType->isObjCClassType() &&
5272 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
5273 Kind = CK_BitCast;
5274 return Compatible;
5275 }
5276
5277 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005278 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005279 }
John McCallb6cfa242011-01-31 22:28:28 +00005280
5281 // T^ -> A*
5282 if (rhsType->isBlockPointerType()) {
5283 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005284 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005285 }
5286
Steve Naroff14108da2009-07-10 23:34:53 +00005287 return Incompatible;
5288 }
John McCallb6cfa242011-01-31 22:28:28 +00005289
5290 // Conversions from pointers that are not covered by the above.
Chris Lattner78eca282008-04-07 06:49:41 +00005291 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005292 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00005293 if (lhsType == Context.BoolTy) {
5294 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005295 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005296 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005297
John McCallb6cfa242011-01-31 22:28:28 +00005298 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00005299 if (lhsType->isIntegerType()) {
5300 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005301 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005302 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005303
Chris Lattnerfc144e22008-01-04 23:18:45 +00005304 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005305 }
John McCallb6cfa242011-01-31 22:28:28 +00005306
5307 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff14108da2009-07-10 23:34:53 +00005308 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005309 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00005310 if (lhsType == Context.BoolTy) {
5311 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005312 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005313 }
Steve Naroff14108da2009-07-10 23:34:53 +00005314
John McCallb6cfa242011-01-31 22:28:28 +00005315 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00005316 if (lhsType->isIntegerType()) {
5317 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005318 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005319 }
5320
Steve Naroff14108da2009-07-10 23:34:53 +00005321 return Incompatible;
5322 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005323
John McCallb6cfa242011-01-31 22:28:28 +00005324 // struct A -> struct B
Chris Lattnerfc144e22008-01-04 23:18:45 +00005325 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005326 if (Context.typesAreCompatible(lhsType, rhsType)) {
5327 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005328 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005329 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005330 }
John McCallb6cfa242011-01-31 22:28:28 +00005331
Reid Spencer5f016e22007-07-11 17:01:13 +00005332 return Incompatible;
5333}
5334
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005335/// \brief Constructs a transparent union from an expression that is
5336/// used to initialize the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005337static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005338 QualType UnionType, FieldDecl *Field) {
5339 // Build an initializer list that designates the appropriate member
5340 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005341 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005342 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00005343 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005344 SourceLocation());
5345 Initializer->setType(UnionType);
5346 Initializer->setInitializedFieldInUnion(Field);
5347
5348 // Build a compound literal constructing a value of the transparent
5349 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005350 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005351 EResult = S.Owned(
5352 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5353 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005354}
5355
5356Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00005357Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
5358 QualType FromType = rExpr.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005359
Mike Stump1eb44332009-09-09 15:08:12 +00005360 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005361 // transparent_union GCC extension.
5362 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005363 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005364 return Incompatible;
5365
5366 // The field to initialize within the transparent union.
5367 RecordDecl *UD = UT->getDecl();
5368 FieldDecl *InitField = 0;
5369 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005370 for (RecordDecl::field_iterator it = UD->field_begin(),
5371 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005372 it != itend; ++it) {
5373 if (it->getType()->isPointerType()) {
5374 // If the transparent union contains a pointer type, we allow:
5375 // 1) void pointer
5376 // 2) null pointer constant
5377 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00005378 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005379 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005380 InitField = *it;
5381 break;
5382 }
Mike Stump1eb44332009-09-09 15:08:12 +00005383
John Wiegley429bb272011-04-08 18:41:53 +00005384 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005385 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00005386 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005387 InitField = *it;
5388 break;
5389 }
5390 }
5391
John McCalldaa8e4e2010-11-15 09:13:47 +00005392 CastKind Kind = CK_Invalid;
John Wiegley429bb272011-04-08 18:41:53 +00005393 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005394 == Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +00005395 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005396 InitField = *it;
5397 break;
5398 }
5399 }
5400
5401 if (!InitField)
5402 return Incompatible;
5403
John Wiegley429bb272011-04-08 18:41:53 +00005404 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005405 return Compatible;
5406}
5407
Chris Lattner5cf216b2008-01-04 18:04:52 +00005408Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00005409Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005410 if (getLangOptions().CPlusPlus) {
5411 if (!lhsType->isRecordType()) {
5412 // C++ 5.17p3: If the left operand is not of class type, the
5413 // expression is implicitly converted (C++ 4) to the
5414 // cv-unqualified type of the left operand.
John Wiegley429bb272011-04-08 18:41:53 +00005415 ExprResult Res = PerformImplicitConversion(rExpr.get(),
5416 lhsType.getUnqualifiedType(),
5417 AA_Assigning);
5418 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00005419 return Incompatible;
John Wiegley429bb272011-04-08 18:41:53 +00005420 rExpr = move(Res);
Chris Lattner2c4463f2009-04-12 09:02:39 +00005421 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005422 }
5423
5424 // FIXME: Currently, we fall through and treat C++ classes like C
5425 // structures.
John McCallf6a16482010-12-04 03:47:34 +00005426 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00005427
Steve Naroff529a4ad2007-11-27 17:58:44 +00005428 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5429 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00005430 if ((lhsType->isPointerType() ||
5431 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00005432 lhsType->isBlockPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00005433 && rExpr.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005434 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00005435 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00005436 return Compatible;
5437 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005438
Chris Lattner943140e2007-10-16 02:55:40 +00005439 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00005440 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00005441 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00005442 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00005443 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00005444 // Suppress this for references: C++ 8.5.3p5.
John Wiegley429bb272011-04-08 18:41:53 +00005445 if (!lhsType->isReferenceType()) {
5446 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
5447 if (rExpr.isInvalid())
5448 return Incompatible;
5449 }
Steve Narofff1120de2007-08-24 22:33:52 +00005450
John McCalldaa8e4e2010-11-15 09:13:47 +00005451 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005452 Sema::AssignConvertType result =
John McCall1c23e912010-11-16 02:32:08 +00005453 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005454
Steve Narofff1120de2007-08-24 22:33:52 +00005455 // C99 6.5.16.1p2: The value of the right operand is converted to the
5456 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00005457 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5458 // so that we can use references in built-in functions even in C.
5459 // The getNonReferenceType() call makes sure that the resulting expression
5460 // does not have reference type.
John Wiegley429bb272011-04-08 18:41:53 +00005461 if (result != Incompatible && rExpr.get()->getType() != lhsType)
5462 rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00005463 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00005464}
5465
John Wiegley429bb272011-04-08 18:41:53 +00005466QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005467 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley429bb272011-04-08 18:41:53 +00005468 << lex.get()->getType() << rex.get()->getType()
5469 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00005470 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005471}
5472
John Wiegley429bb272011-04-08 18:41:53 +00005473QualType Sema::CheckVectorOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00005474 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005475 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00005476 QualType lhsType =
John Wiegley429bb272011-04-08 18:41:53 +00005477 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattnerb77792e2008-07-26 22:17:49 +00005478 QualType rhsType =
John Wiegley429bb272011-04-08 18:41:53 +00005479 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005480
Nate Begemanbe2341d2008-07-14 18:02:46 +00005481 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005482 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00005483 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00005484
Nate Begemanbe2341d2008-07-14 18:02:46 +00005485 // Handle the case of a vector & extvector type of the same size and element
5486 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005487 if (getLangOptions().LaxVectorConversions) {
John McCall183700f2009-09-21 23:43:11 +00005488 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth629f9e42010-08-30 07:36:24 +00005489 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00005490 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005491 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregor26bcf672010-05-19 03:21:00 +00005492 if (lhsType->isExtVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005493 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00005494 return lhsType;
5495 }
5496
John Wiegley429bb272011-04-08 18:41:53 +00005497 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor26bcf672010-05-19 03:21:00 +00005498 return rhsType;
Eric Christophere84f9eb2010-08-26 00:42:16 +00005499 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
5500 // If we are allowing lax vector conversions, and LHS and RHS are both
5501 // vectors, the total size only needs to be the same. This is a
5502 // bitcast; no bits are changed but the result type is different.
John Wiegley429bb272011-04-08 18:41:53 +00005503 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Eric Christophere84f9eb2010-08-26 00:42:16 +00005504 return lhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005505 }
Eric Christophere84f9eb2010-08-26 00:42:16 +00005506 }
Chandler Carruth629f9e42010-08-30 07:36:24 +00005507 }
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005508 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005509
Douglas Gregor255210e2010-08-06 10:14:59 +00005510 // Handle the case of equivalent AltiVec and GCC vector types
5511 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5512 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John Wiegley429bb272011-04-08 18:41:53 +00005513 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor255210e2010-08-06 10:14:59 +00005514 return rhsType;
5515 }
5516
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005517 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5518 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5519 bool swapped = false;
5520 if (rhsType->isExtVectorType()) {
5521 swapped = true;
5522 std::swap(rex, lex);
5523 std::swap(rhsType, lhsType);
5524 }
Mike Stump1eb44332009-09-09 15:08:12 +00005525
Nate Begemandde25982009-06-28 19:12:57 +00005526 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00005527 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005528 QualType EltTy = LV->getElementType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00005529 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005530 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5531 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00005532 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005533 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00005534 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005535 if (swapped) std::swap(rex, lex);
5536 return lhsType;
5537 }
5538 }
5539 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5540 rhsType->isRealFloatingType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005541 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5542 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00005543 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005544 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00005545 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005546 if (swapped) std::swap(rex, lex);
5547 return lhsType;
5548 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00005549 }
5550 }
Mike Stump1eb44332009-09-09 15:08:12 +00005551
Nate Begemandde25982009-06-28 19:12:57 +00005552 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005553 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley429bb272011-04-08 18:41:53 +00005554 << lex.get()->getType() << rex.get()->getType()
5555 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005556 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00005557}
5558
Chris Lattner7ef655a2010-01-12 21:23:57 +00005559QualType Sema::CheckMultiplyDivideOperands(
John Wiegley429bb272011-04-08 18:41:53 +00005560 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
5561 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005562 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005563
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005564 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00005565 if (lex.isInvalid() || rex.isInvalid())
5566 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005567
John Wiegley429bb272011-04-08 18:41:53 +00005568 if (!lex.get()->getType()->isArithmeticType() ||
5569 !rex.get()->getType()->isArithmeticType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00005570 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005571
Chris Lattner7ef655a2010-01-12 21:23:57 +00005572 // Check for division by zero.
5573 if (isDiv &&
John Wiegley429bb272011-04-08 18:41:53 +00005574 rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
5575 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
5576 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005577
Chris Lattner7ef655a2010-01-12 21:23:57 +00005578 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005579}
5580
Chris Lattner7ef655a2010-01-12 21:23:57 +00005581QualType Sema::CheckRemainderOperands(
John Wiegley429bb272011-04-08 18:41:53 +00005582 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
5583 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
5584 if (lex.get()->getType()->hasIntegerRepresentation() &&
5585 rex.get()->getType()->hasIntegerRepresentation())
Daniel Dunbar523aa602009-01-05 22:55:36 +00005586 return CheckVectorOperands(Loc, lex, rex);
5587 return InvalidOperands(Loc, lex, rex);
5588 }
Steve Naroff90045e82007-07-13 23:32:42 +00005589
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005590 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00005591 if (lex.isInvalid() || rex.isInvalid())
5592 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005593
John Wiegley429bb272011-04-08 18:41:53 +00005594 if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00005595 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005596
Chris Lattner7ef655a2010-01-12 21:23:57 +00005597 // Check for remainder by zero.
John Wiegley429bb272011-04-08 18:41:53 +00005598 if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
5599 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
5600 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005601
Chris Lattner7ef655a2010-01-12 21:23:57 +00005602 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005603}
5604
Chris Lattner7ef655a2010-01-12 21:23:57 +00005605QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00005606 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
5607 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005608 QualType compType = CheckVectorOperands(Loc, lex, rex);
5609 if (CompLHSTy) *CompLHSTy = compType;
5610 return compType;
5611 }
Steve Naroff49b45262007-07-13 16:58:59 +00005612
Eli Friedmanab3a8522009-03-28 01:22:36 +00005613 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00005614 if (lex.isInvalid() || rex.isInvalid())
5615 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00005616
Reid Spencer5f016e22007-07-11 17:01:13 +00005617 // handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00005618 if (lex.get()->getType()->isArithmeticType() &&
5619 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005620 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005621 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005622 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005623
Eli Friedmand72d16e2008-05-18 18:08:51 +00005624 // Put any potential pointer into PExp
John Wiegley429bb272011-04-08 18:41:53 +00005625 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005626 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00005627 std::swap(PExp, IExp);
5628
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005629 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005630
Eli Friedmand72d16e2008-05-18 18:08:51 +00005631 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00005632 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005633
Chris Lattnerb5f15622009-04-24 23:50:08 +00005634 // Check for arithmetic on pointers to incomplete types.
5635 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00005636 if (getLangOptions().CPlusPlus) {
5637 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley429bb272011-04-08 18:41:53 +00005638 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005639 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00005640 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005641
5642 // GNU extension: arithmetic on pointer to void
5643 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley429bb272011-04-08 18:41:53 +00005644 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00005645 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00005646 if (getLangOptions().CPlusPlus) {
5647 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chandler Carruthae0bafa2011-06-20 07:52:11 +00005648 << PExp->getType() << PExp->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00005649 return QualType();
5650 }
5651
5652 // GNU extension: arithmetic on pointer to function
5653 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chandler Carruthae0bafa2011-06-20 07:52:11 +00005654 << PExp->getType() << PExp->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00005655 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00005656 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00005657 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00005658 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00005659 PExp->getType()->isObjCObjectPointerType()) &&
5660 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00005661 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5662 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005663 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00005664 return QualType();
5665 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00005666 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00005667 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00005668 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5669 << PointeeTy << PExp->getSourceRange();
5670 return QualType();
5671 }
Mike Stump1eb44332009-09-09 15:08:12 +00005672
Eli Friedmanab3a8522009-03-28 01:22:36 +00005673 if (CompLHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00005674 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman04e83572009-08-20 04:21:42 +00005675 if (LHSTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +00005676 LHSTy = lex.get()->getType();
Eli Friedman04e83572009-08-20 04:21:42 +00005677 if (LHSTy->isPromotableIntegerType())
5678 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005679 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00005680 *CompLHSTy = LHSTy;
5681 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00005682 return PExp->getType();
5683 }
5684 }
5685
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005686 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005687}
5688
Chris Lattnereca7be62008-04-07 05:30:13 +00005689// C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00005690QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00005691 SourceLocation Loc, QualType* CompLHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00005692 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005693 QualType compType = CheckVectorOperands(Loc, lex, rex);
5694 if (CompLHSTy) *CompLHSTy = compType;
5695 return compType;
5696 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005697
Eli Friedmanab3a8522009-03-28 01:22:36 +00005698 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00005699 if (lex.isInvalid() || rex.isInvalid())
5700 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005701
Chris Lattner6e4ab612007-12-09 21:53:25 +00005702 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005703
Chris Lattner6e4ab612007-12-09 21:53:25 +00005704 // Handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00005705 if (lex.get()->getType()->isArithmeticType() &&
5706 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005707 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005708 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005709 }
Mike Stump1eb44332009-09-09 15:08:12 +00005710
Chris Lattner6e4ab612007-12-09 21:53:25 +00005711 // Either ptr - int or ptr - ptr.
John Wiegley429bb272011-04-08 18:41:53 +00005712 if (lex.get()->getType()->isAnyPointerType()) {
5713 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005714
Douglas Gregore7450f52009-03-24 19:52:54 +00005715 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00005716
Douglas Gregore7450f52009-03-24 19:52:54 +00005717 bool ComplainAboutVoid = false;
5718 Expr *ComplainAboutFunc = 0;
5719 if (lpointee->isVoidType()) {
5720 if (getLangOptions().CPlusPlus) {
5721 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley429bb272011-04-08 18:41:53 +00005722 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00005723 return QualType();
5724 }
5725
5726 // GNU C extension: arithmetic on pointer to void
5727 ComplainAboutVoid = true;
5728 } else if (lpointee->isFunctionType()) {
5729 if (getLangOptions().CPlusPlus) {
5730 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley429bb272011-04-08 18:41:53 +00005731 << lex.get()->getType() << lex.get()->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005732 return QualType();
5733 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005734
5735 // GNU C extension: arithmetic on pointer to function
John Wiegley429bb272011-04-08 18:41:53 +00005736 ComplainAboutFunc = lex.get();
Douglas Gregore7450f52009-03-24 19:52:54 +00005737 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005738 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00005739 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley429bb272011-04-08 18:41:53 +00005740 << lex.get()->getSourceRange()
5741 << lex.get()->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00005742 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005743
Chris Lattnerb5f15622009-04-24 23:50:08 +00005744 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00005745 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00005746 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley429bb272011-04-08 18:41:53 +00005747 << lpointee << lex.get()->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00005748 return QualType();
5749 }
Mike Stump1eb44332009-09-09 15:08:12 +00005750
Chris Lattner6e4ab612007-12-09 21:53:25 +00005751 // The result type of a pointer-int computation is the pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00005752 if (rex.get()->getType()->isIntegerType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00005753 if (ComplainAboutVoid)
5754 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley429bb272011-04-08 18:41:53 +00005755 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00005756 if (ComplainAboutFunc)
5757 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00005758 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00005759 << ComplainAboutFunc->getSourceRange();
5760
John Wiegley429bb272011-04-08 18:41:53 +00005761 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
5762 return lex.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00005763 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005764
Chris Lattner6e4ab612007-12-09 21:53:25 +00005765 // Handle pointer-pointer subtractions.
John Wiegley429bb272011-04-08 18:41:53 +00005766 if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00005767 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005768
Douglas Gregore7450f52009-03-24 19:52:54 +00005769 // RHS must be a completely-type object type.
5770 // Handle the GNU void* extension.
5771 if (rpointee->isVoidType()) {
5772 if (getLangOptions().CPlusPlus) {
5773 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley429bb272011-04-08 18:41:53 +00005774 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00005775 return QualType();
5776 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005777
Douglas Gregore7450f52009-03-24 19:52:54 +00005778 ComplainAboutVoid = true;
5779 } else if (rpointee->isFunctionType()) {
5780 if (getLangOptions().CPlusPlus) {
5781 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley429bb272011-04-08 18:41:53 +00005782 << rex.get()->getType() << rex.get()->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005783 return QualType();
5784 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005785
5786 // GNU extension: arithmetic on pointer to function
5787 if (!ComplainAboutFunc)
John Wiegley429bb272011-04-08 18:41:53 +00005788 ComplainAboutFunc = rex.get();
Douglas Gregore7450f52009-03-24 19:52:54 +00005789 } else if (!rpointee->isDependentType() &&
5790 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00005791 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley429bb272011-04-08 18:41:53 +00005792 << rex.get()->getSourceRange()
5793 << rex.get()->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00005794 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005795
Eli Friedman88d936b2009-05-16 13:54:38 +00005796 if (getLangOptions().CPlusPlus) {
5797 // Pointee types must be the same: C++ [expr.add]
5798 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5799 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley429bb272011-04-08 18:41:53 +00005800 << lex.get()->getType() << rex.get()->getType()
5801 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman88d936b2009-05-16 13:54:38 +00005802 return QualType();
5803 }
5804 } else {
5805 // Pointee types must be compatible C99 6.5.6p3
5806 if (!Context.typesAreCompatible(
5807 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5808 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5809 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley429bb272011-04-08 18:41:53 +00005810 << lex.get()->getType() << rex.get()->getType()
5811 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman88d936b2009-05-16 13:54:38 +00005812 return QualType();
5813 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00005814 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005815
Douglas Gregore7450f52009-03-24 19:52:54 +00005816 if (ComplainAboutVoid)
5817 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley429bb272011-04-08 18:41:53 +00005818 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregore7450f52009-03-24 19:52:54 +00005819 if (ComplainAboutFunc)
5820 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00005821 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00005822 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00005823
John Wiegley429bb272011-04-08 18:41:53 +00005824 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005825 return Context.getPointerDiffType();
5826 }
5827 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005828
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005829 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005830}
5831
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005832static bool isScopedEnumerationType(QualType T) {
5833 if (const EnumType *ET = dyn_cast<EnumType>(T))
5834 return ET->getDecl()->isScoped();
5835 return false;
5836}
5837
John Wiegley429bb272011-04-08 18:41:53 +00005838static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth21206d52011-02-23 23:34:11 +00005839 SourceLocation Loc, unsigned Opc,
5840 QualType LHSTy) {
5841 llvm::APSInt Right;
5842 // Check right/shifter operand
John Wiegley429bb272011-04-08 18:41:53 +00005843 if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00005844 return;
5845
5846 if (Right.isNegative()) {
John Wiegley429bb272011-04-08 18:41:53 +00005847 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00005848 S.PDiag(diag::warn_shift_negative)
John Wiegley429bb272011-04-08 18:41:53 +00005849 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00005850 return;
5851 }
5852 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley429bb272011-04-08 18:41:53 +00005853 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00005854 if (Right.uge(LeftBits)) {
John Wiegley429bb272011-04-08 18:41:53 +00005855 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00005856 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley429bb272011-04-08 18:41:53 +00005857 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00005858 return;
5859 }
5860 if (Opc != BO_Shl)
5861 return;
5862
5863 // When left shifting an ICE which is signed, we can check for overflow which
5864 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
5865 // integers have defined behavior modulo one more than the maximum value
5866 // representable in the result type, so never warn for those.
5867 llvm::APSInt Left;
John Wiegley429bb272011-04-08 18:41:53 +00005868 if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth21206d52011-02-23 23:34:11 +00005869 LHSTy->hasUnsignedIntegerRepresentation())
5870 return;
5871 llvm::APInt ResultBits =
5872 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
5873 if (LeftBits.uge(ResultBits))
5874 return;
5875 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
5876 Result = Result.shl(Right);
5877
Ted Kremenekfa821382011-06-15 00:54:52 +00005878 // Print the bit representation of the signed integer as an unsigned
5879 // hexadecimal number.
5880 llvm::SmallString<40> HexResult;
5881 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
5882
Chandler Carruth21206d52011-02-23 23:34:11 +00005883 // If we are only missing a sign bit, this is less likely to result in actual
5884 // bugs -- if the result is cast back to an unsigned type, it will have the
5885 // expected value. Thus we place this behind a different warning that can be
5886 // turned off separately if needed.
5887 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00005888 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
5889 << HexResult.str() << LHSTy
John Wiegley429bb272011-04-08 18:41:53 +00005890 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00005891 return;
5892 }
5893
5894 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Ted Kremenekfa821382011-06-15 00:54:52 +00005895 << HexResult.str() << Result.getMinSignedBits() << LHSTy
John Wiegley429bb272011-04-08 18:41:53 +00005896 << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00005897}
5898
Chris Lattnereca7be62008-04-07 05:30:13 +00005899// C99 6.5.7
John Wiegley429bb272011-04-08 18:41:53 +00005900QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Chandler Carruth21206d52011-02-23 23:34:11 +00005901 unsigned Opc, bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00005902 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley429bb272011-04-08 18:41:53 +00005903 if (!lex.get()->getType()->hasIntegerRepresentation() ||
5904 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005905 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005906
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005907 // C++0x: Don't allow scoped enums. FIXME: Use something better than
5908 // hasIntegerRepresentation() above instead of this.
John Wiegley429bb272011-04-08 18:41:53 +00005909 if (isScopedEnumerationType(lex.get()->getType()) ||
5910 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005911 return InvalidOperands(Loc, lex, rex);
5912 }
5913
Nate Begeman2207d792009-10-25 02:26:48 +00005914 // Vector shifts promote their scalar inputs to vector type.
John Wiegley429bb272011-04-08 18:41:53 +00005915 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Nate Begeman2207d792009-10-25 02:26:48 +00005916 return CheckVectorOperands(Loc, lex, rex);
5917
Chris Lattnerca5eede2007-12-12 05:47:28 +00005918 // Shifts don't perform usual arithmetic conversions, they just do integer
5919 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00005920
John McCall1bc80af2010-12-16 19:28:59 +00005921 // For the LHS, do usual unary conversions, but then reset them away
5922 // if this is a compound assignment.
John Wiegley429bb272011-04-08 18:41:53 +00005923 ExprResult old_lex = lex;
5924 lex = UsualUnaryConversions(lex.take());
5925 if (lex.isInvalid())
5926 return QualType();
5927 QualType LHSTy = lex.get()->getType();
John McCall1bc80af2010-12-16 19:28:59 +00005928 if (isCompAssign) lex = old_lex;
5929
5930 // The RHS is simpler.
John Wiegley429bb272011-04-08 18:41:53 +00005931 rex = UsualUnaryConversions(rex.take());
5932 if (rex.isInvalid())
5933 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005934
Ryan Flynnd0439682009-08-07 16:20:20 +00005935 // Sanity-check shift operands
Chandler Carruth21206d52011-02-23 23:34:11 +00005936 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnd0439682009-08-07 16:20:20 +00005937
Chris Lattnerca5eede2007-12-12 05:47:28 +00005938 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00005939 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005940}
5941
Chandler Carruth99919472010-07-10 12:30:03 +00005942static bool IsWithinTemplateSpecialization(Decl *D) {
5943 if (DeclContext *DC = D->getDeclContext()) {
5944 if (isa<ClassTemplateSpecializationDecl>(DC))
5945 return true;
5946 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
5947 return FD->isFunctionTemplateSpecialization();
5948 }
5949 return false;
5950}
5951
Douglas Gregor0c6db942009-05-04 06:07:12 +00005952// C99 6.5.8, C++ [expr.rel]
John Wiegley429bb272011-04-08 18:41:53 +00005953QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00005954 unsigned OpaqueOpc, bool isRelational) {
John McCall2de56d12010-08-25 11:45:40 +00005955 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00005956
Chris Lattner02dd4b12009-12-05 05:40:13 +00005957 // Handle vector comparisons separately.
John Wiegley429bb272011-04-08 18:41:53 +00005958 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005959 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005960
John Wiegley429bb272011-04-08 18:41:53 +00005961 QualType lType = lex.get()->getType();
5962 QualType rType = rex.get()->getType();
Douglas Gregorfadb53b2011-03-12 01:48:56 +00005963
John Wiegley429bb272011-04-08 18:41:53 +00005964 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
5965 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00005966 QualType LHSStrippedType = LHSStripped->getType();
5967 QualType RHSStrippedType = RHSStripped->getType();
5968
Douglas Gregorfadb53b2011-03-12 01:48:56 +00005969
5970
Chandler Carruth543cb652011-02-17 08:37:06 +00005971 // Two different enums will raise a warning when compared.
5972 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
5973 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
5974 if (LHSEnumType->getDecl()->getIdentifier() &&
5975 RHSEnumType->getDecl()->getIdentifier() &&
5976 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
5977 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
5978 << LHSStrippedType << RHSStrippedType
John Wiegley429bb272011-04-08 18:41:53 +00005979 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth543cb652011-02-17 08:37:06 +00005980 }
5981 }
5982 }
5983
Douglas Gregor8eee1192010-06-22 22:12:46 +00005984 if (!lType->hasFloatingRepresentation() &&
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00005985 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley429bb272011-04-08 18:41:53 +00005986 !lex.get()->getLocStart().isMacroID() &&
5987 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00005988 // For non-floating point types, check for self-comparisons of the form
5989 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5990 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00005991 //
5992 // NOTE: Don't warn about comparison expressions resulting from macro
5993 // expansion. Also don't warn about comparisons which are only self
5994 // comparisons within a template specialization. The warnings should catch
5995 // obvious cases in the definition of the template anyways. The idea is to
5996 // warn when the typed comparison operator will always evaluate to the same
5997 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00005998 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00005999 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006000 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006001 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006002 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006003 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006004 << (Opc == BO_EQ
6005 || Opc == BO_LE
6006 || Opc == BO_GE));
Douglas Gregord64fdd02010-06-08 19:50:34 +00006007 } else if (lType->isArrayType() && rType->isArrayType() &&
6008 !DRL->getDecl()->getType()->isReferenceType() &&
6009 !DRR->getDecl()->getType()->isReferenceType()) {
6010 // what is it always going to eval to?
6011 char always_evals_to;
6012 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006013 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006014 always_evals_to = 0; // false
6015 break;
John McCall2de56d12010-08-25 11:45:40 +00006016 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006017 always_evals_to = 1; // true
6018 break;
6019 default:
6020 // best we can say is 'a constant'
6021 always_evals_to = 2; // e.g. array1 <= array2
6022 break;
6023 }
Ted Kremenek351ba912011-02-23 01:52:04 +00006024 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006025 << 1 // array
6026 << always_evals_to);
6027 }
6028 }
Chandler Carruth99919472010-07-10 12:30:03 +00006029 }
Mike Stump1eb44332009-09-09 15:08:12 +00006030
Chris Lattner55660a72009-03-08 19:39:53 +00006031 if (isa<CastExpr>(LHSStripped))
6032 LHSStripped = LHSStripped->IgnoreParenCasts();
6033 if (isa<CastExpr>(RHSStripped))
6034 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006035
Chris Lattner55660a72009-03-08 19:39:53 +00006036 // Warn about comparisons against a string constant (unless the other
6037 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006038 Expr *literalString = 0;
6039 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006040 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006041 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006042 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00006043 literalString = lex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006044 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006045 } else if ((isa<StringLiteral>(RHSStripped) ||
6046 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006047 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006048 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00006049 literalString = rex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006050 literalStringStripped = RHSStripped;
6051 }
6052
6053 if (literalString) {
6054 std::string resultComparison;
6055 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006056 case BO_LT: resultComparison = ") < 0"; break;
6057 case BO_GT: resultComparison = ") > 0"; break;
6058 case BO_LE: resultComparison = ") <= 0"; break;
6059 case BO_GE: resultComparison = ") >= 0"; break;
6060 case BO_EQ: resultComparison = ") == 0"; break;
6061 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregora86b8322009-04-06 18:45:53 +00006062 default: assert(false && "Invalid comparison operator");
6063 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006064
Ted Kremenek351ba912011-02-23 01:52:04 +00006065 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006066 PDiag(diag::warn_stringcompare)
6067 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006068 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006069 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006070 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006071
Douglas Gregord64fdd02010-06-08 19:50:34 +00006072 // C99 6.5.8p3 / C99 6.5.9p4
John Wiegley429bb272011-04-08 18:41:53 +00006073 if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006074 UsualArithmeticConversions(lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00006075 if (lex.isInvalid() || rex.isInvalid())
6076 return QualType();
6077 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00006078 else {
John Wiegley429bb272011-04-08 18:41:53 +00006079 lex = UsualUnaryConversions(lex.take());
6080 if (lex.isInvalid())
6081 return QualType();
6082
6083 rex = UsualUnaryConversions(rex.take());
6084 if (rex.isInvalid())
6085 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006086 }
6087
John Wiegley429bb272011-04-08 18:41:53 +00006088 lType = lex.get()->getType();
6089 rType = rex.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006090
Douglas Gregor447b69e2008-11-19 03:25:36 +00006091 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00006092 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00006093
Chris Lattnera5937dd2007-08-26 01:18:55 +00006094 if (isRelational) {
6095 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006096 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006097 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00006098 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006099 if (lType->hasFloatingRepresentation())
John Wiegley429bb272011-04-08 18:41:53 +00006100 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006101
Chris Lattnera5937dd2007-08-26 01:18:55 +00006102 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006103 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006104 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006105
John Wiegley429bb272011-04-08 18:41:53 +00006106 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006107 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00006108 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006109 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006110
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006111 // All of the following pointer-related warnings are GCC extensions, except
6112 // when handling null pointer constants.
Steve Naroff77878cc2007-08-27 04:08:11 +00006113 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00006114 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006115 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00006116 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006117 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006118
Douglas Gregor0c6db942009-05-04 06:07:12 +00006119 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00006120 if (LCanPointeeTy == RCanPointeeTy)
6121 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006122 if (!isRelational &&
6123 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6124 // Valid unless comparison between non-null pointer and function pointer
6125 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006126 // In a SFINAE context, we treat this as a hard error to maintain
6127 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006128 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6129 && !LHSIsNull && !RHSIsNull) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006130 Diag(Loc,
6131 isSFINAEContext()?
6132 diag::err_typecheck_comparison_of_fptr_to_void
6133 : diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley429bb272011-04-08 18:41:53 +00006134 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006135
6136 if (isSFINAEContext())
6137 return QualType();
6138
John Wiegley429bb272011-04-08 18:41:53 +00006139 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006140 return ResultTy;
6141 }
6142 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006143
Douglas Gregor0c6db942009-05-04 06:07:12 +00006144 // C++ [expr.rel]p2:
6145 // [...] Pointer conversions (4.10) and qualification
6146 // conversions (4.4) are performed on pointer operands (or on
6147 // a pointer operand and a null pointer constant) to bring
6148 // them to their composite pointer type. [...]
6149 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00006150 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00006151 // comparisons of pointers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006152 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00006153 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006154 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor0c6db942009-05-04 06:07:12 +00006155 if (T.isNull()) {
6156 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00006157 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00006158 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006159 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006160 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006161 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006162 << lType << rType << T
John Wiegley429bb272011-04-08 18:41:53 +00006163 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00006164 }
6165
John Wiegley429bb272011-04-08 18:41:53 +00006166 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6167 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00006168 return ResultTy;
6169 }
Eli Friedman3075e762009-08-23 00:27:47 +00006170 // C99 6.5.9p2 and C99 6.5.8p2
6171 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6172 RCanPointeeTy.getUnqualifiedType())) {
6173 // Valid unless a relational comparison of function pointers
6174 if (isRelational && LCanPointeeTy->isFunctionType()) {
6175 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00006176 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00006177 }
6178 } else if (!isRelational &&
6179 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6180 // Valid unless comparison between non-null pointer and function pointer
6181 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6182 && !LHSIsNull && !RHSIsNull) {
6183 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley429bb272011-04-08 18:41:53 +00006184 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00006185 }
6186 } else {
6187 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006188 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00006189 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006190 }
John McCall34d6f932011-03-11 04:25:25 +00006191 if (LCanPointeeTy != RCanPointeeTy) {
6192 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00006193 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006194 else
John Wiegley429bb272011-04-08 18:41:53 +00006195 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006196 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00006197 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00006198 }
Mike Stump1eb44332009-09-09 15:08:12 +00006199
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006200 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006201 // Comparison of nullptr_t with itself.
6202 if (lType->isNullPtrType() && rType->isNullPtrType())
6203 return ResultTy;
6204
Mike Stump1eb44332009-09-09 15:08:12 +00006205 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00006206 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00006207 if (RHSIsNull &&
Douglas Gregor17e37c72011-06-01 15:12:24 +00006208 ((lType->isAnyPointerType() || lType->isNullPtrType()) ||
Douglas Gregor16cd4b72011-06-16 18:52:05 +00006209 (!isRelational &&
6210 (lType->isMemberPointerType() || lType->isBlockPointerType())))) {
John Wiegley429bb272011-04-08 18:41:53 +00006211 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregor443c2122010-08-07 13:36:37 +00006212 lType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006213 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006214 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006215 return ResultTy;
6216 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006217 if (LHSIsNull &&
Douglas Gregor17e37c72011-06-01 15:12:24 +00006218 ((rType->isAnyPointerType() || rType->isNullPtrType()) ||
Douglas Gregor16cd4b72011-06-16 18:52:05 +00006219 (!isRelational &&
6220 (rType->isMemberPointerType() || rType->isBlockPointerType())))) {
John Wiegley429bb272011-04-08 18:41:53 +00006221 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregor443c2122010-08-07 13:36:37 +00006222 rType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006223 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006224 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006225 return ResultTy;
6226 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006227
6228 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00006229 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00006230 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6231 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00006232 // In addition, pointers to members can be compared, or a pointer to
6233 // member and a null pointer constant. Pointer to member conversions
6234 // (4.11) and qualification conversions (4.4) are performed to bring
6235 // them to a common type. If one operand is a null pointer constant,
6236 // the common type is the type of the other operand. Otherwise, the
6237 // common type is a pointer to member type similar (4.4) to the type
6238 // of one of the operands, with a cv-qualification signature (4.4)
6239 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00006240 // types.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006241 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00006242 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006243 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor20b3e992009-08-24 17:42:35 +00006244 if (T.isNull()) {
6245 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00006246 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00006247 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006248 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006249 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006250 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006251 << lType << rType << T
John Wiegley429bb272011-04-08 18:41:53 +00006252 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00006253 }
Mike Stump1eb44332009-09-09 15:08:12 +00006254
John Wiegley429bb272011-04-08 18:41:53 +00006255 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6256 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00006257 return ResultTy;
6258 }
Douglas Gregor90566c02011-03-01 17:16:20 +00006259
6260 // Handle scoped enumeration types specifically, since they don't promote
6261 // to integers.
John Wiegley429bb272011-04-08 18:41:53 +00006262 if (lex.get()->getType()->isEnumeralType() &&
6263 Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00006264 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006265 }
Mike Stump1eb44332009-09-09 15:08:12 +00006266
Steve Naroff1c7d0672008-09-04 15:10:53 +00006267 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00006268 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00006269 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6270 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006271
Steve Naroff1c7d0672008-09-04 15:10:53 +00006272 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00006273 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006274 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley429bb272011-04-08 18:41:53 +00006275 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00006276 }
John Wiegley429bb272011-04-08 18:41:53 +00006277 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006278 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006279 }
John Wiegley429bb272011-04-08 18:41:53 +00006280
Steve Naroff59f53942008-09-28 01:11:11 +00006281 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00006282 if (!isRelational
6283 && ((lType->isBlockPointerType() && rType->isPointerType())
6284 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00006285 if (!LHSIsNull && !RHSIsNull) {
John McCall34d6f932011-03-11 04:25:25 +00006286 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006287 ->getPointeeType()->isVoidType())
John McCall34d6f932011-03-11 04:25:25 +00006288 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006289 ->getPointeeType()->isVoidType())))
6290 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley429bb272011-04-08 18:41:53 +00006291 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00006292 }
John McCall34d6f932011-03-11 04:25:25 +00006293 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00006294 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006295 else
John Wiegley429bb272011-04-08 18:41:53 +00006296 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006297 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00006298 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00006299
John McCall34d6f932011-03-11 04:25:25 +00006300 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
6301 const PointerType *LPT = lType->getAs<PointerType>();
6302 const PointerType *RPT = rType->getAs<PointerType>();
6303 if (LPT || RPT) {
6304 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6305 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006306
Steve Naroffa8069f12008-11-17 19:49:16 +00006307 if (!LPtrToVoid && !RPtrToVoid &&
6308 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006309 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00006310 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00006311 }
John McCall34d6f932011-03-11 04:25:25 +00006312 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00006313 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006314 else
John Wiegley429bb272011-04-08 18:41:53 +00006315 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006316 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00006317 }
Steve Naroff14108da2009-07-10 23:34:53 +00006318 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00006319 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00006320 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley429bb272011-04-08 18:41:53 +00006321 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
John McCall34d6f932011-03-11 04:25:25 +00006322 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00006323 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006324 else
John Wiegley429bb272011-04-08 18:41:53 +00006325 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006326 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00006327 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00006328 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006329 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6330 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006331 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006332 bool isError = false;
6333 if ((LHSIsNull && lType->isIntegerType()) ||
6334 (RHSIsNull && rType->isIntegerType())) {
6335 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006336 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006337 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006338 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006339 else if (getLangOptions().CPlusPlus) {
6340 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6341 isError = true;
6342 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006343 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00006344
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006345 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00006346 Diag(Loc, DiagID)
John Wiegley429bb272011-04-08 18:41:53 +00006347 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006348 if (isError)
6349 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00006350 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006351
6352 if (lType->isIntegerType())
John Wiegley429bb272011-04-08 18:41:53 +00006353 lex = ImpCastExprToType(lex.take(), rType,
John McCall404cd162010-11-13 01:35:44 +00006354 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006355 else
John Wiegley429bb272011-04-08 18:41:53 +00006356 rex = ImpCastExprToType(rex.take(), lType,
John McCall404cd162010-11-13 01:35:44 +00006357 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006358 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006359 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006360
Steve Naroff39218df2008-09-04 16:56:14 +00006361 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00006362 if (!isRelational && RHSIsNull
6363 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006364 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006365 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006366 }
Mike Stumpaf199f32009-05-07 18:43:07 +00006367 if (!isRelational && LHSIsNull
6368 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006369 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006370 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006371 }
Douglas Gregor90566c02011-03-01 17:16:20 +00006372
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006373 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006374}
6375
Nate Begemanbe2341d2008-07-14 18:02:46 +00006376/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00006377/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00006378/// like a scalar comparison, a vector comparison produces a vector of integer
6379/// types.
John Wiegley429bb272011-04-08 18:41:53 +00006380QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006381 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00006382 bool isRelational) {
6383 // Check to make sure we're operating on vectors of the same type and width,
6384 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006385 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00006386 if (vType.isNull())
6387 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006388
John Wiegley429bb272011-04-08 18:41:53 +00006389 QualType lType = lex.get()->getType();
6390 QualType rType = rex.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006391
Anton Yartsev7870b132011-03-27 15:36:07 +00006392 // If AltiVec, the comparison results in a numeric type, i.e.
6393 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00006394 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00006395 return Context.getLogicalOperationType();
6396
Nate Begemanbe2341d2008-07-14 18:02:46 +00006397 // For non-floating point types, check for self-comparisons of the form
6398 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6399 // often indicate logic errors in the program.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006400 if (!lType->hasFloatingRepresentation()) {
John Wiegley429bb272011-04-08 18:41:53 +00006401 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
6402 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006403 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00006404 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00006405 PDiag(diag::warn_comparison_always)
6406 << 0 // self-
6407 << 2 // "a constant"
6408 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00006409 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006410
Nate Begemanbe2341d2008-07-14 18:02:46 +00006411 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006412 if (!isRelational && lType->hasFloatingRepresentation()) {
6413 assert (rType->hasFloatingRepresentation());
John Wiegley429bb272011-04-08 18:41:53 +00006414 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00006415 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006416
Nate Begemanbe2341d2008-07-14 18:02:46 +00006417 // Return the type for the comparison, which is the same as vector type for
6418 // integer vectors, or an integer type of identical size and number of
6419 // elements for floating point vectors.
Douglas Gregorf6094622010-07-23 15:58:24 +00006420 if (lType->hasIntegerRepresentation())
Nate Begemanbe2341d2008-07-14 18:02:46 +00006421 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006422
John McCall183700f2009-09-21 23:43:11 +00006423 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00006424 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00006425 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006426 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00006427 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00006428 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6429
Mike Stumpeed9cac2009-02-19 03:04:26 +00006430 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00006431 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00006432 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6433}
6434
Reid Spencer5f016e22007-07-11 17:01:13 +00006435inline QualType Sema::CheckBitwiseOperands(
John Wiegley429bb272011-04-08 18:41:53 +00006436 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
6437 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
6438 if (lex.get()->getType()->hasIntegerRepresentation() &&
6439 rex.get()->getType()->hasIntegerRepresentation())
Douglas Gregorf6094622010-07-23 15:58:24 +00006440 return CheckVectorOperands(Loc, lex, rex);
6441
6442 return InvalidOperands(Loc, lex, rex);
6443 }
Steve Naroff90045e82007-07-13 23:32:42 +00006444
John Wiegley429bb272011-04-08 18:41:53 +00006445 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
6446 QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
6447 if (lexResult.isInvalid() || rexResult.isInvalid())
6448 return QualType();
6449 lex = lexResult.take();
6450 rex = rexResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006451
John Wiegley429bb272011-04-08 18:41:53 +00006452 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6453 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006454 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006455 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006456}
6457
6458inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley429bb272011-04-08 18:41:53 +00006459 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00006460
6461 // Diagnose cases where the user write a logical and/or but probably meant a
6462 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6463 // is a constant.
John Wiegley429bb272011-04-08 18:41:53 +00006464 if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
6465 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Chris Lattner23ef3e42010-07-15 00:26:43 +00006466 // Don't warn in macros.
Chris Lattnerb7690b42010-07-24 01:10:11 +00006467 !Loc.isMacroID()) {
6468 // If the RHS can be constant folded, and if it constant folds to something
6469 // that isn't 0 or 1 (which indicate a potential logical operation that
6470 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00006471 // Parens on the RHS are ignored.
Chris Lattnerb7690b42010-07-24 01:10:11 +00006472 Expr::EvalResult Result;
Chandler Carruth0683a142011-05-31 05:41:42 +00006473 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6474 if ((getLangOptions().Bool && !rex.get()->getType()->isBooleanType()) ||
6475 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6476 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6477 << rex.get()->getSourceRange()
6478 << (Opc == BO_LAnd ? "&&" : "||")
6479 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattnerb7690b42010-07-24 01:10:11 +00006480 }
6481 }
Chris Lattner90a8f272010-07-13 19:41:32 +00006482
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006483 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00006484 lex = UsualUnaryConversions(lex.take());
6485 if (lex.isInvalid())
6486 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006487
John Wiegley429bb272011-04-08 18:41:53 +00006488 rex = UsualUnaryConversions(rex.take());
6489 if (rex.isInvalid())
6490 return QualType();
6491
6492 if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006493 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006494
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006495 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00006496 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006497
John McCall75f7c0f2010-06-04 00:29:51 +00006498 // The following is safe because we only use this method for
6499 // non-overloadable operands.
6500
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006501 // C++ [expr.log.and]p1
6502 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00006503 // The operands are both contextually converted to type bool.
John Wiegley429bb272011-04-08 18:41:53 +00006504 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
6505 if (lexRes.isInvalid())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006506 return InvalidOperands(Loc, lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00006507 lex = move(lexRes);
6508
6509 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
6510 if (rexRes.isInvalid())
6511 return InvalidOperands(Loc, lex, rex);
6512 rex = move(rexRes);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006513
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006514 // C++ [expr.log.and]p2
6515 // C++ [expr.log.or]p2
6516 // The result is a bool.
6517 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006518}
6519
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006520/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6521/// is a read-only property; return true if so. A readonly property expression
6522/// depends on various declarations and thus must be treated specially.
6523///
Mike Stump1eb44332009-09-09 15:08:12 +00006524static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006525 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6526 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCall12f78a62010-12-02 01:19:52 +00006527 if (PropExpr->isImplicitProperty()) return false;
6528
6529 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6530 QualType BaseType = PropExpr->isSuperReceiver() ?
6531 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00006532 PropExpr->getBase()->getType();
6533
John McCall12f78a62010-12-02 01:19:52 +00006534 if (const ObjCObjectPointerType *OPT =
6535 BaseType->getAsObjCInterfacePointerType())
6536 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6537 if (S.isPropertyReadonly(PDecl, IFace))
6538 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006539 }
6540 return false;
6541}
6542
Fariborz Jahanian14086762011-03-28 23:47:18 +00006543static bool IsConstProperty(Expr *E, Sema &S) {
6544 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6545 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6546 if (PropExpr->isImplicitProperty()) return false;
6547
6548 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6549 QualType T = PDecl->getType();
6550 if (T->isReferenceType())
Fariborz Jahanian61750f22011-03-30 16:59:30 +00006551 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanian14086762011-03-28 23:47:18 +00006552 CanQualType CT = S.Context.getCanonicalType(T);
6553 return CT.isConstQualified();
6554 }
6555 return false;
6556}
6557
Fariborz Jahanian077f4902011-03-26 19:48:30 +00006558static bool IsReadonlyMessage(Expr *E, Sema &S) {
6559 if (E->getStmtClass() != Expr::MemberExprClass)
6560 return false;
6561 const MemberExpr *ME = cast<MemberExpr>(E);
6562 NamedDecl *Member = ME->getMemberDecl();
6563 if (isa<FieldDecl>(Member)) {
6564 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
6565 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
6566 return false;
6567 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
6568 }
6569 return false;
6570}
6571
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006572/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6573/// emit an error and return true. If so, return false.
6574static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006575 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00006576 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006577 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006578 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6579 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian14086762011-03-28 23:47:18 +00006580 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
6581 IsLV = Expr::MLV_Valid;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00006582 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
6583 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006584 if (IsLV == Expr::MLV_Valid)
6585 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006586
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006587 unsigned Diag = 0;
6588 bool NeedType = false;
6589 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00006590 case Expr::MLV_ConstQualified:
6591 Diag = diag::err_typecheck_assign_const;
6592
John McCall7acddac2011-06-17 06:42:21 +00006593 // In ARC, use some specialized diagnostics for occasions where we
6594 // infer 'const'. These are always pseudo-strong variables.
John McCallf85e1932011-06-15 23:02:42 +00006595 if (S.getLangOptions().ObjCAutoRefCount) {
6596 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
6597 if (declRef && isa<VarDecl>(declRef->getDecl())) {
6598 VarDecl *var = cast<VarDecl>(declRef->getDecl());
6599
John McCall7acddac2011-06-17 06:42:21 +00006600 // Use the normal diagnostic if it's pseudo-__strong but the
6601 // user actually wrote 'const'.
6602 if (var->isARCPseudoStrong() &&
6603 (!var->getTypeSourceInfo() ||
6604 !var->getTypeSourceInfo()->getType().isConstQualified())) {
6605 // There are two pseudo-strong cases:
6606 // - self
John McCallf85e1932011-06-15 23:02:42 +00006607 ObjCMethodDecl *method = S.getCurMethodDecl();
6608 if (method && var == method->getSelfDecl())
6609 Diag = diag::err_typecheck_arr_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00006610
6611 // - fast enumeration variables
6612 else
John McCallf85e1932011-06-15 23:02:42 +00006613 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00006614
John McCallf85e1932011-06-15 23:02:42 +00006615 SourceRange Assign;
6616 if (Loc != OrigLoc)
6617 Assign = SourceRange(OrigLoc, OrigLoc);
6618 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
6619 // We need to preserve the AST regardless, so migration tool
6620 // can do its job.
6621 return false;
6622 }
6623 }
6624 }
6625
6626 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006627 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006628 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6629 NeedType = true;
6630 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006631 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006632 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6633 NeedType = true;
6634 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00006635 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006636 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6637 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00006638 case Expr::MLV_Valid:
6639 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00006640 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00006641 case Expr::MLV_MemberFunction:
6642 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006643 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6644 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006645 case Expr::MLV_IncompleteType:
6646 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00006647 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006648 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00006649 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00006650 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006651 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6652 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00006653 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006654 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6655 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00006656 case Expr::MLV_ReadonlyProperty:
6657 Diag = diag::error_readonly_property_assignment;
6658 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00006659 case Expr::MLV_NoSetterProperty:
6660 Diag = diag::error_nosetter_property_assignment;
6661 break;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00006662 case Expr::MLV_InvalidMessageExpression:
6663 Diag = diag::error_readonly_message_assignment;
6664 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00006665 case Expr::MLV_SubObjCPropertySetting:
6666 Diag = diag::error_no_subobject_property_setting;
6667 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006668 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00006669
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006670 SourceRange Assign;
6671 if (Loc != OrigLoc)
6672 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006673 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006674 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006675 else
Mike Stump1eb44332009-09-09 15:08:12 +00006676 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006677 return true;
6678}
6679
6680
6681
6682// C99 6.5.16.1
John Wiegley429bb272011-04-08 18:41:53 +00006683QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006684 SourceLocation Loc,
6685 QualType CompoundType) {
6686 // Verify that LHS is a modifiable lvalue, and emit error if not.
6687 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006688 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006689
6690 QualType LHSType = LHS->getType();
John Wiegley429bb272011-04-08 18:41:53 +00006691 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006692 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006693 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00006694 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00006695 // Simple assignment "x = y".
John Wiegley429bb272011-04-08 18:41:53 +00006696 if (LHS->getObjectKind() == OK_ObjCProperty) {
6697 ExprResult LHSResult = Owned(LHS);
6698 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
6699 if (LHSResult.isInvalid())
6700 return QualType();
6701 LHS = LHSResult.take();
6702 }
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00006703 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00006704 if (RHS.isInvalid())
6705 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00006706 // Special case of NSObject attributes on c-style pointer types.
6707 if (ConvTy == IncompatiblePointer &&
6708 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00006709 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00006710 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00006711 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00006712 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006713
John McCallf89e55a2010-11-18 06:31:45 +00006714 if (ConvTy == Compatible &&
6715 getLangOptions().ObjCNonFragileABI &&
6716 LHSType->isObjCObjectType())
6717 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
6718 << LHSType;
6719
Chris Lattner2c156472008-08-21 18:04:13 +00006720 // If the RHS is a unary plus or minus, check to see if they = and + are
6721 // right next to each other. If so, the user may have typo'd "x =+ 4"
6722 // instead of "x += 4".
John Wiegley429bb272011-04-08 18:41:53 +00006723 Expr *RHSCheck = RHS.get();
Chris Lattner2c156472008-08-21 18:04:13 +00006724 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
6725 RHSCheck = ICE->getSubExpr();
6726 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00006727 if ((UO->getOpcode() == UO_Plus ||
6728 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006729 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00006730 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00006731 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
6732 // And there is a space or other character before the subexpr of the
6733 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00006734 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
6735 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006736 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00006737 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006738 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00006739 }
Chris Lattner2c156472008-08-21 18:04:13 +00006740 }
John McCallf85e1932011-06-15 23:02:42 +00006741
6742 if (ConvTy == Compatible) {
6743 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
6744 checkRetainCycles(LHS, RHS.get());
6745 else
6746 checkUnsafeAssigns(Loc, LHSType, RHS.get());
6747 }
Chris Lattner2c156472008-08-21 18:04:13 +00006748 } else {
6749 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00006750 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00006751 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00006752
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006753 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00006754 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00006755 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006756
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +00006757 CheckForNullPointerDereference(*this, LHS);
Ted Kremeneka0125d82011-02-16 01:57:07 +00006758 // Check for trivial buffer overflows.
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006759 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006760
Reid Spencer5f016e22007-07-11 17:01:13 +00006761 // C99 6.5.16p3: The type of an assignment expression is the type of the
6762 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00006763 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00006764 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
6765 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006766 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00006767 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00006768 return (getLangOptions().CPlusPlus
6769 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00006770}
6771
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006772// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00006773static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00006774 SourceLocation Loc) {
John Wiegley429bb272011-04-08 18:41:53 +00006775 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00006776
John McCallfb8721c2011-04-10 19:13:55 +00006777 LHS = S.CheckPlaceholderExpr(LHS.take());
6778 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00006779 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00006780 return QualType();
6781
John McCallcf2e5062010-10-12 07:14:40 +00006782 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
6783 // operands, but not unary promotions.
6784 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006785
John McCallf6a16482010-12-04 03:47:34 +00006786 // So we treat the LHS as a ignored value, and in C++ we allow the
6787 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00006788 LHS = S.IgnoredValueConversions(LHS.take());
6789 if (LHS.isInvalid())
6790 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00006791
6792 if (!S.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00006793 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
6794 if (RHS.isInvalid())
6795 return QualType();
6796 if (!RHS.get()->getType()->isVoidType())
6797 S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00006798 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006799
John Wiegley429bb272011-04-08 18:41:53 +00006800 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006801}
6802
Steve Naroff49b45262007-07-13 16:58:59 +00006803/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
6804/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00006805static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
6806 ExprValueKind &VK,
6807 SourceLocation OpLoc,
6808 bool isInc, bool isPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00006809 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00006810 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00006811
Chris Lattner3528d352008-11-21 07:05:48 +00006812 QualType ResType = Op->getType();
6813 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00006814
John McCall09431682010-11-18 19:01:18 +00006815 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006816 // Decrement of bool is not allowed.
6817 if (!isInc) {
John McCall09431682010-11-18 19:01:18 +00006818 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006819 return QualType();
6820 }
6821 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00006822 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006823 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00006824 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00006825 } else if (ResType->isAnyPointerType()) {
6826 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00006827
Chris Lattner3528d352008-11-21 07:05:48 +00006828 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00006829 if (PointeeTy->isVoidType()) {
John McCall09431682010-11-18 19:01:18 +00006830 if (S.getLangOptions().CPlusPlus) {
6831 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00006832 << Op->getSourceRange();
6833 return QualType();
6834 }
6835
6836 // Pointer to void is a GNU extension in C.
John McCall09431682010-11-18 19:01:18 +00006837 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00006838 } else if (PointeeTy->isFunctionType()) {
John McCall09431682010-11-18 19:01:18 +00006839 if (S.getLangOptions().CPlusPlus) {
6840 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorc983b862009-01-23 00:36:41 +00006841 << Op->getType() << Op->getSourceRange();
6842 return QualType();
6843 }
6844
John McCall09431682010-11-18 19:01:18 +00006845 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00006846 << ResType << Op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00006847 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
6848 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00006849 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00006850 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006851 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00006852 // Diagnose bad cases where we step over interface counts.
John McCall09431682010-11-18 19:01:18 +00006853 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
6854 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00006855 << PointeeTy << Op->getSourceRange();
6856 return QualType();
6857 }
Eli Friedman5b088a12010-01-03 00:20:48 +00006858 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00006859 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00006860 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00006861 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00006862 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00006863 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00006864 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00006865 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
6866 isInc, isPrefix);
Anton Yartsev683564a2011-02-07 02:17:30 +00006867 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
6868 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00006869 } else {
John McCall09431682010-11-18 19:01:18 +00006870 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00006871 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00006872 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006873 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006874 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00006875 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00006876 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00006877 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00006878 // In C++, a prefix increment is the same type as the operand. Otherwise
6879 // (in C or with postfix), the increment is the unqualified type of the
6880 // operand.
John McCall09431682010-11-18 19:01:18 +00006881 if (isPrefix && S.getLangOptions().CPlusPlus) {
6882 VK = VK_LValue;
6883 return ResType;
6884 } else {
6885 VK = VK_RValue;
6886 return ResType.getUnqualifiedType();
6887 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006888}
6889
John Wiegley429bb272011-04-08 18:41:53 +00006890ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCallf6a16482010-12-04 03:47:34 +00006891 assert(E->getValueKind() == VK_LValue &&
6892 E->getObjectKind() == OK_ObjCProperty);
6893 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
6894
Douglas Gregor926df6c2011-06-11 01:09:30 +00006895 QualType T = E->getType();
6896 QualType ReceiverType;
6897 if (PRE->isObjectReceiver())
6898 ReceiverType = PRE->getBase()->getType();
6899 else if (PRE->isSuperReceiver())
6900 ReceiverType = PRE->getSuperReceiverType();
6901 else
6902 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
6903
John McCallf6a16482010-12-04 03:47:34 +00006904 ExprValueKind VK = VK_RValue;
6905 if (PRE->isImplicitProperty()) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00006906 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian99130e52010-12-22 19:46:35 +00006907 PRE->getImplicitPropertyGetter()) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00006908 T = getMessageSendResultType(ReceiverType, GetterMethod,
6909 PRE->isClassReceiver(),
6910 PRE->isSuperReceiver());
6911 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian99130e52010-12-22 19:46:35 +00006912 }
6913 else {
6914 Diag(PRE->getLocation(), diag::err_getter_not_found)
6915 << PRE->getBase()->getType();
6916 }
John McCallf6a16482010-12-04 03:47:34 +00006917 }
Douglas Gregor926df6c2011-06-11 01:09:30 +00006918
6919 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCallf6a16482010-12-04 03:47:34 +00006920 E, 0, VK);
John McCalldb67e2f2010-12-10 01:49:45 +00006921
6922 ExprResult Result = MaybeBindToTemporary(E);
6923 if (!Result.isInvalid())
6924 E = Result.take();
John Wiegley429bb272011-04-08 18:41:53 +00006925
6926 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00006927}
6928
John Wiegley429bb272011-04-08 18:41:53 +00006929void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
6930 assert(LHS.get()->getValueKind() == VK_LValue &&
6931 LHS.get()->getObjectKind() == OK_ObjCProperty);
6932 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCallf6a16482010-12-04 03:47:34 +00006933
John McCallf85e1932011-06-15 23:02:42 +00006934 bool Consumed = false;
6935
John Wiegley429bb272011-04-08 18:41:53 +00006936 if (PropRef->isImplicitProperty()) {
John McCallf6a16482010-12-04 03:47:34 +00006937 // If using property-dot syntax notation for assignment, and there is a
6938 // setter, RHS expression is being passed to the setter argument. So,
6939 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley429bb272011-04-08 18:41:53 +00006940 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCallf6a16482010-12-04 03:47:34 +00006941 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
6942 LHSTy = (*P)->getType();
John McCallf85e1932011-06-15 23:02:42 +00006943 Consumed = (getLangOptions().ObjCAutoRefCount &&
6944 (*P)->hasAttr<NSConsumedAttr>());
John McCallf6a16482010-12-04 03:47:34 +00006945
6946 // Otherwise, if the getter returns an l-value, just call that.
6947 } else {
John Wiegley429bb272011-04-08 18:41:53 +00006948 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCallf6a16482010-12-04 03:47:34 +00006949 ExprValueKind VK = Expr::getValueKindForType(Result);
6950 if (VK == VK_LValue) {
John Wiegley429bb272011-04-08 18:41:53 +00006951 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
6952 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCallf6a16482010-12-04 03:47:34 +00006953 return;
John McCall12f78a62010-12-02 01:19:52 +00006954 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00006955 }
John McCallf85e1932011-06-15 23:02:42 +00006956 } else if (getLangOptions().ObjCAutoRefCount) {
6957 const ObjCMethodDecl *setter
6958 = PropRef->getExplicitProperty()->getSetterMethodDecl();
6959 if (setter) {
6960 ObjCMethodDecl::param_iterator P = setter->param_begin();
6961 LHSTy = (*P)->getType();
6962 Consumed = (*P)->hasAttr<NSConsumedAttr>();
6963 }
John McCallf6a16482010-12-04 03:47:34 +00006964 }
6965
John McCallf85e1932011-06-15 23:02:42 +00006966 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
6967 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00006968 InitializedEntity Entity =
John McCallf85e1932011-06-15 23:02:42 +00006969 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley429bb272011-04-08 18:41:53 +00006970 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCallf85e1932011-06-15 23:02:42 +00006971 if (!ArgE.isInvalid()) {
John Wiegley429bb272011-04-08 18:41:53 +00006972 RHS = ArgE;
John McCallf85e1932011-06-15 23:02:42 +00006973 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
6974 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
6975 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00006976 }
6977}
6978
6979
Anders Carlsson369dee42008-02-01 07:15:58 +00006980/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00006981/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00006982/// where the declaration is needed for type checking. We only need to
6983/// handle cases when the expression references a function designator
6984/// or is an lvalue. Here are some examples:
6985/// - &(x) => x
6986/// - &*****f => f for f a function designator.
6987/// - &s.xx => s
6988/// - &s.zz[1].yy -> s, if zz is an array
6989/// - *(x + 1) -> x, if x is an array
6990/// - &"123"[2] -> 0
6991/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00006992static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00006993 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006994 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00006995 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00006996 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00006997 // If this is an arrow operator, the address is an offset from
6998 // the base's value, so the object the base refers to is
6999 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007000 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007001 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007002 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007003 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007004 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007005 // FIXME: This code shouldn't be necessary! We should catch the implicit
7006 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007007 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7008 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7009 if (ICE->getSubExpr()->getType()->isArrayType())
7010 return getPrimaryDecl(ICE->getSubExpr());
7011 }
7012 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007013 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007014 case Stmt::UnaryOperatorClass: {
7015 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007016
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007017 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007018 case UO_Real:
7019 case UO_Imag:
7020 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007021 return getPrimaryDecl(UO->getSubExpr());
7022 default:
7023 return 0;
7024 }
7025 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007026 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007027 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007028 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007029 // If the result of an implicit cast is an l-value, we care about
7030 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007031 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007032 default:
7033 return 0;
7034 }
7035}
7036
7037/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007038/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007039/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007040/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007041/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007042/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007043/// we allow the '&' but retain the overloaded-function type.
John McCall09431682010-11-18 19:01:18 +00007044static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7045 SourceLocation OpLoc) {
John McCall9c72c602010-08-27 09:08:28 +00007046 if (OrigOp->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007047 return S.Context.DependentTy;
7048 if (OrigOp->getType() == S.Context.OverloadTy)
7049 return S.Context.OverloadTy;
John McCall755d8492011-04-12 00:42:48 +00007050 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7051 return S.Context.UnknownAnyTy;
John McCall864c0412011-04-26 20:42:42 +00007052 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7053 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7054 << OrigOp->getSourceRange();
7055 return QualType();
7056 }
John McCall9c72c602010-08-27 09:08:28 +00007057
John McCall755d8492011-04-12 00:42:48 +00007058 assert(!OrigOp->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00007059
John McCall9c72c602010-08-27 09:08:28 +00007060 // Make sure to ignore parentheses in subsequent checks
7061 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007062
John McCall09431682010-11-18 19:01:18 +00007063 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007064 // Implement C99-only parts of addressof rules.
7065 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007066 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007067 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7068 // (assuming the deref expression is valid).
7069 return uOp->getSubExpr()->getType();
7070 }
7071 // Technically, there should be a check for array subscript
7072 // expressions here, but the result of one is always an lvalue anyway.
7073 }
John McCall5808ce42011-02-03 08:15:49 +00007074 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007075 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007076
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007077 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007078 bool sfinae = S.isSFINAEContext();
7079 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7080 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007081 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007082 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007083 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007084 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007085 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007086 } else if (lval == Expr::LV_MemberFunction) {
7087 // If it's an instance method, make a member pointer.
7088 // The expression must have exactly the form &A::foo.
7089
7090 // If the underlying expression isn't a decl ref, give up.
7091 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007092 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007093 << OrigOp->getSourceRange();
7094 return QualType();
7095 }
7096 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7097 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7098
7099 // The id-expression was parenthesized.
7100 if (OrigOp != DRE) {
John McCall09431682010-11-18 19:01:18 +00007101 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007102 << OrigOp->getSourceRange();
7103
7104 // The method was named without a qualifier.
7105 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007106 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007107 << op->getSourceRange();
7108 }
7109
John McCall09431682010-11-18 19:01:18 +00007110 return S.Context.getMemberPointerType(op->getType(),
7111 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007112 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007113 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007114 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007115 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00007116 // FIXME: emit more specific diag...
John McCall09431682010-11-18 19:01:18 +00007117 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00007118 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007119 return QualType();
7120 }
John McCall7eb0a9e2010-11-24 05:12:34 +00007121 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007122 // The operand cannot be a bit-field
John McCall09431682010-11-18 19:01:18 +00007123 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman23d58ce2009-04-20 08:23:18 +00007124 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00007125 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007126 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00007127 // The operand cannot be an element of a vector
John McCall09431682010-11-18 19:01:18 +00007128 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00007129 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00007130 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007131 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007132 // cannot take address of a property expression.
John McCall09431682010-11-18 19:01:18 +00007133 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007134 << "property expression" << op->getSourceRange();
7135 return QualType();
Steve Naroffbcb2b612008-02-29 23:30:25 +00007136 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00007137 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00007138 // with the register storage-class specifier.
7139 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00007140 // in C++ it is not error to take address of a register
7141 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00007142 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00007143 !S.getLangOptions().CPlusPlus) {
7144 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007145 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007146 return QualType();
7147 }
John McCallba135432009-11-21 08:51:07 +00007148 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00007149 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00007150 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00007151 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00007152 // Could be a pointer to member, though, if there is an explicit
7153 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00007154 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00007155 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007156 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00007157 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00007158 S.Diag(OpLoc,
7159 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00007160 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007161 return QualType();
7162 }
Mike Stump1eb44332009-09-09 15:08:12 +00007163
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00007164 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7165 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00007166 return S.Context.getMemberPointerType(op->getType(),
7167 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007168 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00007169 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00007170 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00007171 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00007172 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00007173
Eli Friedman441cf102009-05-16 23:27:50 +00007174 if (lval == Expr::LV_IncompleteVoidType) {
7175 // Taking the address of a void variable is technically illegal, but we
7176 // allow it in cases which are otherwise valid.
7177 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00007178 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00007179 }
7180
Reid Spencer5f016e22007-07-11 17:01:13 +00007181 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00007182 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00007183 return S.Context.getObjCObjectPointerType(op->getType());
7184 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007185}
7186
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007187/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00007188static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7189 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00007190 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007191 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007192
John Wiegley429bb272011-04-08 18:41:53 +00007193 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7194 if (ConvResult.isInvalid())
7195 return QualType();
7196 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007197 QualType OpTy = Op->getType();
7198 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00007199
7200 if (isa<CXXReinterpretCastExpr>(Op)) {
7201 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7202 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7203 Op->getSourceRange());
7204 }
7205
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007206 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7207 // is an incomplete type or void. It would be possible to warn about
7208 // dereferencing a void pointer, but it's completely well-defined, and such a
7209 // warning is unlikely to catch any mistakes.
7210 if (const PointerType *PT = OpTy->getAs<PointerType>())
7211 Result = PT->getPointeeType();
7212 else if (const ObjCObjectPointerType *OPT =
7213 OpTy->getAs<ObjCObjectPointerType>())
7214 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00007215 else {
John McCallfb8721c2011-04-10 19:13:55 +00007216 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007217 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007218 if (PR.take() != Op)
7219 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007220 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007221
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007222 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00007223 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007224 << OpTy << Op->getSourceRange();
7225 return QualType();
7226 }
John McCall09431682010-11-18 19:01:18 +00007227
7228 // Dereferences are usually l-values...
7229 VK = VK_LValue;
7230
7231 // ...except that certain expressions are never l-values in C.
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00007232 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00007233 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007234
7235 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00007236}
7237
John McCall2de56d12010-08-25 11:45:40 +00007238static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007239 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007240 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007241 switch (Kind) {
7242 default: assert(0 && "Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00007243 case tok::periodstar: Opc = BO_PtrMemD; break;
7244 case tok::arrowstar: Opc = BO_PtrMemI; break;
7245 case tok::star: Opc = BO_Mul; break;
7246 case tok::slash: Opc = BO_Div; break;
7247 case tok::percent: Opc = BO_Rem; break;
7248 case tok::plus: Opc = BO_Add; break;
7249 case tok::minus: Opc = BO_Sub; break;
7250 case tok::lessless: Opc = BO_Shl; break;
7251 case tok::greatergreater: Opc = BO_Shr; break;
7252 case tok::lessequal: Opc = BO_LE; break;
7253 case tok::less: Opc = BO_LT; break;
7254 case tok::greaterequal: Opc = BO_GE; break;
7255 case tok::greater: Opc = BO_GT; break;
7256 case tok::exclaimequal: Opc = BO_NE; break;
7257 case tok::equalequal: Opc = BO_EQ; break;
7258 case tok::amp: Opc = BO_And; break;
7259 case tok::caret: Opc = BO_Xor; break;
7260 case tok::pipe: Opc = BO_Or; break;
7261 case tok::ampamp: Opc = BO_LAnd; break;
7262 case tok::pipepipe: Opc = BO_LOr; break;
7263 case tok::equal: Opc = BO_Assign; break;
7264 case tok::starequal: Opc = BO_MulAssign; break;
7265 case tok::slashequal: Opc = BO_DivAssign; break;
7266 case tok::percentequal: Opc = BO_RemAssign; break;
7267 case tok::plusequal: Opc = BO_AddAssign; break;
7268 case tok::minusequal: Opc = BO_SubAssign; break;
7269 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7270 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7271 case tok::ampequal: Opc = BO_AndAssign; break;
7272 case tok::caretequal: Opc = BO_XorAssign; break;
7273 case tok::pipeequal: Opc = BO_OrAssign; break;
7274 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007275 }
7276 return Opc;
7277}
7278
John McCall2de56d12010-08-25 11:45:40 +00007279static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007280 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007281 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007282 switch (Kind) {
7283 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00007284 case tok::plusplus: Opc = UO_PreInc; break;
7285 case tok::minusminus: Opc = UO_PreDec; break;
7286 case tok::amp: Opc = UO_AddrOf; break;
7287 case tok::star: Opc = UO_Deref; break;
7288 case tok::plus: Opc = UO_Plus; break;
7289 case tok::minus: Opc = UO_Minus; break;
7290 case tok::tilde: Opc = UO_Not; break;
7291 case tok::exclaim: Opc = UO_LNot; break;
7292 case tok::kw___real: Opc = UO_Real; break;
7293 case tok::kw___imag: Opc = UO_Imag; break;
7294 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007295 }
7296 return Opc;
7297}
7298
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007299/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7300/// This warning is only emitted for builtin assignment operations. It is also
7301/// suppressed in the event of macro expansions.
7302static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7303 SourceLocation OpLoc) {
7304 if (!S.ActiveTemplateInstantiations.empty())
7305 return;
7306 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7307 return;
7308 lhs = lhs->IgnoreParenImpCasts();
7309 rhs = rhs->IgnoreParenImpCasts();
7310 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7311 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7312 if (!LeftDeclRef || !RightDeclRef ||
7313 LeftDeclRef->getLocation().isMacroID() ||
7314 RightDeclRef->getLocation().isMacroID())
7315 return;
7316 const ValueDecl *LeftDecl =
7317 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7318 const ValueDecl *RightDecl =
7319 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7320 if (LeftDecl != RightDecl)
7321 return;
7322 if (LeftDecl->getType().isVolatileQualified())
7323 return;
7324 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7325 if (RefTy->getPointeeType().isVolatileQualified())
7326 return;
7327
7328 S.Diag(OpLoc, diag::warn_self_assignment)
7329 << LeftDeclRef->getType()
7330 << lhs->getSourceRange() << rhs->getSourceRange();
7331}
7332
Douglas Gregoreaebc752008-11-06 23:29:22 +00007333/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7334/// operator @p Opc at location @c TokLoc. This routine only supports
7335/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00007336ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007337 BinaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00007338 Expr *lhsExpr, Expr *rhsExpr) {
7339 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007340 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00007341 // The following two variables are used for compound assignment operators
7342 QualType CompLHSTy; // Type of LHS after promotions for computation
7343 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00007344 ExprValueKind VK = VK_RValue;
7345 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00007346
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007347 // Check if a 'foo<int>' involved in a binary op, identifies a single
7348 // function unambiguously (i.e. an lvalue ala 13.4)
7349 // But since an assignment can trigger target based overload, exclude it in
7350 // our blind search. i.e:
7351 // template<class T> void f(); template<class T, class U> void f(U);
7352 // f<int> == 0; // resolve f<int> blindly
7353 // void (*p)(int); p = f<int>; // resolve f<int> using target
7354 if (Opc != BO_Assign) {
John McCallfb8721c2011-04-10 19:13:55 +00007355 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00007356 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00007357 lhs = move(resolvedLHS);
John McCall1de4d4e2011-04-07 08:22:57 +00007358
John McCallfb8721c2011-04-10 19:13:55 +00007359 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00007360 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00007361 rhs = move(resolvedRHS);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007362 }
7363
Eli Friedmaned3b2562011-06-17 20:52:22 +00007364 // The canonical way to check for a GNU null is with isNullPointerConstant,
7365 // but we use a bit of a hack here for speed; this is a relatively
7366 // hot path, and isNullPointerConstant is slow.
7367 bool LeftNull = isa<GNUNullExpr>(lhs.get()->IgnoreParenImpCasts());
7368 bool RightNull = isa<GNUNullExpr>(rhs.get()->IgnoreParenImpCasts());
Richard Trieu3e95ba92011-06-16 21:36:56 +00007369
7370 // Detect when a NULL constant is used improperly in an expression. These
7371 // are mainly cases where the null pointer is used as an integer instead
7372 // of a pointer.
7373 if (LeftNull || RightNull) {
Chandler Carruth1567a8b2011-06-20 07:38:51 +00007374 // Avoid analyzing cases where the result will either be invalid (and
7375 // diagnosed as such) or entirely valid and not something to warn about.
7376 QualType LeftType = lhs.get()->getType();
7377 QualType RightType = rhs.get()->getType();
7378 if (!LeftType->isBlockPointerType() && !LeftType->isMemberPointerType() &&
7379 !LeftType->isFunctionType() &&
7380 !RightType->isBlockPointerType() &&
7381 !RightType->isMemberPointerType() &&
7382 !RightType->isFunctionType()) {
7383 if (Opc == BO_Mul || Opc == BO_Div || Opc == BO_Rem || Opc == BO_Add ||
7384 Opc == BO_Sub || Opc == BO_Shl || Opc == BO_Shr || Opc == BO_And ||
7385 Opc == BO_Xor || Opc == BO_Or || Opc == BO_MulAssign ||
7386 Opc == BO_DivAssign || Opc == BO_AddAssign || Opc == BO_SubAssign ||
7387 Opc == BO_RemAssign || Opc == BO_ShlAssign || Opc == BO_ShrAssign ||
7388 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign) {
7389 // These are the operations that would not make sense with a null pointer
7390 // no matter what the other expression is.
Chandler Carruth2af68e42011-06-19 09:05:14 +00007391 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
Chandler Carruth1567a8b2011-06-20 07:38:51 +00007392 << (LeftNull ? lhs.get()->getSourceRange() : SourceRange())
7393 << (RightNull ? rhs.get()->getSourceRange() : SourceRange());
7394 } else if (Opc == BO_LE || Opc == BO_LT || Opc == BO_GE || Opc == BO_GT ||
7395 Opc == BO_EQ || Opc == BO_NE) {
7396 // These are the operations that would not make sense with a null pointer
7397 // if the other expression the other expression is not a pointer.
7398 if (LeftNull != RightNull &&
7399 !LeftType->isAnyPointerType() &&
7400 !LeftType->canDecayToPointerType() &&
7401 !RightType->isAnyPointerType() &&
7402 !RightType->canDecayToPointerType()) {
7403 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
7404 << (LeftNull ? lhs.get()->getSourceRange()
7405 : rhs.get()->getSourceRange());
7406 }
Richard Trieu3e95ba92011-06-16 21:36:56 +00007407 }
7408 }
7409 }
7410
Douglas Gregoreaebc752008-11-06 23:29:22 +00007411 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007412 case BO_Assign:
John Wiegley429bb272011-04-08 18:41:53 +00007413 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00007414 if (getLangOptions().CPlusPlus &&
John Wiegley429bb272011-04-08 18:41:53 +00007415 lhs.get()->getObjectKind() != OK_ObjCProperty) {
7416 VK = lhs.get()->getValueKind();
7417 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007418 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007419 if (!ResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00007420 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007421 break;
John McCall2de56d12010-08-25 11:45:40 +00007422 case BO_PtrMemD:
7423 case BO_PtrMemI:
John McCallf89e55a2010-11-18 06:31:45 +00007424 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007425 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00007426 break;
John McCall2de56d12010-08-25 11:45:40 +00007427 case BO_Mul:
7428 case BO_Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00007429 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00007430 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007431 break;
John McCall2de56d12010-08-25 11:45:40 +00007432 case BO_Rem:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007433 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7434 break;
John McCall2de56d12010-08-25 11:45:40 +00007435 case BO_Add:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007436 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7437 break;
John McCall2de56d12010-08-25 11:45:40 +00007438 case BO_Sub:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007439 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7440 break;
John McCall2de56d12010-08-25 11:45:40 +00007441 case BO_Shl:
7442 case BO_Shr:
Chandler Carruth21206d52011-02-23 23:34:11 +00007443 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007444 break;
John McCall2de56d12010-08-25 11:45:40 +00007445 case BO_LE:
7446 case BO_LT:
7447 case BO_GE:
7448 case BO_GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00007449 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007450 break;
John McCall2de56d12010-08-25 11:45:40 +00007451 case BO_EQ:
7452 case BO_NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00007453 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007454 break;
John McCall2de56d12010-08-25 11:45:40 +00007455 case BO_And:
7456 case BO_Xor:
7457 case BO_Or:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007458 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7459 break;
John McCall2de56d12010-08-25 11:45:40 +00007460 case BO_LAnd:
7461 case BO_LOr:
Chris Lattner90a8f272010-07-13 19:41:32 +00007462 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007463 break;
John McCall2de56d12010-08-25 11:45:40 +00007464 case BO_MulAssign:
7465 case BO_DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00007466 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00007467 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007468 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00007469 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7470 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007471 break;
John McCall2de56d12010-08-25 11:45:40 +00007472 case BO_RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007473 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7474 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00007475 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7476 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007477 break;
John McCall2de56d12010-08-25 11:45:40 +00007478 case BO_AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007479 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00007480 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7481 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007482 break;
John McCall2de56d12010-08-25 11:45:40 +00007483 case BO_SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007484 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00007485 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7486 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007487 break;
John McCall2de56d12010-08-25 11:45:40 +00007488 case BO_ShlAssign:
7489 case BO_ShrAssign:
Chandler Carruth21206d52011-02-23 23:34:11 +00007490 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007491 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00007492 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7493 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007494 break;
John McCall2de56d12010-08-25 11:45:40 +00007495 case BO_AndAssign:
7496 case BO_XorAssign:
7497 case BO_OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007498 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7499 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00007500 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7501 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007502 break;
John McCall2de56d12010-08-25 11:45:40 +00007503 case BO_Comma:
John McCall09431682010-11-18 19:01:18 +00007504 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00007505 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
7506 VK = rhs.get()->getValueKind();
7507 OK = rhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007508 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00007509 break;
7510 }
John Wiegley429bb272011-04-08 18:41:53 +00007511 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00007512 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00007513 if (CompResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00007514 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
7515 ResultTy, VK, OK, OpLoc));
7516 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00007517 VK = VK_LValue;
John Wiegley429bb272011-04-08 18:41:53 +00007518 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007519 }
John Wiegley429bb272011-04-08 18:41:53 +00007520 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
7521 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00007522 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00007523}
7524
Sebastian Redlaee3c932009-10-27 12:10:02 +00007525/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7526/// operators are mixed in a way that suggests that the programmer forgot that
7527/// comparison operators have higher precedence. The most typical example of
7528/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00007529static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007530 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00007531 typedef BinaryOperator BinOp;
7532 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7533 rhsopc = static_cast<BinOp::Opcode>(-1);
7534 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007535 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00007536 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007537 rhsopc = BO->getOpcode();
7538
7539 // Subs are not binary operators.
7540 if (lhsopc == -1 && rhsopc == -1)
7541 return;
7542
7543 // Bitwise operations are sometimes used as eager logical ops.
7544 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00007545 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7546 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007547 return;
7548
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007549 if (BinOp::isComparisonOp(lhsopc)) {
7550 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7551 << SourceRange(lhs->getLocStart(), OpLoc)
7552 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc);
Sebastian Redl6b169ac2009-10-26 17:01:32 +00007553 SuggestParentheses(Self, OpLoc,
Douglas Gregor55b38842010-04-14 16:09:52 +00007554 Self.PDiag(diag::note_precedence_bitwise_silence)
7555 << BinOp::getOpcodeStr(lhsopc),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007556 lhs->getSourceRange());
7557 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00007558 Self.PDiag(diag::note_precedence_bitwise_first)
7559 << BinOp::getOpcodeStr(Opc),
7560 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007561 } else if (BinOp::isComparisonOp(rhsopc)) {
7562 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7563 << SourceRange(OpLoc, rhs->getLocEnd())
7564 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc);
Sebastian Redl6b169ac2009-10-26 17:01:32 +00007565 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00007566 Self.PDiag(diag::note_precedence_bitwise_silence)
7567 << BinOp::getOpcodeStr(rhsopc),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007568 rhs->getSourceRange());
7569 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007570 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00007571 << BinOp::getOpcodeStr(Opc),
Douglas Gregorb27c7a12011-06-22 18:41:08 +00007572 SourceRange(lhs->getLocStart(),
7573 cast<BinOp>(rhs)->getLHS()->getLocStart()));
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007574 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007575}
7576
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00007577/// \brief It accepts a '&' expr that is inside a '|' one.
7578/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7579/// in parentheses.
7580static void
7581EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7582 BinaryOperator *Bop) {
7583 assert(Bop->getOpcode() == BO_And);
7584 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7585 << Bop->getSourceRange() << OpLoc;
7586 SuggestParentheses(Self, Bop->getOperatorLoc(),
7587 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7588 Bop->getSourceRange());
7589}
7590
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007591/// \brief It accepts a '&&' expr that is inside a '||' one.
7592/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7593/// in parentheses.
7594static void
7595EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00007596 BinaryOperator *Bop) {
7597 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007598 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7599 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00007600 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007601 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007602 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007603}
7604
7605/// \brief Returns true if the given expression can be evaluated as a constant
7606/// 'true'.
7607static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7608 bool Res;
7609 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7610}
7611
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007612/// \brief Returns true if the given expression can be evaluated as a constant
7613/// 'false'.
7614static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7615 bool Res;
7616 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7617}
7618
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007619/// \brief Look for '&&' in the left hand of a '||' expr.
7620static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007621 Expr *OrLHS, Expr *OrRHS) {
7622 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007623 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007624 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7625 if (EvaluatesAsFalse(S, OrRHS))
7626 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007627 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7628 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7629 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7630 } else if (Bop->getOpcode() == BO_LOr) {
7631 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7632 // If it's "a || b && 1 || c" we didn't warn earlier for
7633 // "a || b && 1", but warn now.
7634 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7635 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7636 }
7637 }
7638 }
7639}
7640
7641/// \brief Look for '&&' in the right hand of a '||' expr.
7642static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007643 Expr *OrLHS, Expr *OrRHS) {
7644 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007645 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007646 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7647 if (EvaluatesAsFalse(S, OrLHS))
7648 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007649 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7650 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7651 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007652 }
7653 }
7654}
7655
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00007656/// \brief Look for '&' in the left or right hand of a '|' expr.
7657static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7658 Expr *OrArg) {
7659 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7660 if (Bop->getOpcode() == BO_And)
7661 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7662 }
7663}
7664
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007665/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007666/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00007667static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007668 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007669 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00007670 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00007671 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7672
7673 // Diagnose "arg1 & arg2 | arg3"
7674 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7675 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, lhs);
7676 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, rhs);
7677 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007678
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007679 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7680 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00007681 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007682 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7683 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007684 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007685}
7686
Reid Spencer5f016e22007-07-11 17:01:13 +00007687// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00007688ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00007689 tok::TokenKind Kind,
7690 Expr *lhs, Expr *rhs) {
7691 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Narofff69936d2007-09-16 03:34:24 +00007692 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
7693 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007694
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007695 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7696 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
7697
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007698 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
7699}
7700
John McCall60d7b3a2010-08-24 06:29:42 +00007701ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007702 BinaryOperatorKind Opc,
7703 Expr *lhs, Expr *rhs) {
John McCall01b2e4e2010-12-06 05:26:58 +00007704 if (getLangOptions().CPlusPlus) {
7705 bool UseBuiltinOperator;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007706
John McCall01b2e4e2010-12-06 05:26:58 +00007707 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
7708 UseBuiltinOperator = false;
7709 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
7710 UseBuiltinOperator = true;
7711 } else {
7712 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
7713 !rhs->getType()->isOverloadableType();
7714 }
7715
7716 if (!UseBuiltinOperator) {
7717 // Find all of the overloaded operators visible from this
7718 // point. We perform both an operator-name lookup from the local
7719 // scope and an argument-dependent lookup based on the types of
7720 // the arguments.
7721 UnresolvedSet<16> Functions;
7722 OverloadedOperatorKind OverOp
7723 = BinaryOperator::getOverloadedOperator(Opc);
7724 if (S && OverOp != OO_None)
7725 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
7726 Functions);
7727
7728 // Build the (potentially-overloaded, potentially-dependent)
7729 // binary operation.
7730 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
7731 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00007732 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007733
Douglas Gregoreaebc752008-11-06 23:29:22 +00007734 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007735 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00007736}
7737
John McCall60d7b3a2010-08-24 06:29:42 +00007738ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007739 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00007740 Expr *InputExpr) {
7741 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00007742 ExprValueKind VK = VK_RValue;
7743 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00007744 QualType resultType;
7745 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007746 case UO_PreInc:
7747 case UO_PreDec:
7748 case UO_PostInc:
7749 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00007750 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007751 Opc == UO_PreInc ||
7752 Opc == UO_PostInc,
7753 Opc == UO_PreInc ||
7754 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00007755 break;
John McCall2de56d12010-08-25 11:45:40 +00007756 case UO_AddrOf:
John Wiegley429bb272011-04-08 18:41:53 +00007757 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00007758 break;
John McCall1de4d4e2011-04-07 08:22:57 +00007759 case UO_Deref: {
John McCallfb8721c2011-04-10 19:13:55 +00007760 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall1de4d4e2011-04-07 08:22:57 +00007761 if (!resolved.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00007762 Input = move(resolved);
7763 Input = DefaultFunctionArrayLvalueConversion(Input.take());
7764 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00007765 break;
John McCall1de4d4e2011-04-07 08:22:57 +00007766 }
John McCall2de56d12010-08-25 11:45:40 +00007767 case UO_Plus:
7768 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00007769 Input = UsualUnaryConversions(Input.take());
7770 if (Input.isInvalid()) return ExprError();
7771 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00007772 if (resultType->isDependentType())
7773 break;
Douglas Gregor00619622010-06-22 23:41:02 +00007774 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
7775 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00007776 break;
7777 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
7778 resultType->isEnumeralType())
7779 break;
7780 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00007781 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00007782 resultType->isPointerType())
7783 break;
John McCall2cd11fe2010-10-12 02:09:17 +00007784 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007785 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00007786 if (Input.isInvalid()) return ExprError();
7787 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00007788 }
Douglas Gregor74253732008-11-19 15:42:04 +00007789
Sebastian Redl0eb23302009-01-19 00:08:26 +00007790 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00007791 << resultType << Input.get()->getSourceRange());
7792
John McCall2de56d12010-08-25 11:45:40 +00007793 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00007794 Input = UsualUnaryConversions(Input.take());
7795 if (Input.isInvalid()) return ExprError();
7796 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00007797 if (resultType->isDependentType())
7798 break;
Chris Lattner02a65142008-07-25 23:52:49 +00007799 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
7800 if (resultType->isComplexType() || resultType->isComplexIntegerType())
7801 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007802 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00007803 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007804 else if (resultType->hasIntegerRepresentation())
7805 break;
7806 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007807 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00007808 if (Input.isInvalid()) return ExprError();
7809 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00007810 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00007811 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00007812 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00007813 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007814 break;
John Wiegley429bb272011-04-08 18:41:53 +00007815
John McCall2de56d12010-08-25 11:45:40 +00007816 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00007817 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00007818 Input = DefaultFunctionArrayLvalueConversion(Input.take());
7819 if (Input.isInvalid()) return ExprError();
7820 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00007821 if (resultType->isDependentType())
7822 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00007823 if (resultType->isScalarType()) {
7824 // C99 6.5.3.3p1: ok, fallthrough;
7825 if (Context.getLangOptions().CPlusPlus) {
7826 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
7827 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00007828 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
7829 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00007830 }
John McCall2cd11fe2010-10-12 02:09:17 +00007831 } else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007832 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00007833 if (Input.isInvalid()) return ExprError();
7834 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00007835 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00007836 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00007837 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00007838 }
Douglas Gregorea844f32010-09-20 17:13:33 +00007839
Reid Spencer5f016e22007-07-11 17:01:13 +00007840 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00007841 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00007842 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007843 break;
John McCall2de56d12010-08-25 11:45:40 +00007844 case UO_Real:
7845 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00007846 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00007847 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley429bb272011-04-08 18:41:53 +00007848 if (Input.isInvalid()) return ExprError();
7849 if (Input.get()->getValueKind() != VK_RValue &&
7850 Input.get()->getObjectKind() == OK_Ordinary)
7851 VK = Input.get()->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00007852 break;
John McCall2de56d12010-08-25 11:45:40 +00007853 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00007854 resultType = Input.get()->getType();
7855 VK = Input.get()->getValueKind();
7856 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00007857 break;
7858 }
John Wiegley429bb272011-04-08 18:41:53 +00007859 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00007860 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007861
John Wiegley429bb272011-04-08 18:41:53 +00007862 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00007863 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00007864}
7865
John McCall60d7b3a2010-08-24 06:29:42 +00007866ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007867 UnaryOperatorKind Opc,
7868 Expr *Input) {
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00007869 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00007870 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007871 // Find all of the overloaded operators visible from this
7872 // point. We perform both an operator-name lookup from the local
7873 // scope and an argument-dependent lookup based on the types of
7874 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00007875 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007876 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00007877 if (S && OverOp != OO_None)
7878 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
7879 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007880
John McCall9ae2f072010-08-23 23:25:46 +00007881 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007882 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007883
John McCall9ae2f072010-08-23 23:25:46 +00007884 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007885}
7886
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007887// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00007888ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00007889 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00007890 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007891}
7892
Steve Naroff1b273c42007-09-16 14:56:35 +00007893/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00007894ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00007895 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00007896 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00007897 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00007898 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00007899 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00007900}
7901
John McCallf85e1932011-06-15 23:02:42 +00007902/// Given the last statement in a statement-expression, check whether
7903/// the result is a producing expression (like a call to an
7904/// ns_returns_retained function) and, if so, rebuild it to hoist the
7905/// release out of the full-expression. Otherwise, return null.
7906/// Cannot fail.
7907static Expr *maybeRebuildARCConsumingStmt(Stmt *s) {
7908 // Should always be wrapped with one of these.
7909 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(s);
7910 if (!cleanups) return 0;
7911
7912 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
7913 if (!cast || cast->getCastKind() != CK_ObjCConsumeObject)
7914 return 0;
7915
7916 // Splice out the cast. This shouldn't modify any interesting
7917 // features of the statement.
7918 Expr *producer = cast->getSubExpr();
7919 assert(producer->getType() == cast->getType());
7920 assert(producer->getValueKind() == cast->getValueKind());
7921 cleanups->setSubExpr(producer);
7922 return cleanups;
7923}
7924
John McCall60d7b3a2010-08-24 06:29:42 +00007925ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00007926Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00007927 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00007928 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
7929 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
7930
Douglas Gregordd8f5692010-03-10 04:54:39 +00007931 bool isFileScope
7932 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00007933 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00007934 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00007935
Chris Lattnerab18c4c2007-07-24 16:58:17 +00007936 // FIXME: there are a variety of strange constraints to enforce here, for
7937 // example, it is not possible to goto into a stmt expression apparently.
7938 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007939
Chris Lattnerab18c4c2007-07-24 16:58:17 +00007940 // If there are sub stmts in the compound stmt, take the type of the last one
7941 // as the type of the stmtexpr.
7942 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00007943 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00007944 if (!Compound->body_empty()) {
7945 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00007946 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00007947 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00007948 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
7949 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00007950 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00007951 }
John McCallf85e1932011-06-15 23:02:42 +00007952
John Wiegley429bb272011-04-08 18:41:53 +00007953 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00007954 // Do function/array conversion on the last expression, but not
7955 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00007956 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
7957 if (LastExpr.isInvalid())
7958 return ExprError();
7959 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00007960
John Wiegley429bb272011-04-08 18:41:53 +00007961 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00007962 // In ARC, if the final expression ends in a consume, splice
7963 // the consume out and bind it later. In the alternate case
7964 // (when dealing with a retainable type), the result
7965 // initialization will create a produce. In both cases the
7966 // result will be +1, and we'll need to balance that out with
7967 // a bind.
7968 if (Expr *rebuiltLastStmt
7969 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
7970 LastExpr = rebuiltLastStmt;
7971 } else {
7972 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00007973 InitializedEntity::InitializeResult(LPLoc,
7974 Ty,
7975 false),
7976 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00007977 LastExpr);
7978 }
7979
John Wiegley429bb272011-04-08 18:41:53 +00007980 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00007981 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00007982 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00007983 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00007984 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00007985 else
John Wiegley429bb272011-04-08 18:41:53 +00007986 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00007987 StmtExprMayBindToTemp = true;
7988 }
7989 }
7990 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00007991 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007992
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007993 // FIXME: Check that expression type is complete/non-abstract; statement
7994 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00007995 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
7996 if (StmtExprMayBindToTemp)
7997 return MaybeBindToTemporary(ResStmtExpr);
7998 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00007999}
Steve Naroffd34e9152007-08-01 22:05:33 +00008000
John McCall60d7b3a2010-08-24 06:29:42 +00008001ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008002 TypeSourceInfo *TInfo,
8003 OffsetOfComponent *CompPtr,
8004 unsigned NumComponents,
8005 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008006 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008007 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008008 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008009
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008010 // We must have at least one component that refers to the type, and the first
8011 // one is known to be a field designator. Verify that the ArgTy represents
8012 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00008013 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008014 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8015 << ArgTy << TypeRange);
8016
8017 // Type must be complete per C99 7.17p3 because a declaring a variable
8018 // with an incomplete type would be ill-formed.
8019 if (!Dependent
8020 && RequireCompleteType(BuiltinLoc, ArgTy,
8021 PDiag(diag::err_offsetof_incomplete_type)
8022 << TypeRange))
8023 return ExprError();
8024
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008025 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8026 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00008027 // FIXME: This diagnostic isn't actually visible because the location is in
8028 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008029 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008030 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8031 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008032
8033 bool DidWarnAboutNonPOD = false;
8034 QualType CurrentType = ArgTy;
8035 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8036 llvm::SmallVector<OffsetOfNode, 4> Comps;
8037 llvm::SmallVector<Expr*, 4> Exprs;
8038 for (unsigned i = 0; i != NumComponents; ++i) {
8039 const OffsetOfComponent &OC = CompPtr[i];
8040 if (OC.isBrackets) {
8041 // Offset of an array sub-field. TODO: Should we allow vector elements?
8042 if (!CurrentType->isDependentType()) {
8043 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8044 if(!AT)
8045 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8046 << CurrentType);
8047 CurrentType = AT->getElementType();
8048 } else
8049 CurrentType = Context.DependentTy;
8050
8051 // The expression must be an integral expression.
8052 // FIXME: An integral constant expression?
8053 Expr *Idx = static_cast<Expr*>(OC.U.E);
8054 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8055 !Idx->getType()->isIntegerType())
8056 return ExprError(Diag(Idx->getLocStart(),
8057 diag::err_typecheck_subscript_not_integer)
8058 << Idx->getSourceRange());
8059
8060 // Record this array index.
8061 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8062 Exprs.push_back(Idx);
8063 continue;
8064 }
8065
8066 // Offset of a field.
8067 if (CurrentType->isDependentType()) {
8068 // We have the offset of a field, but we can't look into the dependent
8069 // type. Just record the identifier of the field.
8070 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8071 CurrentType = Context.DependentTy;
8072 continue;
8073 }
8074
8075 // We need to have a complete type to look into.
8076 if (RequireCompleteType(OC.LocStart, CurrentType,
8077 diag::err_offsetof_incomplete_type))
8078 return ExprError();
8079
8080 // Look for the designated field.
8081 const RecordType *RC = CurrentType->getAs<RecordType>();
8082 if (!RC)
8083 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8084 << CurrentType);
8085 RecordDecl *RD = RC->getDecl();
8086
8087 // C++ [lib.support.types]p5:
8088 // The macro offsetof accepts a restricted set of type arguments in this
8089 // International Standard. type shall be a POD structure or a POD union
8090 // (clause 9).
8091 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8092 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00008093 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008094 PDiag(diag::warn_offsetof_non_pod_type)
8095 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8096 << CurrentType))
8097 DidWarnAboutNonPOD = true;
8098 }
8099
8100 // Look for the field.
8101 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8102 LookupQualifiedName(R, RD);
8103 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00008104 IndirectFieldDecl *IndirectMemberDecl = 0;
8105 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00008106 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00008107 MemberDecl = IndirectMemberDecl->getAnonField();
8108 }
8109
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008110 if (!MemberDecl)
8111 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8112 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8113 OC.LocEnd));
8114
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00008115 // C99 7.17p3:
8116 // (If the specified member is a bit-field, the behavior is undefined.)
8117 //
8118 // We diagnose this as an error.
8119 if (MemberDecl->getBitWidth()) {
8120 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8121 << MemberDecl->getDeclName()
8122 << SourceRange(BuiltinLoc, RParenLoc);
8123 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8124 return ExprError();
8125 }
Eli Friedman19410a72010-08-05 10:11:36 +00008126
8127 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00008128 if (IndirectMemberDecl)
8129 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00008130
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008131 // If the member was found in a base class, introduce OffsetOfNodes for
8132 // the base class indirections.
8133 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8134 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00008135 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008136 CXXBasePath &Path = Paths.front();
8137 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8138 B != BEnd; ++B)
8139 Comps.push_back(OffsetOfNode(B->Base));
8140 }
Eli Friedman19410a72010-08-05 10:11:36 +00008141
Francois Pichet87c2e122010-11-21 06:08:52 +00008142 if (IndirectMemberDecl) {
8143 for (IndirectFieldDecl::chain_iterator FI =
8144 IndirectMemberDecl->chain_begin(),
8145 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8146 assert(isa<FieldDecl>(*FI));
8147 Comps.push_back(OffsetOfNode(OC.LocStart,
8148 cast<FieldDecl>(*FI), OC.LocEnd));
8149 }
8150 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008151 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00008152
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008153 CurrentType = MemberDecl->getType().getNonReferenceType();
8154 }
8155
8156 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8157 TInfo, Comps.data(), Comps.size(),
8158 Exprs.data(), Exprs.size(), RParenLoc));
8159}
Mike Stumpeed9cac2009-02-19 03:04:26 +00008160
John McCall60d7b3a2010-08-24 06:29:42 +00008161ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00008162 SourceLocation BuiltinLoc,
8163 SourceLocation TypeLoc,
8164 ParsedType argty,
8165 OffsetOfComponent *CompPtr,
8166 unsigned NumComponents,
8167 SourceLocation RPLoc) {
8168
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008169 TypeSourceInfo *ArgTInfo;
8170 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8171 if (ArgTy.isNull())
8172 return ExprError();
8173
Eli Friedman5a15dc12010-08-05 10:15:45 +00008174 if (!ArgTInfo)
8175 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8176
8177 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8178 RPLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008179}
8180
8181
John McCall60d7b3a2010-08-24 06:29:42 +00008182ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008183 Expr *CondExpr,
8184 Expr *LHSExpr, Expr *RHSExpr,
8185 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00008186 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8187
John McCallf89e55a2010-11-18 06:31:45 +00008188 ExprValueKind VK = VK_RValue;
8189 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00008190 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00008191 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00008192 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00008193 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00008194 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00008195 } else {
8196 // The conditional expression is required to be a constant expression.
8197 llvm::APSInt condEval(32);
8198 SourceLocation ExpLoc;
8199 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00008200 return ExprError(Diag(ExpLoc,
8201 diag::err_typecheck_choose_expr_requires_constant)
8202 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00008203
Sebastian Redl28507842009-02-26 14:39:58 +00008204 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00008205 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8206
8207 resType = ActiveExpr->getType();
8208 ValueDependent = ActiveExpr->isValueDependent();
8209 VK = ActiveExpr->getValueKind();
8210 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00008211 }
8212
Sebastian Redlf53597f2009-03-15 17:47:39 +00008213 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00008214 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00008215 resType->isDependentType(),
8216 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00008217}
8218
Steve Naroff4eb206b2008-09-03 18:15:37 +00008219//===----------------------------------------------------------------------===//
8220// Clang Extensions.
8221//===----------------------------------------------------------------------===//
8222
8223/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00008224void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008225 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8226 PushBlockScope(BlockScope, Block);
8227 CurContext->addDecl(Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008228 if (BlockScope)
8229 PushDeclContext(BlockScope, Block);
8230 else
8231 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00008232}
8233
Mike Stump98eb8a72009-02-04 22:31:32 +00008234void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00008235 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00008236 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008237 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008238
John McCallbf1a0282010-06-04 23:28:52 +00008239 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00008240 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00008241
John McCall711c52b2011-01-05 12:14:39 +00008242 // GetTypeForDeclarator always produces a function type for a block
8243 // literal signature. Furthermore, it is always a FunctionProtoType
8244 // unless the function was written with a typedef.
8245 assert(T->isFunctionType() &&
8246 "GetTypeForDeclarator made a non-function block signature");
8247
8248 // Look for an explicit signature in that function type.
8249 FunctionProtoTypeLoc ExplicitSignature;
8250
8251 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8252 if (isa<FunctionProtoTypeLoc>(tmp)) {
8253 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8254
8255 // Check whether that explicit signature was synthesized by
8256 // GetTypeForDeclarator. If so, don't save that as part of the
8257 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00008258 if (ExplicitSignature.getLocalRangeBegin() ==
8259 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00008260 // This would be much cheaper if we stored TypeLocs instead of
8261 // TypeSourceInfos.
8262 TypeLoc Result = ExplicitSignature.getResultLoc();
8263 unsigned Size = Result.getFullDataSize();
8264 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8265 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8266
8267 ExplicitSignature = FunctionProtoTypeLoc();
8268 }
John McCall82dc0092010-06-04 11:21:44 +00008269 }
Mike Stump1eb44332009-09-09 15:08:12 +00008270
John McCall711c52b2011-01-05 12:14:39 +00008271 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8272 CurBlock->FunctionType = T;
8273
8274 const FunctionType *Fn = T->getAs<FunctionType>();
8275 QualType RetTy = Fn->getResultType();
8276 bool isVariadic =
8277 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8278
John McCallc71a4912010-06-04 19:02:56 +00008279 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00008280
John McCall82dc0092010-06-04 11:21:44 +00008281 // Don't allow returning a objc interface by value.
8282 if (RetTy->isObjCObjectType()) {
8283 Diag(ParamInfo.getSourceRange().getBegin(),
8284 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8285 return;
8286 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008287
John McCall82dc0092010-06-04 11:21:44 +00008288 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00008289 // return type. TODO: what should we do with declarators like:
8290 // ^ * { ... }
8291 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00008292 if (RetTy != Context.DependentTy)
8293 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008294
John McCall82dc0092010-06-04 11:21:44 +00008295 // Push block parameters from the declarator if we had them.
John McCallc71a4912010-06-04 19:02:56 +00008296 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00008297 if (ExplicitSignature) {
8298 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8299 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008300 if (Param->getIdentifier() == 0 &&
8301 !Param->isImplicit() &&
8302 !Param->isInvalidDecl() &&
8303 !getLangOptions().CPlusPlus)
8304 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00008305 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008306 }
John McCall82dc0092010-06-04 11:21:44 +00008307
8308 // Fake up parameter variables if we have a typedef, like
8309 // ^ fntype { ... }
8310 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8311 for (FunctionProtoType::arg_type_iterator
8312 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8313 ParmVarDecl *Param =
8314 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8315 ParamInfo.getSourceRange().getBegin(),
8316 *I);
John McCallc71a4912010-06-04 19:02:56 +00008317 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00008318 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008319 }
John McCall82dc0092010-06-04 11:21:44 +00008320
John McCallc71a4912010-06-04 19:02:56 +00008321 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00008322 if (!Params.empty()) {
John McCallc71a4912010-06-04 19:02:56 +00008323 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregor82aa7132010-11-01 18:37:59 +00008324 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8325 CurBlock->TheDecl->param_end(),
8326 /*CheckParameterNames=*/false);
8327 }
8328
John McCall82dc0092010-06-04 11:21:44 +00008329 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00008330 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00008331
John McCallc71a4912010-06-04 19:02:56 +00008332 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00008333 Diag(ParamInfo.getAttributes()->getLoc(),
8334 diag::warn_attribute_sentinel_not_variadic) << 1;
8335 // FIXME: remove the attribute.
8336 }
8337
8338 // Put the parameter variables in scope. We can bail out immediately
8339 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00008340 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00008341 return;
8342
Steve Naroff090276f2008-10-10 01:28:17 +00008343 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00008344 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8345 (*AI)->setOwningFunction(CurBlock->TheDecl);
8346
Steve Naroff090276f2008-10-10 01:28:17 +00008347 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00008348 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00008349 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00008350
Steve Naroff090276f2008-10-10 01:28:17 +00008351 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00008352 }
John McCall7a9813c2010-01-22 00:28:27 +00008353 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008354}
8355
8356/// ActOnBlockError - If there is an error parsing a block, this callback
8357/// is invoked to pop the information about the block from the action impl.
8358void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00008359 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00008360 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008361 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008362}
8363
8364/// ActOnBlockStmtExpr - This is called when the body of a block statement
8365/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00008366ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00008367 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00008368 // If blocks are disabled, emit an error.
8369 if (!LangOpts.Blocks)
8370 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00008371
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008372 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008373
Steve Naroff090276f2008-10-10 01:28:17 +00008374 PopDeclContext();
8375
Steve Naroff4eb206b2008-09-03 18:15:37 +00008376 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00008377 if (!BSI->ReturnType.isNull())
8378 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008379
Mike Stump56925862009-07-28 22:04:01 +00008380 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008381 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00008382
John McCall469a1eb2011-02-02 13:00:07 +00008383 // Set the captured variables on the block.
John McCall6b5a61b2011-02-07 10:33:21 +00008384 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8385 BSI->CapturesCXXThis);
John McCall469a1eb2011-02-02 13:00:07 +00008386
John McCallc71a4912010-06-04 19:02:56 +00008387 // If the user wrote a function type in some form, try to use that.
8388 if (!BSI->FunctionType.isNull()) {
8389 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8390
8391 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8392 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8393
8394 // Turn protoless block types into nullary block types.
8395 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00008396 FunctionProtoType::ExtProtoInfo EPI;
8397 EPI.ExtInfo = Ext;
8398 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008399
8400 // Otherwise, if we don't need to change anything about the function type,
8401 // preserve its sugar structure.
8402 } else if (FTy->getResultType() == RetTy &&
8403 (!NoReturn || FTy->getNoReturnAttr())) {
8404 BlockTy = BSI->FunctionType;
8405
8406 // Otherwise, make the minimal modifications to the function type.
8407 } else {
8408 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00008409 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8410 EPI.TypeQuals = 0; // FIXME: silently?
8411 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00008412 BlockTy = Context.getFunctionType(RetTy,
8413 FPT->arg_type_begin(),
8414 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00008415 EPI);
John McCallc71a4912010-06-04 19:02:56 +00008416 }
8417
8418 // If we don't have a function type, just build one from nothing.
8419 } else {
John McCalle23cf432010-12-14 08:05:40 +00008420 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00008421 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00008422 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008423 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008424
John McCallc71a4912010-06-04 19:02:56 +00008425 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8426 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00008427 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008428
Chris Lattner17a78302009-04-19 05:28:12 +00008429 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00008430 if (getCurFunction()->NeedsScopeChecking() &&
8431 !hasAnyUnrecoverableErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00008432 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00008433
Chris Lattnere476bdc2011-02-17 23:58:47 +00008434 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008435
John McCall469a1eb2011-02-02 13:00:07 +00008436 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCalle0054f62010-08-25 05:56:39 +00008437
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00008438 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8439 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008440 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00008441}
8442
John McCall60d7b3a2010-08-24 06:29:42 +00008443ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallb3d87482010-08-24 05:47:05 +00008444 Expr *expr, ParsedType type,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008445 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008446 TypeSourceInfo *TInfo;
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008447 GetTypeFromParser(type, &TInfo);
John McCall9ae2f072010-08-23 23:25:46 +00008448 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008449}
8450
John McCall60d7b3a2010-08-24 06:29:42 +00008451ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00008452 Expr *E, TypeSourceInfo *TInfo,
8453 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008454 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00008455
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008456 // Get the va_list type
8457 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008458 if (VaListType->isArrayType()) {
8459 // Deal with implicit array decay; for example, on x86-64,
8460 // va_list is an array, but it's supposed to decay to
8461 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008462 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00008463 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00008464 ExprResult Result = UsualUnaryConversions(E);
8465 if (Result.isInvalid())
8466 return ExprError();
8467 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008468 } else {
8469 // Otherwise, the va_list argument must be an l-value because
8470 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00008471 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00008472 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00008473 return ExprError();
8474 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008475
Douglas Gregordd027302009-05-19 23:10:31 +00008476 if (!E->isTypeDependent() &&
8477 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00008478 return ExprError(Diag(E->getLocStart(),
8479 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008480 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00008481 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008482
David Majnemer0adde122011-06-14 05:17:32 +00008483 if (!TInfo->getType()->isDependentType()) {
8484 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8485 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8486 << TInfo->getTypeLoc().getSourceRange()))
8487 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00008488
David Majnemer0adde122011-06-14 05:17:32 +00008489 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8490 TInfo->getType(),
8491 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8492 << TInfo->getTypeLoc().getSourceRange()))
8493 return ExprError();
8494
John McCallf85e1932011-06-15 23:02:42 +00008495 if (!TInfo->getType().isPODType(Context))
David Majnemer0adde122011-06-14 05:17:32 +00008496 Diag(TInfo->getTypeLoc().getBeginLoc(),
8497 diag::warn_second_parameter_to_va_arg_not_pod)
8498 << TInfo->getType()
8499 << TInfo->getTypeLoc().getSourceRange();
8500 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008501
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008502 QualType T = TInfo->getType().getNonLValueExprType(Context);
8503 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00008504}
8505
John McCall60d7b3a2010-08-24 06:29:42 +00008506ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008507 // The type of __null will be int or long, depending on the size of
8508 // pointers on the target.
8509 QualType Ty;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008510 unsigned pw = Context.Target.getPointerWidth(0);
8511 if (pw == Context.Target.getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008512 Ty = Context.IntTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008513 else if (pw == Context.Target.getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008514 Ty = Context.LongTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008515 else if (pw == Context.Target.getLongLongWidth())
8516 Ty = Context.LongLongTy;
8517 else {
8518 assert(!"I don't know size of pointer!");
8519 Ty = Context.IntTy;
8520 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008521
Sebastian Redlf53597f2009-03-15 17:47:39 +00008522 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008523}
8524
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008525static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00008526 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008527 if (!SemaRef.getLangOptions().ObjC1)
8528 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008529
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008530 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8531 if (!PT)
8532 return;
8533
8534 // Check if the destination is of type 'id'.
8535 if (!PT->isObjCIdType()) {
8536 // Check if the destination is the 'NSString' interface.
8537 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8538 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8539 return;
8540 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008541
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008542 // Strip off any parens and casts.
8543 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
8544 if (!SL || SL->isWide())
8545 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008546
Douglas Gregor849b2432010-03-31 17:46:05 +00008547 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008548}
8549
Chris Lattner5cf216b2008-01-04 18:04:52 +00008550bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8551 SourceLocation Loc,
8552 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00008553 Expr *SrcExpr, AssignmentAction Action,
8554 bool *Complained) {
8555 if (Complained)
8556 *Complained = false;
8557
Chris Lattner5cf216b2008-01-04 18:04:52 +00008558 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00008559 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008560 bool isInvalid = false;
8561 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00008562 FixItHint Hint;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008563
Chris Lattner5cf216b2008-01-04 18:04:52 +00008564 switch (ConvTy) {
8565 default: assert(0 && "Unknown conversion type");
8566 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008567 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00008568 DiagKind = diag::ext_typecheck_convert_pointer_int;
8569 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008570 case IntToPointer:
8571 DiagKind = diag::ext_typecheck_convert_int_pointer;
8572 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008573 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00008574 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00008575 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00008576 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
8577 SrcType->isObjCObjectPointerType();
Chris Lattner5cf216b2008-01-04 18:04:52 +00008578 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00008579 case IncompatiblePointerSign:
8580 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8581 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008582 case FunctionVoidPointer:
8583 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8584 break;
John McCall86c05f32011-02-01 00:10:29 +00008585 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00008586 // Perform array-to-pointer decay if necessary.
8587 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8588
John McCall86c05f32011-02-01 00:10:29 +00008589 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8590 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8591 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8592 DiagKind = diag::err_typecheck_incompatible_address_space;
8593 break;
John McCallf85e1932011-06-15 23:02:42 +00008594
8595
8596 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
8597 DiagKind = diag::err_typecheck_incompatible_lifetime;
8598 break;
John McCall86c05f32011-02-01 00:10:29 +00008599 }
8600
8601 llvm_unreachable("unknown error case for discarding qualifiers!");
8602 // fallthrough
8603 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00008604 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00008605 // If the qualifiers lost were because we were applying the
8606 // (deprecated) C++ conversion from a string literal to a char*
8607 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8608 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00008609 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00008610 // bit of refactoring (so that the second argument is an
8611 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00008612 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00008613 // C++ semantics.
8614 if (getLangOptions().CPlusPlus &&
8615 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8616 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008617 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8618 break;
Sean Huntc9132b62009-11-08 07:46:34 +00008619 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00008620 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00008621 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00008622 case IntToBlockPointer:
8623 DiagKind = diag::err_int_to_block_pointer;
8624 break;
8625 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00008626 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00008627 break;
Steve Naroff39579072008-10-14 22:18:38 +00008628 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00008629 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00008630 // it can give a more specific diagnostic.
8631 DiagKind = diag::warn_incompatible_qualified_id;
8632 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00008633 case IncompatibleVectors:
8634 DiagKind = diag::warn_incompatible_vectors;
8635 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008636 case Incompatible:
8637 DiagKind = diag::err_typecheck_convert_incompatible;
8638 isInvalid = true;
8639 break;
8640 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008641
Douglas Gregord4eea832010-04-09 00:35:39 +00008642 QualType FirstType, SecondType;
8643 switch (Action) {
8644 case AA_Assigning:
8645 case AA_Initializing:
8646 // The destination type comes first.
8647 FirstType = DstType;
8648 SecondType = SrcType;
8649 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008650
Douglas Gregord4eea832010-04-09 00:35:39 +00008651 case AA_Returning:
8652 case AA_Passing:
8653 case AA_Converting:
8654 case AA_Sending:
8655 case AA_Casting:
8656 // The source type comes first.
8657 FirstType = SrcType;
8658 SecondType = DstType;
8659 break;
8660 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008661
Douglas Gregord4eea832010-04-09 00:35:39 +00008662 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008663 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor926df6c2011-06-11 01:09:30 +00008664 if (CheckInferredResultType)
8665 EmitRelatedResultTypeNote(SrcExpr);
8666
Douglas Gregora41a8c52010-04-22 00:20:18 +00008667 if (Complained)
8668 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008669 return isInvalid;
8670}
Anders Carlssone21555e2008-11-30 19:50:32 +00008671
Chris Lattner3bf68932009-04-25 21:59:05 +00008672bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00008673 llvm::APSInt ICEResult;
8674 if (E->isIntegerConstantExpr(ICEResult, Context)) {
8675 if (Result)
8676 *Result = ICEResult;
8677 return false;
8678 }
8679
Anders Carlssone21555e2008-11-30 19:50:32 +00008680 Expr::EvalResult EvalResult;
8681
Mike Stumpeed9cac2009-02-19 03:04:26 +00008682 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00008683 EvalResult.HasSideEffects) {
8684 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
8685
8686 if (EvalResult.Diag) {
8687 // We only show the note if it's not the usual "invalid subexpression"
8688 // or if it's actually in a subexpression.
8689 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
8690 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
8691 Diag(EvalResult.DiagLoc, EvalResult.Diag);
8692 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008693
Anders Carlssone21555e2008-11-30 19:50:32 +00008694 return true;
8695 }
8696
Eli Friedman3b5ccca2009-04-25 22:26:58 +00008697 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
8698 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00008699
Eli Friedman3b5ccca2009-04-25 22:26:58 +00008700 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00008701 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
8702 != Diagnostic::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +00008703 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008704
Anders Carlssone21555e2008-11-30 19:50:32 +00008705 if (Result)
8706 *Result = EvalResult.Val.getInt();
8707 return false;
8708}
Douglas Gregore0762c92009-06-19 23:52:42 +00008709
Douglas Gregor2afce722009-11-26 00:44:06 +00008710void
Mike Stump1eb44332009-09-09 15:08:12 +00008711Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00008712 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +00008713 ExpressionEvaluationContextRecord(NewContext,
8714 ExprTemporaries.size(),
8715 ExprNeedsCleanups));
8716 ExprNeedsCleanups = false;
Douglas Gregorac7610d2009-06-22 20:57:11 +00008717}
8718
Mike Stump1eb44332009-09-09 15:08:12 +00008719void
Douglas Gregor2afce722009-11-26 00:44:06 +00008720Sema::PopExpressionEvaluationContext() {
8721 // Pop the current expression evaluation context off the stack.
8722 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
8723 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00008724
Douglas Gregor06d33692009-12-12 07:57:52 +00008725 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
8726 if (Rec.PotentiallyReferenced) {
8727 // Mark any remaining declarations in the current position of the stack
8728 // as "referenced". If they were not meant to be referenced, semantic
8729 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008730 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00008731 I = Rec.PotentiallyReferenced->begin(),
8732 IEnd = Rec.PotentiallyReferenced->end();
8733 I != IEnd; ++I)
8734 MarkDeclarationReferenced(I->first, I->second);
8735 }
8736
8737 if (Rec.PotentiallyDiagnosed) {
8738 // Emit any pending diagnostics.
8739 for (PotentiallyEmittedDiagnostics::iterator
8740 I = Rec.PotentiallyDiagnosed->begin(),
8741 IEnd = Rec.PotentiallyDiagnosed->end();
8742 I != IEnd; ++I)
8743 Diag(I->first, I->second);
8744 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008745 }
Douglas Gregor2afce722009-11-26 00:44:06 +00008746
8747 // When are coming out of an unevaluated context, clear out any
8748 // temporaries that we may have created as part of the evaluation of
8749 // the expression in that context: they aren't relevant because they
8750 // will never be constructed.
John McCallf85e1932011-06-15 23:02:42 +00008751 if (Rec.Context == Unevaluated) {
Douglas Gregor2afce722009-11-26 00:44:06 +00008752 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
8753 ExprTemporaries.end());
John McCallf85e1932011-06-15 23:02:42 +00008754 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
8755
8756 // Otherwise, merge the contexts together.
8757 } else {
8758 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
8759 }
Douglas Gregor2afce722009-11-26 00:44:06 +00008760
8761 // Destroy the popped expression evaluation record.
8762 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00008763}
Douglas Gregore0762c92009-06-19 23:52:42 +00008764
John McCallf85e1932011-06-15 23:02:42 +00008765void Sema::DiscardCleanupsInEvaluationContext() {
8766 ExprTemporaries.erase(
8767 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
8768 ExprTemporaries.end());
8769 ExprNeedsCleanups = false;
8770}
8771
Douglas Gregore0762c92009-06-19 23:52:42 +00008772/// \brief Note that the given declaration was referenced in the source code.
8773///
8774/// This routine should be invoke whenever a given declaration is referenced
8775/// in the source code, and where that reference occurred. If this declaration
8776/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
8777/// C99 6.9p3), then the declaration will be marked as used.
8778///
8779/// \param Loc the location where the declaration was referenced.
8780///
8781/// \param D the declaration that has been referenced by the source code.
8782void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
8783 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00008784
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +00008785 D->setReferenced();
8786
Douglas Gregorc070cc62010-06-17 23:14:26 +00008787 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00008788 return;
Mike Stump1eb44332009-09-09 15:08:12 +00008789
Douglas Gregorb5352cf2009-10-08 21:35:42 +00008790 // Mark a parameter or variable declaration "used", regardless of whether we're in a
8791 // template or not. The reason for this is that unevaluated expressions
8792 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
8793 // -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008794 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00008795 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +00008796 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +00008797 return;
8798 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008799
Douglas Gregorfc2ca562010-04-07 20:29:57 +00008800 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
8801 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008802
Douglas Gregore0762c92009-06-19 23:52:42 +00008803 // Do not mark anything as "used" within a dependent context; wait for
8804 // an instantiation.
8805 if (CurContext->isDependentContext())
8806 return;
Mike Stump1eb44332009-09-09 15:08:12 +00008807
Douglas Gregor2afce722009-11-26 00:44:06 +00008808 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00008809 case Unevaluated:
8810 // We are in an expression that is not potentially evaluated; do nothing.
8811 return;
Mike Stump1eb44332009-09-09 15:08:12 +00008812
Douglas Gregorac7610d2009-06-22 20:57:11 +00008813 case PotentiallyEvaluated:
8814 // We are in a potentially-evaluated expression, so this declaration is
8815 // "used"; handle this below.
8816 break;
Mike Stump1eb44332009-09-09 15:08:12 +00008817
Douglas Gregorac7610d2009-06-22 20:57:11 +00008818 case PotentiallyPotentiallyEvaluated:
8819 // We are in an expression that may be potentially evaluated; queue this
8820 // declaration reference until we know whether the expression is
8821 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00008822 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00008823 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00008824
8825 case PotentiallyEvaluatedIfUsed:
8826 // Referenced declarations will only be used if the construct in the
8827 // containing expression is used.
8828 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +00008829 }
Mike Stump1eb44332009-09-09 15:08:12 +00008830
Douglas Gregore0762c92009-06-19 23:52:42 +00008831 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00008832 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Sean Hunt1e238652011-05-12 03:51:51 +00008833 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor()) {
8834 if (Constructor->isTrivial())
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00008835 return;
8836 if (!Constructor->isUsed(false))
8837 DefineImplicitDefaultConstructor(Loc, Constructor);
Sean Hunt509f0482011-05-14 18:20:50 +00008838 } else if (Constructor->isDefaulted() &&
Sean Hunt49634cf2011-05-13 06:10:58 +00008839 Constructor->isCopyConstructor()) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00008840 if (!Constructor->isUsed(false))
Sean Hunt49634cf2011-05-13 06:10:58 +00008841 DefineImplicitCopyConstructor(Loc, Constructor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008842 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008843
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008844 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008845 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00008846 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008847 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008848 if (Destructor->isVirtual())
8849 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008850 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Sean Hunt2b188082011-05-14 05:23:28 +00008851 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008852 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00008853 if (!MethodDecl->isUsed(false))
Douglas Gregor39957dc2010-05-01 15:04:51 +00008854 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008855 } else if (MethodDecl->isVirtual())
8856 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008857 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00008858 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall15e310a2011-02-19 02:53:41 +00008859 // Recursive functions should be marked when used from another function.
8860 if (CurContext == Function) return;
8861
Mike Stump1eb44332009-09-09 15:08:12 +00008862 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00008863 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00008864 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00008865 bool AlreadyInstantiated = false;
8866 if (FunctionTemplateSpecializationInfo *SpecInfo
8867 = Function->getTemplateSpecializationInfo()) {
8868 if (SpecInfo->getPointOfInstantiation().isInvalid())
8869 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008870 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00008871 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00008872 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008873 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00008874 = Function->getMemberSpecializationInfo()) {
8875 if (MSInfo->getPointOfInstantiation().isInvalid())
8876 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008877 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00008878 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00008879 AlreadyInstantiated = true;
8880 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008881
Douglas Gregor60406be2010-01-16 22:29:39 +00008882 if (!AlreadyInstantiated) {
8883 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
8884 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
8885 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
8886 Loc));
8887 else
Chandler Carruth62c78d52010-08-25 08:44:16 +00008888 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +00008889 }
John McCall15e310a2011-02-19 02:53:41 +00008890 } else {
8891 // Walk redefinitions, as some of them may be instantiable.
Gabor Greif40181c42010-08-28 00:16:06 +00008892 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
8893 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +00008894 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +00008895 MarkDeclarationReferenced(Loc, *i);
8896 }
John McCall15e310a2011-02-19 02:53:41 +00008897 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008898
John McCall15e310a2011-02-19 02:53:41 +00008899 // Keep track of used but undefined functions.
8900 if (!Function->isPure() && !Function->hasBody() &&
8901 Function->getLinkage() != ExternalLinkage) {
8902 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
8903 if (old.isInvalid()) old = Loc;
8904 }
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +00008905
John McCall15e310a2011-02-19 02:53:41 +00008906 Function->setUsed(true);
Douglas Gregore0762c92009-06-19 23:52:42 +00008907 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00008908 }
Mike Stump1eb44332009-09-09 15:08:12 +00008909
Douglas Gregore0762c92009-06-19 23:52:42 +00008910 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00008911 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00008912 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00008913 Var->getInstantiatedFromStaticDataMember()) {
8914 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
8915 assert(MSInfo && "Missing member specialization information?");
8916 if (MSInfo->getPointOfInstantiation().isInvalid() &&
8917 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
8918 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redlf79a7192011-04-29 08:19:30 +00008919 // This is a modification of an existing AST node. Notify listeners.
8920 if (ASTMutationListener *L = getASTMutationListener())
8921 L->StaticDataMemberInstantiated(Var);
Chandler Carruth62c78d52010-08-25 08:44:16 +00008922 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00008923 }
8924 }
Mike Stump1eb44332009-09-09 15:08:12 +00008925
John McCall77efc682011-02-21 19:25:48 +00008926 // Keep track of used but undefined variables. We make a hole in
8927 // the warning for static const data members with in-line
8928 // initializers.
John McCall15e310a2011-02-19 02:53:41 +00008929 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall77efc682011-02-21 19:25:48 +00008930 && Var->getLinkage() != ExternalLinkage
8931 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall15e310a2011-02-19 02:53:41 +00008932 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
8933 if (old.isInvalid()) old = Loc;
8934 }
Douglas Gregor7caa6822009-07-24 20:34:43 +00008935
Douglas Gregore0762c92009-06-19 23:52:42 +00008936 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00008937 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00008938 }
Douglas Gregore0762c92009-06-19 23:52:42 +00008939}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00008940
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00008941namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +00008942 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00008943 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +00008944 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00008945 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
8946 Sema &S;
8947 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00008948
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00008949 public:
8950 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00008951
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00008952 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00008953
8954 bool TraverseTemplateArgument(const TemplateArgument &Arg);
8955 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00008956 };
8957}
8958
Chandler Carruthdfc35e32010-06-09 08:17:30 +00008959bool MarkReferencedDecls::TraverseTemplateArgument(
8960 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00008961 if (Arg.getKind() == TemplateArgument::Declaration) {
8962 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
8963 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00008964
8965 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00008966}
8967
Chandler Carruthdfc35e32010-06-09 08:17:30 +00008968bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00008969 if (ClassTemplateSpecializationDecl *Spec
8970 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
8971 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +00008972 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00008973 }
8974
Chandler Carruthe3e210c2010-06-10 10:31:57 +00008975 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00008976}
8977
8978void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
8979 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +00008980 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00008981}
8982
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00008983namespace {
8984 /// \brief Helper class that marks all of the declarations referenced by
8985 /// potentially-evaluated subexpressions as "referenced".
8986 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
8987 Sema &S;
8988
8989 public:
8990 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
8991
8992 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
8993
8994 void VisitDeclRefExpr(DeclRefExpr *E) {
8995 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
8996 }
8997
8998 void VisitMemberExpr(MemberExpr *E) {
8999 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009000 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009001 }
9002
9003 void VisitCXXNewExpr(CXXNewExpr *E) {
9004 if (E->getConstructor())
9005 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9006 if (E->getOperatorNew())
9007 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9008 if (E->getOperatorDelete())
9009 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009010 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009011 }
9012
9013 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9014 if (E->getOperatorDelete())
9015 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +00009016 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9017 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9018 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9019 S.MarkDeclarationReferenced(E->getLocStart(),
9020 S.LookupDestructor(Record));
9021 }
9022
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009023 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009024 }
9025
9026 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9027 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009028 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009029 }
9030
9031 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9032 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9033 }
Douglas Gregor102ff972010-10-19 17:17:35 +00009034
9035 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9036 Visit(E->getExpr());
9037 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009038 };
9039}
9040
9041/// \brief Mark any declarations that appear within this expression or any
9042/// potentially-evaluated subexpressions as "referenced".
9043void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9044 EvaluatedExprMarker(*this).Visit(E);
9045}
9046
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009047/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9048/// of the program being compiled.
9049///
9050/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009051/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009052/// possibility that the code will actually be executable. Code in sizeof()
9053/// expressions, code used only during overload resolution, etc., are not
9054/// potentially evaluated. This routine will suppress such diagnostics or,
9055/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009056/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009057/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009058///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009059/// This routine should be used for all diagnostics that describe the run-time
9060/// behavior of a program, such as passing a non-POD value through an ellipsis.
9061/// Failure to do so will likely result in spurious diagnostics or failures
9062/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek762696f2011-02-23 01:51:43 +00009063bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009064 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +00009065 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009066 case Unevaluated:
9067 // The argument will never be evaluated, so don't complain.
9068 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009069
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009070 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009071 case PotentiallyEvaluatedIfUsed:
Ted Kremenek351ba912011-02-23 01:52:04 +00009072 if (stmt && getCurFunctionOrMethodDecl()) {
9073 FunctionScopes.back()->PossiblyUnreachableDiags.
9074 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9075 }
9076 else
9077 Diag(Loc, PD);
9078
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009079 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009080
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009081 case PotentiallyPotentiallyEvaluated:
9082 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9083 break;
9084 }
9085
9086 return false;
9087}
9088
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009089bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9090 CallExpr *CE, FunctionDecl *FD) {
9091 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9092 return false;
9093
9094 PartialDiagnostic Note =
9095 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9096 << FD->getDeclName() : PDiag();
9097 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009098
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009099 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009100 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009101 PDiag(diag::err_call_function_incomplete_return)
9102 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009103 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009104 << CE->getSourceRange(),
9105 std::make_pair(NoteLoc, Note)))
9106 return true;
9107
9108 return false;
9109}
9110
Douglas Gregor92c3a042011-01-19 16:50:08 +00009111// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +00009112// will prevent this condition from triggering, which is what we want.
9113void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9114 SourceLocation Loc;
9115
John McCalla52ef082009-11-11 02:41:58 +00009116 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +00009117 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +00009118
John McCall5a881bb2009-10-12 21:59:07 +00009119 if (isa<BinaryOperator>(E)) {
9120 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +00009121 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +00009122 return;
9123
Douglas Gregor92c3a042011-01-19 16:50:08 +00009124 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9125
John McCallc8d8ac52009-11-12 00:06:05 +00009126 // Greylist some idioms by putting them into a warning subcategory.
9127 if (ObjCMessageExpr *ME
9128 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9129 Selector Sel = ME->getSelector();
9130
John McCallc8d8ac52009-11-12 00:06:05 +00009131 // self = [<foo> init...]
Douglas Gregor813d8342011-02-18 22:29:55 +00009132 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +00009133 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9134
9135 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +00009136 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +00009137 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9138 }
John McCalla52ef082009-11-11 02:41:58 +00009139
John McCall5a881bb2009-10-12 21:59:07 +00009140 Loc = Op->getOperatorLoc();
9141 } else if (isa<CXXOperatorCallExpr>(E)) {
9142 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +00009143 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +00009144 return;
9145
Douglas Gregor92c3a042011-01-19 16:50:08 +00009146 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +00009147 Loc = Op->getOperatorLoc();
9148 } else {
9149 // Not an assignment.
9150 return;
9151 }
9152
Douglas Gregor55b38842010-04-14 16:09:52 +00009153 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +00009154
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009155 SourceLocation Open = E->getSourceRange().getBegin();
9156 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9157 Diag(Loc, diag::note_condition_assign_silence)
9158 << FixItHint::CreateInsertion(Open, "(")
9159 << FixItHint::CreateInsertion(Close, ")");
9160
Douglas Gregor92c3a042011-01-19 16:50:08 +00009161 if (IsOrAssign)
9162 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9163 << FixItHint::CreateReplacement(Loc, "!=");
9164 else
9165 Diag(Loc, diag::note_condition_assign_to_comparison)
9166 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +00009167}
9168
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009169/// \brief Redundant parentheses over an equality comparison can indicate
9170/// that the user intended an assignment used as condition.
9171void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009172 // Don't warn if the parens came from a macro.
9173 SourceLocation parenLoc = parenE->getLocStart();
9174 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9175 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +00009176 // Don't warn for dependent expressions.
9177 if (parenE->isTypeDependent())
9178 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009179
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009180 Expr *E = parenE->IgnoreParens();
9181
9182 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +00009183 if (opE->getOpcode() == BO_EQ &&
9184 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9185 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009186 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +00009187
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009188 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009189 Diag(Loc, diag::note_equality_comparison_silence)
9190 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9191 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009192 Diag(Loc, diag::note_equality_comparison_to_assign)
9193 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009194 }
9195}
9196
John Wiegley429bb272011-04-08 18:41:53 +00009197ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +00009198 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009199 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9200 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +00009201
John McCall864c0412011-04-26 20:42:42 +00009202 ExprResult result = CheckPlaceholderExpr(E);
9203 if (result.isInvalid()) return ExprError();
9204 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00009205
John McCall864c0412011-04-26 20:42:42 +00009206 if (!E->isTypeDependent()) {
John McCallf6a16482010-12-04 03:47:34 +00009207 if (getLangOptions().CPlusPlus)
9208 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9209
John Wiegley429bb272011-04-08 18:41:53 +00009210 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9211 if (ERes.isInvalid())
9212 return ExprError();
9213 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +00009214
9215 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +00009216 if (!T->isScalarType()) { // C99 6.8.4.1p1
9217 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9218 << T << E->getSourceRange();
9219 return ExprError();
9220 }
John McCall5a881bb2009-10-12 21:59:07 +00009221 }
9222
John Wiegley429bb272011-04-08 18:41:53 +00009223 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +00009224}
Douglas Gregor586596f2010-05-06 17:25:47 +00009225
John McCall60d7b3a2010-08-24 06:29:42 +00009226ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9227 Expr *Sub) {
Douglas Gregoreecf38f2010-05-06 21:39:56 +00009228 if (!Sub)
Douglas Gregor586596f2010-05-06 17:25:47 +00009229 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009230
9231 return CheckBooleanCondition(Sub, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +00009232}
John McCall2a984ca2010-10-12 00:20:44 +00009233
John McCall1de4d4e2011-04-07 08:22:57 +00009234namespace {
John McCall755d8492011-04-12 00:42:48 +00009235 /// A visitor for rebuilding a call to an __unknown_any expression
9236 /// to have an appropriate type.
9237 struct RebuildUnknownAnyFunction
9238 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9239
9240 Sema &S;
9241
9242 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9243
9244 ExprResult VisitStmt(Stmt *S) {
9245 llvm_unreachable("unexpected statement!");
9246 return ExprError();
9247 }
9248
9249 ExprResult VisitExpr(Expr *expr) {
9250 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
9251 << expr->getSourceRange();
9252 return ExprError();
9253 }
9254
9255 /// Rebuild an expression which simply semantically wraps another
9256 /// expression which it shares the type and value kind of.
9257 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9258 ExprResult subResult = Visit(expr->getSubExpr());
9259 if (subResult.isInvalid()) return ExprError();
9260
9261 Expr *subExpr = subResult.take();
9262 expr->setSubExpr(subExpr);
9263 expr->setType(subExpr->getType());
9264 expr->setValueKind(subExpr->getValueKind());
9265 assert(expr->getObjectKind() == OK_Ordinary);
9266 return expr;
9267 }
9268
9269 ExprResult VisitParenExpr(ParenExpr *paren) {
9270 return rebuildSugarExpr(paren);
9271 }
9272
9273 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9274 return rebuildSugarExpr(op);
9275 }
9276
9277 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9278 ExprResult subResult = Visit(op->getSubExpr());
9279 if (subResult.isInvalid()) return ExprError();
9280
9281 Expr *subExpr = subResult.take();
9282 op->setSubExpr(subExpr);
9283 op->setType(S.Context.getPointerType(subExpr->getType()));
9284 assert(op->getValueKind() == VK_RValue);
9285 assert(op->getObjectKind() == OK_Ordinary);
9286 return op;
9287 }
9288
9289 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
9290 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
9291
9292 expr->setType(decl->getType());
9293
9294 assert(expr->getValueKind() == VK_RValue);
9295 if (S.getLangOptions().CPlusPlus &&
9296 !(isa<CXXMethodDecl>(decl) &&
9297 cast<CXXMethodDecl>(decl)->isInstance()))
9298 expr->setValueKind(VK_LValue);
9299
9300 return expr;
9301 }
9302
9303 ExprResult VisitMemberExpr(MemberExpr *mem) {
9304 return resolveDecl(mem, mem->getMemberDecl());
9305 }
9306
9307 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
9308 return resolveDecl(ref, ref->getDecl());
9309 }
9310 };
9311}
9312
9313/// Given a function expression of unknown-any type, try to rebuild it
9314/// to have a function type.
9315static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
9316 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
9317 if (result.isInvalid()) return ExprError();
9318 return S.DefaultFunctionArrayConversion(result.take());
9319}
9320
9321namespace {
John McCall379b5152011-04-11 07:02:50 +00009322 /// A visitor for rebuilding an expression of type __unknown_anytype
9323 /// into one which resolves the type directly on the referring
9324 /// expression. Strict preservation of the original source
9325 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +00009326 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +00009327 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +00009328
9329 Sema &S;
9330
9331 /// The current destination type.
9332 QualType DestType;
9333
9334 RebuildUnknownAnyExpr(Sema &S, QualType castType)
9335 : S(S), DestType(castType) {}
9336
John McCalla5fc4722011-04-09 22:50:59 +00009337 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +00009338 llvm_unreachable("unexpected statement!");
John McCalla5fc4722011-04-09 22:50:59 +00009339 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009340 }
9341
John McCall379b5152011-04-11 07:02:50 +00009342 ExprResult VisitExpr(Expr *expr) {
9343 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9344 << expr->getSourceRange();
9345 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009346 }
9347
John McCall379b5152011-04-11 07:02:50 +00009348 ExprResult VisitCallExpr(CallExpr *call);
9349 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
9350
John McCalla5fc4722011-04-09 22:50:59 +00009351 /// Rebuild an expression which simply semantically wraps another
9352 /// expression which it shares the type and value kind of.
9353 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9354 ExprResult subResult = Visit(expr->getSubExpr());
John McCall755d8492011-04-12 00:42:48 +00009355 if (subResult.isInvalid()) return ExprError();
John McCalla5fc4722011-04-09 22:50:59 +00009356 Expr *subExpr = subResult.take();
9357 expr->setSubExpr(subExpr);
9358 expr->setType(subExpr->getType());
9359 expr->setValueKind(subExpr->getValueKind());
9360 assert(expr->getObjectKind() == OK_Ordinary);
9361 return expr;
9362 }
John McCall1de4d4e2011-04-07 08:22:57 +00009363
John McCalla5fc4722011-04-09 22:50:59 +00009364 ExprResult VisitParenExpr(ParenExpr *paren) {
9365 return rebuildSugarExpr(paren);
9366 }
9367
9368 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9369 return rebuildSugarExpr(op);
9370 }
9371
John McCall755d8492011-04-12 00:42:48 +00009372 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9373 const PointerType *ptr = DestType->getAs<PointerType>();
9374 if (!ptr) {
9375 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
9376 << op->getSourceRange();
9377 return ExprError();
9378 }
9379 assert(op->getValueKind() == VK_RValue);
9380 assert(op->getObjectKind() == OK_Ordinary);
9381 op->setType(DestType);
9382
9383 // Build the sub-expression as if it were an object of the pointee type.
9384 DestType = ptr->getPointeeType();
9385 ExprResult subResult = Visit(op->getSubExpr());
9386 if (subResult.isInvalid()) return ExprError();
9387 op->setSubExpr(subResult.take());
9388 return op;
9389 }
9390
John McCall379b5152011-04-11 07:02:50 +00009391 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCalla5fc4722011-04-09 22:50:59 +00009392
John McCall755d8492011-04-12 00:42:48 +00009393 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCalla5fc4722011-04-09 22:50:59 +00009394
John McCall755d8492011-04-12 00:42:48 +00009395 ExprResult VisitMemberExpr(MemberExpr *mem) {
9396 return resolveDecl(mem, mem->getMemberDecl());
9397 }
John McCalla5fc4722011-04-09 22:50:59 +00009398
9399 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall379b5152011-04-11 07:02:50 +00009400 return resolveDecl(ref, ref->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +00009401 }
9402 };
9403}
9404
John McCall379b5152011-04-11 07:02:50 +00009405/// Rebuilds a call expression which yielded __unknown_anytype.
9406ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
9407 Expr *callee = call->getCallee();
9408
9409 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +00009410 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +00009411 FK_FunctionPointer,
9412 FK_BlockPointer
9413 };
9414
9415 FnKind kind;
9416 QualType type = callee->getType();
John McCallf5307512011-04-27 00:36:17 +00009417 if (type == S.Context.BoundMemberTy) {
9418 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
9419 kind = FK_MemberFunction;
9420 type = Expr::findBoundMemberType(callee);
John McCall379b5152011-04-11 07:02:50 +00009421 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
9422 type = ptr->getPointeeType();
9423 kind = FK_FunctionPointer;
9424 } else {
9425 type = type->castAs<BlockPointerType>()->getPointeeType();
9426 kind = FK_BlockPointer;
9427 }
9428 const FunctionType *fnType = type->castAs<FunctionType>();
9429
9430 // Verify that this is a legal result type of a function.
9431 if (DestType->isArrayType() || DestType->isFunctionType()) {
9432 unsigned diagID = diag::err_func_returning_array_function;
9433 if (kind == FK_BlockPointer)
9434 diagID = diag::err_block_returning_array_function;
9435
9436 S.Diag(call->getExprLoc(), diagID)
9437 << DestType->isFunctionType() << DestType;
9438 return ExprError();
9439 }
9440
9441 // Otherwise, go ahead and set DestType as the call's result.
9442 call->setType(DestType.getNonLValueExprType(S.Context));
9443 call->setValueKind(Expr::getValueKindForType(DestType));
9444 assert(call->getObjectKind() == OK_Ordinary);
9445
9446 // Rebuild the function type, replacing the result type with DestType.
9447 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
9448 DestType = S.Context.getFunctionType(DestType,
9449 proto->arg_type_begin(),
9450 proto->getNumArgs(),
9451 proto->getExtProtoInfo());
9452 else
9453 DestType = S.Context.getFunctionNoProtoType(DestType,
9454 fnType->getExtInfo());
9455
9456 // Rebuild the appropriate pointer-to-function type.
9457 switch (kind) {
John McCallf5307512011-04-27 00:36:17 +00009458 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +00009459 // Nothing to do.
9460 break;
9461
9462 case FK_FunctionPointer:
9463 DestType = S.Context.getPointerType(DestType);
9464 break;
9465
9466 case FK_BlockPointer:
9467 DestType = S.Context.getBlockPointerType(DestType);
9468 break;
9469 }
9470
9471 // Finally, we can recurse.
9472 ExprResult calleeResult = Visit(callee);
9473 if (!calleeResult.isUsable()) return ExprError();
9474 call->setCallee(calleeResult.take());
9475
9476 // Bind a temporary if necessary.
9477 return S.MaybeBindToTemporary(call);
9478}
9479
9480ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall755d8492011-04-12 00:42:48 +00009481 ObjCMethodDecl *method = msg->getMethodDecl();
9482 assert(method && "__unknown_anytype message without result type?");
John McCall379b5152011-04-11 07:02:50 +00009483
John McCall755d8492011-04-12 00:42:48 +00009484 // Verify that this is a legal result type of a call.
9485 if (DestType->isArrayType() || DestType->isFunctionType()) {
9486 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
9487 << DestType->isFunctionType() << DestType;
9488 return ExprError();
John McCall379b5152011-04-11 07:02:50 +00009489 }
9490
John McCall755d8492011-04-12 00:42:48 +00009491 assert(method->getResultType() == S.Context.UnknownAnyTy);
9492 method->setResultType(DestType);
9493
John McCall379b5152011-04-11 07:02:50 +00009494 // Change the type of the message.
John McCall755d8492011-04-12 00:42:48 +00009495 msg->setType(DestType.getNonReferenceType());
9496 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +00009497
John McCall755d8492011-04-12 00:42:48 +00009498 return S.MaybeBindToTemporary(msg);
John McCall379b5152011-04-11 07:02:50 +00009499}
9500
9501ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall755d8492011-04-12 00:42:48 +00009502 // The only case we should ever see here is a function-to-pointer decay.
John McCall379b5152011-04-11 07:02:50 +00009503 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall379b5152011-04-11 07:02:50 +00009504 assert(ice->getValueKind() == VK_RValue);
9505 assert(ice->getObjectKind() == OK_Ordinary);
9506
John McCall755d8492011-04-12 00:42:48 +00009507 ice->setType(DestType);
9508
John McCall379b5152011-04-11 07:02:50 +00009509 // Rebuild the sub-expression as the pointee (function) type.
9510 DestType = DestType->castAs<PointerType>()->getPointeeType();
9511
9512 ExprResult result = Visit(ice->getSubExpr());
9513 if (!result.isUsable()) return ExprError();
9514
9515 ice->setSubExpr(result.take());
9516 return S.Owned(ice);
9517}
9518
John McCall755d8492011-04-12 00:42:48 +00009519ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall379b5152011-04-11 07:02:50 +00009520 ExprValueKind valueKind = VK_LValue;
John McCall379b5152011-04-11 07:02:50 +00009521 QualType type = DestType;
9522
9523 // We know how to make this work for certain kinds of decls:
9524
9525 // - functions
John McCall755d8492011-04-12 00:42:48 +00009526 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCall379b5152011-04-11 07:02:50 +00009527 // This is true because FunctionDecls must always have function
9528 // type, so we can't be resolving the entire thing at once.
9529 assert(type->isFunctionType());
9530
John McCallf5307512011-04-27 00:36:17 +00009531 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
9532 if (method->isInstance()) {
9533 valueKind = VK_RValue;
9534 type = S.Context.BoundMemberTy;
9535 }
9536
John McCall379b5152011-04-11 07:02:50 +00009537 // Function references aren't l-values in C.
9538 if (!S.getLangOptions().CPlusPlus)
9539 valueKind = VK_RValue;
9540
9541 // - variables
9542 } else if (isa<VarDecl>(decl)) {
John McCall755d8492011-04-12 00:42:48 +00009543 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
9544 type = refTy->getPointeeType();
John McCall379b5152011-04-11 07:02:50 +00009545 } else if (type->isFunctionType()) {
John McCall755d8492011-04-12 00:42:48 +00009546 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
9547 << decl << expr->getSourceRange();
9548 return ExprError();
John McCall379b5152011-04-11 07:02:50 +00009549 }
9550
9551 // - nothing else
9552 } else {
9553 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
9554 << decl << expr->getSourceRange();
9555 return ExprError();
9556 }
9557
John McCall755d8492011-04-12 00:42:48 +00009558 decl->setType(DestType);
9559 expr->setType(type);
9560 expr->setValueKind(valueKind);
9561 return S.Owned(expr);
John McCall379b5152011-04-11 07:02:50 +00009562}
9563
John McCall1de4d4e2011-04-07 08:22:57 +00009564/// Check a cast of an unknown-any type. We intentionally only
9565/// trigger this for C-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00009566ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
9567 Expr *castExpr, CastKind &castKind,
9568 ExprValueKind &VK, CXXCastPath &path) {
John McCall1de4d4e2011-04-07 08:22:57 +00009569 // Rewrite the casted expression from scratch.
John McCalla5fc4722011-04-09 22:50:59 +00009570 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
9571 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009572
John McCalla5fc4722011-04-09 22:50:59 +00009573 castExpr = result.take();
9574 VK = castExpr->getValueKind();
9575 castKind = CK_NoOp;
9576
9577 return castExpr;
John McCall1de4d4e2011-04-07 08:22:57 +00009578}
9579
9580static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
9581 Expr *orig = e;
John McCall379b5152011-04-11 07:02:50 +00009582 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +00009583 while (true) {
9584 e = e->IgnoreParenImpCasts();
John McCall379b5152011-04-11 07:02:50 +00009585 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall1de4d4e2011-04-07 08:22:57 +00009586 e = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +00009587 diagID = diag::err_uncasted_call_of_unknown_any;
9588 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00009589 break;
John McCall379b5152011-04-11 07:02:50 +00009590 }
John McCall1de4d4e2011-04-07 08:22:57 +00009591 }
9592
John McCall379b5152011-04-11 07:02:50 +00009593 SourceLocation loc;
9594 NamedDecl *d;
9595 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9596 loc = ref->getLocation();
9597 d = ref->getDecl();
9598 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
9599 loc = mem->getMemberLoc();
9600 d = mem->getMemberDecl();
9601 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
9602 diagID = diag::err_uncasted_call_of_unknown_any;
9603 loc = msg->getSelectorLoc();
9604 d = msg->getMethodDecl();
9605 assert(d && "unknown method returning __unknown_any?");
9606 } else {
9607 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9608 << e->getSourceRange();
9609 return ExprError();
9610 }
9611
9612 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +00009613
9614 // Never recoverable.
9615 return ExprError();
9616}
9617
John McCall2a984ca2010-10-12 00:20:44 +00009618/// Check for operands with placeholder types and complain if found.
9619/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +00009620ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall1de4d4e2011-04-07 08:22:57 +00009621 // Placeholder types are always *exactly* the appropriate builtin type.
9622 QualType type = E->getType();
John McCall2a984ca2010-10-12 00:20:44 +00009623
John McCall1de4d4e2011-04-07 08:22:57 +00009624 // Overloaded expressions.
9625 if (type == Context.OverloadTy)
9626 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregordb2eae62011-03-16 19:16:25 +00009627 E->getSourceRange(),
John McCall1de4d4e2011-04-07 08:22:57 +00009628 QualType(),
9629 diag::err_ovl_unresolvable);
9630
John McCall864c0412011-04-26 20:42:42 +00009631 // Bound member functions.
9632 if (type == Context.BoundMemberTy) {
9633 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9634 << E->getSourceRange();
9635 return ExprError();
9636 }
9637
John McCall1de4d4e2011-04-07 08:22:57 +00009638 // Expressions of unknown type.
9639 if (type == Context.UnknownAnyTy)
9640 return diagnoseUnknownAnyExpr(*this, E);
9641
9642 assert(!type->isPlaceholderType());
9643 return Owned(E);
John McCall2a984ca2010-10-12 00:20:44 +00009644}
Richard Trieubb9b80c2011-04-21 21:44:26 +00009645
9646bool Sema::CheckCaseExpression(Expr *expr) {
9647 if (expr->isTypeDependent())
9648 return true;
9649 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
9650 return expr->getType()->isIntegralOrEnumerationType();
9651 return false;
9652}