blob: ffa092aad1eadc8b111af31d31d8139942a5fb5e [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"
Anna Zaks67221552011-07-28 19:51:27 +000039#include "clang/Sema/SemaFixItUtils.h"
John McCall7cd088e2010-08-24 07:21:54 +000040#include "clang/Sema/Template.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000041using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000042using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000043
David Chisnall0f436562009-08-17 16:35:33 +000044
Douglas Gregor48f3bb92009-02-18 21:56:37 +000045/// \brief Determine whether the use of this declaration is valid, and
46/// emit any corresponding diagnostics.
47///
48/// This routine diagnoses various problems with referencing
49/// declarations that can occur when using a declaration. For example,
50/// it might warn if a deprecated or unavailable declaration is being
51/// used, or produce an error (and return true) if a C++0x deleted
52/// function is being used.
53///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000054/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattner52338262009-10-25 22:31:57 +000055/// decls.
56///
Douglas Gregor48f3bb92009-02-18 21:56:37 +000057/// \returns true if there was an error (this declaration cannot be
58/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +000059///
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +000060bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +000061 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor9b623632010-10-12 23:32:35 +000062 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
63 // If there were any diagnostics suppressed by template argument deduction,
64 // emit them now.
Chris Lattner5f9e2722011-07-23 10:55:15 +000065 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor9b623632010-10-12 23:32:35 +000066 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
67 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000068 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor9b623632010-10-12 23:32:35 +000069 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
70 Diag(Suppressed[I].first, Suppressed[I].second);
71
72 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000073 // them again for this specialization. However, we don't obsolete this
Douglas Gregor9b623632010-10-12 23:32:35 +000074 // entry from the table, because we want to avoid ever emitting these
75 // diagnostics again.
76 Suppressed.clear();
77 }
78 }
79
Richard Smith34b41d92011-02-20 03:19:35 +000080 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smith483b9f32011-02-21 20:05:19 +000081 if (ParsingInitForAutoVars.count(D)) {
82 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
83 << D->getDeclName();
84 return true;
Richard Smith34b41d92011-02-20 03:19:35 +000085 }
86
Douglas Gregor48f3bb92009-02-18 21:56:37 +000087 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000088 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000089 if (FD->isDeleted()) {
90 Diag(Loc, diag::err_deleted_function_use);
John McCallf85e1932011-06-15 23:02:42 +000091 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000092 return true;
93 }
Douglas Gregor25d944a2009-02-24 04:26:15 +000094 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +000095
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000096 // See if this declaration is unavailable or deprecated.
97 std::string Message;
98 switch (D->getAvailability(&Message)) {
99 case AR_Available:
100 case AR_NotYetIntroduced:
101 break;
102
103 case AR_Deprecated:
104 EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
105 break;
106
107 case AR_Unavailable:
Argyrios Kyrtzidis12189f52011-06-17 17:28:30 +0000108 if (cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) {
109 if (Message.empty()) {
110 if (!UnknownObjCClass)
111 Diag(Loc, diag::err_unavailable) << D->getDeclName();
112 else
113 Diag(Loc, diag::warn_unavailable_fwdclass_message)
114 << D->getDeclName();
115 }
116 else
117 Diag(Loc, diag::err_unavailable_message)
118 << D->getDeclName() << Message;
119 Diag(D->getLocation(), diag::note_unavailable_here)
120 << isa<FunctionDecl>(D) << false;
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000121 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000122 break;
123 }
124
Anders Carlsson2127ecc2010-10-22 23:37:08 +0000125 // Warn if this is used but marked unused.
126 if (D->hasAttr<UnusedAttr>())
127 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
128
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000129 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +0000130}
131
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000132/// \brief Retrieve the message suffix that should be added to a
133/// diagnostic complaining about the given function being deleted or
134/// unavailable.
135std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
136 // FIXME: C++0x implicitly-deleted special member functions could be
137 // detected here so that we could improve diagnostics to say, e.g.,
138 // "base class 'A' had a deleted copy constructor".
139 if (FD->isDeleted())
140 return std::string();
141
142 std::string Message;
143 if (FD->getAvailability(&Message))
144 return ": " + Message;
145
146 return std::string();
147}
148
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000149/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +0000150/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000151/// attribute. It warns if call does not have the sentinel argument.
152///
153void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000154 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000155 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +0000156 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000157 return;
Douglas Gregor92e986e2010-04-22 16:44:27 +0000158
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000159 int sentinelPos = attr->getSentinel();
160 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +0000161
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000162 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000163 bool warnNotEnoughArgs = false;
164 int isMethod = 0;
165 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
166 // skip over named parameters.
167 ObjCMethodDecl::param_iterator P, E = MD->param_end();
168 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
169 if (nullPos)
170 --nullPos;
171 else
172 ++i;
173 }
174 warnNotEnoughArgs = (P != E || i >= NumArgs);
175 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000176 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000177 // skip over named parameters.
178 ObjCMethodDecl::param_iterator P, E = FD->param_end();
179 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
180 if (nullPos)
181 --nullPos;
182 else
183 ++i;
184 }
185 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000186 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000187 // block or function pointer call.
188 QualType Ty = V->getType();
189 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000190 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000191 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
192 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000193 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
194 unsigned NumArgsInProto = Proto->getNumArgs();
195 unsigned k;
196 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
197 if (nullPos)
198 --nullPos;
199 else
200 ++i;
201 }
202 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
203 }
204 if (Ty->isBlockPointerType())
205 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000206 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000207 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000208 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000209 return;
210
211 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000212 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000213 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000214 return;
215 }
216 int sentinel = i;
217 while (sentinelPos > 0 && i < NumArgs-1) {
218 --sentinelPos;
219 ++i;
220 }
221 if (sentinelPos > 0) {
222 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000223 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000224 return;
225 }
226 while (i < NumArgs-1) {
227 ++i;
228 ++sentinel;
229 }
230 Expr *sentinelExpr = Args[sentinel];
John McCall8eb662e2010-05-06 23:53:00 +0000231 if (!sentinelExpr) return;
232 if (sentinelExpr->isTypeDependent()) return;
233 if (sentinelExpr->isValueDependent()) return;
Anders Carlsson343e6ff2010-11-05 15:21:33 +0000234
235 // nullptr_t is always treated as null.
236 if (sentinelExpr->getType()->isNullPtrType()) return;
237
Fariborz Jahanian9ccd7252010-07-14 16:37:51 +0000238 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall8eb662e2010-05-06 23:53:00 +0000239 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
240 Expr::NPC_ValueDependentIsNull))
241 return;
242
243 // Unfortunately, __null has type 'int'.
244 if (isa<GNUNullExpr>(sentinelExpr)) return;
245
Douglas Gregorf78c4e52011-07-30 08:57:03 +0000246 SourceLocation MissingNilLoc
247 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
248 std::string NullValue;
249 if (isMethod && PP.getIdentifierInfo("nil")->hasMacroDefinition())
250 NullValue = "nil";
251 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
252 NullValue = "NULL";
253 else if (Context.getTypeSize(Context.IntTy)
254 == Context.getTypeSize(Context.getSizeType()))
255 NullValue = "0";
256 else
257 NullValue = "0L";
258
259 Diag(MissingNilLoc, diag::warn_missing_sentinel)
260 << isMethod
261 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCall8eb662e2010-05-06 23:53:00 +0000262 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000263}
264
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000265SourceRange Sema::getExprRange(ExprTy *E) const {
266 Expr *Ex = (Expr *)E;
267 return Ex? Ex->getSourceRange() : SourceRange();
268}
269
Chris Lattnere7a2e912008-07-25 21:10:04 +0000270//===----------------------------------------------------------------------===//
271// Standard Promotions and Conversions
272//===----------------------------------------------------------------------===//
273
Chris Lattnere7a2e912008-07-25 21:10:04 +0000274/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley429bb272011-04-08 18:41:53 +0000275ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000276 QualType Ty = E->getType();
277 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
278
Chris Lattnere7a2e912008-07-25 21:10:04 +0000279 if (Ty->isFunctionType())
John Wiegley429bb272011-04-08 18:41:53 +0000280 E = ImpCastExprToType(E, Context.getPointerType(Ty),
281 CK_FunctionToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000282 else if (Ty->isArrayType()) {
283 // In C90 mode, arrays only promote to pointers if the array expression is
284 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
285 // type 'array of type' is converted to an expression that has type 'pointer
286 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
287 // that has type 'array of type' ...". The relevant change is "an lvalue"
288 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000289 //
290 // C++ 4.2p1:
291 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
292 // T" can be converted to an rvalue of type "pointer to T".
293 //
John McCall7eb0a9e2010-11-24 05:12:34 +0000294 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000295 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
296 CK_ArrayToPointerDecay).take();
Chris Lattner67d33d82008-07-25 21:33:13 +0000297 }
John Wiegley429bb272011-04-08 18:41:53 +0000298 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000299}
300
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000301static void CheckForNullPointerDereference(Sema &S, Expr *E) {
302 // Check to see if we are dereferencing a null pointer. If so,
303 // and if not volatile-qualified, this is undefined behavior that the
304 // optimizer will delete, so warn about it. People sometimes try to use this
305 // to get a deterministic trap and are surprised by clang's behavior. This
306 // only handles the pattern "*null", which is a very syntactic check.
307 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
308 if (UO->getOpcode() == UO_Deref &&
309 UO->getSubExpr()->IgnoreParenCasts()->
310 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
311 !UO->getType().isVolatileQualified()) {
312 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
313 S.PDiag(diag::warn_indirection_through_null)
314 << UO->getSubExpr()->getSourceRange());
315 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
316 S.PDiag(diag::note_indirection_through_null));
317 }
318}
319
John Wiegley429bb272011-04-08 18:41:53 +0000320ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000321 // C++ [conv.lval]p1:
322 // A glvalue of a non-function, non-array type T can be
323 // converted to a prvalue.
John Wiegley429bb272011-04-08 18:41:53 +0000324 if (!E->isGLValue()) return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000325 QualType T = E->getType();
326 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCallf6a16482010-12-04 03:47:34 +0000327
John McCall409fa9a2010-12-06 20:48:59 +0000328 // Create a load out of an ObjCProperty l-value, if necessary.
329 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley429bb272011-04-08 18:41:53 +0000330 ExprResult Res = ConvertPropertyForRValue(E);
331 if (Res.isInvalid())
332 return Owned(E);
333 E = Res.take();
John McCall409fa9a2010-12-06 20:48:59 +0000334 if (!E->isGLValue())
John Wiegley429bb272011-04-08 18:41:53 +0000335 return Owned(E);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000336 }
John McCall409fa9a2010-12-06 20:48:59 +0000337
338 // We don't want to throw lvalue-to-rvalue casts on top of
339 // expressions of certain types in C++.
340 if (getLangOptions().CPlusPlus &&
341 (E->getType() == Context.OverloadTy ||
342 T->isDependentType() ||
343 T->isRecordType()))
John Wiegley429bb272011-04-08 18:41:53 +0000344 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000345
346 // The C standard is actually really unclear on this point, and
347 // DR106 tells us what the result should be but not why. It's
348 // generally best to say that void types just doesn't undergo
349 // lvalue-to-rvalue at all. Note that expressions of unqualified
350 // 'void' type are never l-values, but qualified void can be.
351 if (T->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +0000352 return Owned(E);
John McCall409fa9a2010-12-06 20:48:59 +0000353
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +0000354 CheckForNullPointerDereference(*this, E);
355
John McCall409fa9a2010-12-06 20:48:59 +0000356 // C++ [conv.lval]p1:
357 // [...] If T is a non-class type, the type of the prvalue is the
358 // cv-unqualified version of T. Otherwise, the type of the
359 // rvalue is T.
360 //
361 // C99 6.3.2.1p2:
362 // If the lvalue has qualified type, the value has the unqualified
363 // version of the type of the lvalue; otherwise, the value has the
364 // type of the lvalue.
365 if (T.hasQualifiers())
366 T = T.getUnqualifiedType();
367
Ted Kremenek3aea4da2011-03-01 18:41:00 +0000368 CheckArrayAccess(E);
Ted Kremeneka0125d82011-02-16 01:57:07 +0000369
John Wiegley429bb272011-04-08 18:41:53 +0000370 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
371 E, 0, VK_RValue));
John McCall409fa9a2010-12-06 20:48:59 +0000372}
373
John Wiegley429bb272011-04-08 18:41:53 +0000374ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
375 ExprResult Res = DefaultFunctionArrayConversion(E);
376 if (Res.isInvalid())
377 return ExprError();
378 Res = DefaultLvalueConversion(Res.take());
379 if (Res.isInvalid())
380 return ExprError();
381 return move(Res);
Douglas Gregora873dfc2010-02-03 00:27:59 +0000382}
383
384
Chris Lattnere7a2e912008-07-25 21:10:04 +0000385/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000386/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000387/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattnere7a2e912008-07-25 21:10:04 +0000388/// apply if the array is an argument to the sizeof or address (&) operators.
389/// In these instances, this routine should *not* be called.
John Wiegley429bb272011-04-08 18:41:53 +0000390ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCall0ae287a2010-12-01 04:43:34 +0000391 // First, convert to an r-value.
John Wiegley429bb272011-04-08 18:41:53 +0000392 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
393 if (Res.isInvalid())
394 return Owned(E);
395 E = Res.take();
John McCall0ae287a2010-12-01 04:43:34 +0000396
397 QualType Ty = E->getType();
Chris Lattnere7a2e912008-07-25 21:10:04 +0000398 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCall0ae287a2010-12-01 04:43:34 +0000399
400 // Try to perform integral promotions if the object has a theoretically
401 // promotable type.
402 if (Ty->isIntegralOrUnscopedEnumerationType()) {
403 // C99 6.3.1.1p2:
404 //
405 // The following may be used in an expression wherever an int or
406 // unsigned int may be used:
407 // - an object or expression with an integer type whose integer
408 // conversion rank is less than or equal to the rank of int
409 // and unsigned int.
410 // - A bit-field of type _Bool, int, signed int, or unsigned int.
411 //
412 // If an int can represent all values of the original type, the
413 // value is converted to an int; otherwise, it is converted to an
414 // unsigned int. These are called the integer promotions. All
415 // other types are unchanged by the integer promotions.
416
417 QualType PTy = Context.isPromotableBitField(E);
418 if (!PTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +0000419 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
420 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000421 }
422 if (Ty->isPromotableIntegerType()) {
423 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley429bb272011-04-08 18:41:53 +0000424 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
425 return Owned(E);
John McCall0ae287a2010-12-01 04:43:34 +0000426 }
Eli Friedman04e83572009-08-20 04:21:42 +0000427 }
John Wiegley429bb272011-04-08 18:41:53 +0000428 return Owned(E);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000429}
430
Chris Lattner05faf172008-07-25 22:25:12 +0000431/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000432/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000433/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley429bb272011-04-08 18:41:53 +0000434ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
435 QualType Ty = E->getType();
Chris Lattner05faf172008-07-25 22:25:12 +0000436 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000437
John Wiegley429bb272011-04-08 18:41:53 +0000438 ExprResult Res = UsualUnaryConversions(E);
439 if (Res.isInvalid())
440 return Owned(E);
441 E = Res.take();
John McCall40c29132010-12-06 18:36:11 +0000442
Chris Lattner05faf172008-07-25 22:25:12 +0000443 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattner40378332010-05-16 04:01:30 +0000444 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley429bb272011-04-08 18:41:53 +0000445 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
446
447 return Owned(E);
Chris Lattner05faf172008-07-25 22:25:12 +0000448}
449
Chris Lattner312531a2009-04-12 08:11:20 +0000450/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
451/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley429bb272011-04-08 18:41:53 +0000452/// interfaces passed by value.
453ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCallf85e1932011-06-15 23:02:42 +0000454 FunctionDecl *FDecl) {
Douglas Gregor8d5e18c2011-06-17 00:15:10 +0000455 ExprResult ExprRes = CheckPlaceholderExpr(E);
456 if (ExprRes.isInvalid())
457 return ExprError();
458
459 ExprRes = DefaultArgumentPromotion(E);
John Wiegley429bb272011-04-08 18:41:53 +0000460 if (ExprRes.isInvalid())
461 return ExprError();
462 E = ExprRes.take();
Mike Stump1eb44332009-09-09 15:08:12 +0000463
Chris Lattner40378332010-05-16 04:01:30 +0000464 // __builtin_va_start takes the second argument as a "varargs" argument, but
465 // it doesn't actually do anything with it. It doesn't need to be non-pod
466 // etc.
467 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
John Wiegley429bb272011-04-08 18:41:53 +0000468 return Owned(E);
Chris Lattner40378332010-05-16 04:01:30 +0000469
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000470 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley429bb272011-04-08 18:41:53 +0000471 if (E->getType()->isObjCObjectType() &&
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000472 DiagRuntimeBehavior(E->getLocStart(), 0,
473 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
474 << E->getType() << CT))
John Wiegley429bb272011-04-08 18:41:53 +0000475 return ExprError();
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000476
John McCallf85e1932011-06-15 23:02:42 +0000477 if (!E->getType().isPODType(Context)) {
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000478 // C++0x [expr.call]p7:
479 // Passing a potentially-evaluated argument of class type (Clause 9)
480 // having a non-trivial copy constructor, a non-trivial move constructor,
481 // or a non-trivial destructor, with no corresponding parameter,
482 // is conditionally-supported with implementation-defined semantics.
483 bool TrivialEnough = false;
484 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
485 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
486 if (Record->hasTrivialCopyConstructor() &&
487 Record->hasTrivialMoveConstructor() &&
488 Record->hasTrivialDestructor())
489 TrivialEnough = true;
490 }
491 }
John McCallf85e1932011-06-15 23:02:42 +0000492
493 if (!TrivialEnough &&
494 getLangOptions().ObjCAutoRefCount &&
495 E->getType()->isObjCLifetimeType())
496 TrivialEnough = true;
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000497
498 if (TrivialEnough) {
499 // Nothing to diagnose. This is okay.
500 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000501 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000502 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor930a9ab2011-05-21 19:26:31 +0000503 << CT)) {
504 // Turn this into a trap.
505 CXXScopeSpec SS;
506 UnqualifiedId Name;
507 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
508 E->getLocStart());
509 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
510 if (TrapFn.isInvalid())
511 return ExprError();
512
513 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
514 MultiExprArg(), E->getLocEnd());
515 if (Call.isInvalid())
516 return ExprError();
517
518 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
519 Call.get(), E);
520 if (Comma.isInvalid())
521 return ExprError();
522
523 E = Comma.get();
524 }
Douglas Gregor0fd228d2011-05-21 16:27:21 +0000525 }
526
John Wiegley429bb272011-04-08 18:41:53 +0000527 return Owned(E);
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000528}
529
Chris Lattnere7a2e912008-07-25 21:10:04 +0000530/// UsualArithmeticConversions - Performs various conversions that are common to
531/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000532/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000533/// responsible for emitting appropriate error diagnostics.
534/// FIXME: verify the conversion rules for "complex int" are consistent with
535/// GCC.
Richard Trieu67e29332011-08-02 04:35:43 +0000536QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr,
537 ExprResult &rhsExpr,
Chris Lattnere7a2e912008-07-25 21:10:04 +0000538 bool isCompAssign) {
John Wiegley429bb272011-04-08 18:41:53 +0000539 if (!isCompAssign) {
540 lhsExpr = UsualUnaryConversions(lhsExpr.take());
541 if (lhsExpr.isInvalid())
542 return QualType();
543 }
Eli Friedmanab3a8522009-03-28 01:22:36 +0000544
John Wiegley429bb272011-04-08 18:41:53 +0000545 rhsExpr = UsualUnaryConversions(rhsExpr.take());
546 if (rhsExpr.isInvalid())
547 return QualType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000548
Mike Stump1eb44332009-09-09 15:08:12 +0000549 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000550 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000551 QualType lhs =
John Wiegley429bb272011-04-08 18:41:53 +0000552 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000553 QualType rhs =
John Wiegley429bb272011-04-08 18:41:53 +0000554 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000555
556 // If both types are identical, no conversion is needed.
557 if (lhs == rhs)
558 return lhs;
559
560 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
561 // The caller can deal with this (e.g. pointer + int).
562 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
563 return lhs;
564
John McCallcf33b242010-11-13 08:17:45 +0000565 // Apply unary and bitfield promotions to the LHS's type.
566 QualType lhs_unpromoted = lhs;
567 if (lhs->isPromotableIntegerType())
568 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley429bb272011-04-08 18:41:53 +0000569 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregor2d833e32009-05-02 00:36:19 +0000570 if (!LHSBitfieldPromoteTy.isNull())
571 lhs = LHSBitfieldPromoteTy;
John McCallcf33b242010-11-13 08:17:45 +0000572 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000573 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000574
John McCallcf33b242010-11-13 08:17:45 +0000575 // If both types are identical, no conversion is needed.
576 if (lhs == rhs)
577 return lhs;
578
579 // At this point, we have two different arithmetic types.
580
581 // Handle complex types first (C99 6.3.1.8p1).
582 bool LHSComplexFloat = lhs->isComplexType();
583 bool RHSComplexFloat = rhs->isComplexType();
584 if (LHSComplexFloat || RHSComplexFloat) {
585 // if we have an integer operand, the result is the complex type.
586
John McCall2bb5d002010-11-13 09:02:35 +0000587 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
588 if (rhs->isIntegerType()) {
589 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000590 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
Richard Trieu67e29332011-08-02 04:35:43 +0000591 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
592 CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000593 } else {
594 assert(rhs->isComplexIntegerType());
Richard Trieu67e29332011-08-02 04:35:43 +0000595 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
596 CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000597 }
John McCallcf33b242010-11-13 08:17:45 +0000598 return lhs;
599 }
600
John McCall2bb5d002010-11-13 09:02:35 +0000601 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
602 if (!isCompAssign) {
603 // int -> float -> _Complex float
604 if (lhs->isIntegerType()) {
605 QualType fp = cast<ComplexType>(rhs)->getElementType();
Richard Trieu67e29332011-08-02 04:35:43 +0000606 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp,
607 CK_IntegralToFloating);
608 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
609 CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000610 } else {
611 assert(lhs->isComplexIntegerType());
Richard Trieu67e29332011-08-02 04:35:43 +0000612 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
613 CK_IntegralComplexToFloatingComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000614 }
615 }
John McCallcf33b242010-11-13 08:17:45 +0000616 return rhs;
617 }
618
619 // This handles complex/complex, complex/float, or float/complex.
620 // When both operands are complex, the shorter operand is converted to the
621 // type of the longer, and that is the type of the result. This corresponds
622 // to what is done when combining two real floating-point operands.
623 // The fun begins when size promotion occur across type domains.
624 // From H&S 6.3.4: When one operand is complex and the other is a real
625 // floating-point type, the less precise type is converted, within it's
626 // real or complex domain, to the precision of the other type. For example,
627 // when combining a "long double" with a "double _Complex", the
628 // "double _Complex" is promoted to "long double _Complex".
629 int order = Context.getFloatingTypeOrder(lhs, rhs);
630
631 // If both are complex, just cast to the more precise type.
632 if (LHSComplexFloat && RHSComplexFloat) {
633 if (order > 0) {
634 // _Complex float -> _Complex double
Richard Trieu67e29332011-08-02 04:35:43 +0000635 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
636 CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000637 return lhs;
638
639 } else if (order < 0) {
640 // _Complex float -> _Complex double
641 if (!isCompAssign)
Richard Trieu67e29332011-08-02 04:35:43 +0000642 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
643 CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000644 return rhs;
645 }
646 return lhs;
647 }
648
649 // If just the LHS is complex, the RHS needs to be converted,
650 // and the LHS might need to be promoted.
651 if (LHSComplexFloat) {
652 if (order > 0) { // LHS is wider
653 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000654 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000655 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
Richard Trieu67e29332011-08-02 04:35:43 +0000656 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
657 CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000658 return lhs;
659 }
660
661 // RHS is at least as wide. Find its corresponding complex type.
662 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
663
664 // double -> _Complex double
Richard Trieu67e29332011-08-02 04:35:43 +0000665 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
666 CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000667
668 // _Complex float -> _Complex double
669 if (!isCompAssign && order < 0)
Richard Trieu67e29332011-08-02 04:35:43 +0000670 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
671 CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000672
673 return result;
674 }
675
676 // Just the RHS is complex, so the LHS needs to be converted
677 // and the RHS might need to be promoted.
678 assert(RHSComplexFloat);
679
680 if (order < 0) { // RHS is wider
681 // float -> _Complex double
John McCall2bb5d002010-11-13 09:02:35 +0000682 if (!isCompAssign) {
Argyrios Kyrtzidise1889332011-01-18 18:49:33 +0000683 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +0000684 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
Richard Trieu67e29332011-08-02 04:35:43 +0000685 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
686 CK_FloatingRealToComplex);
John McCall2bb5d002010-11-13 09:02:35 +0000687 }
John McCallcf33b242010-11-13 08:17:45 +0000688 return rhs;
689 }
690
691 // LHS is at least as wide. Find its corresponding complex type.
692 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
693
694 // double -> _Complex double
695 if (!isCompAssign)
Richard Trieu67e29332011-08-02 04:35:43 +0000696 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
697 CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000698
699 // _Complex float -> _Complex double
700 if (order > 0)
Richard Trieu67e29332011-08-02 04:35:43 +0000701 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
702 CK_FloatingComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000703
704 return result;
705 }
706
707 // Now handle "real" floating types (i.e. float, double, long double).
708 bool LHSFloat = lhs->isRealFloatingType();
709 bool RHSFloat = rhs->isRealFloatingType();
710 if (LHSFloat || RHSFloat) {
711 // If we have two real floating types, convert the smaller operand
712 // to the bigger result.
713 if (LHSFloat && RHSFloat) {
714 int order = Context.getFloatingTypeOrder(lhs, rhs);
715 if (order > 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000716 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCallcf33b242010-11-13 08:17:45 +0000717 return lhs;
718 }
719
720 assert(order < 0 && "illegal float comparison");
721 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000722 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCallcf33b242010-11-13 08:17:45 +0000723 return rhs;
724 }
725
726 // If we have an integer operand, the result is the real floating type.
727 if (LHSFloat) {
728 if (rhs->isIntegerType()) {
729 // Convert rhs to the lhs floating point type.
John Wiegley429bb272011-04-08 18:41:53 +0000730 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCallcf33b242010-11-13 08:17:45 +0000731 return lhs;
732 }
733
734 // Convert both sides to the appropriate complex float.
735 assert(rhs->isComplexIntegerType());
736 QualType result = Context.getComplexType(lhs);
737
738 // _Complex int -> _Complex float
Richard Trieu67e29332011-08-02 04:35:43 +0000739 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
740 CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000741
742 // float -> _Complex float
743 if (!isCompAssign)
Richard Trieu67e29332011-08-02 04:35:43 +0000744 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
745 CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000746
747 return result;
748 }
749
750 assert(RHSFloat);
751 if (lhs->isIntegerType()) {
752 // Convert lhs to the rhs floating point type.
753 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000754 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCallcf33b242010-11-13 08:17:45 +0000755 return rhs;
756 }
757
758 // Convert both sides to the appropriate complex float.
759 assert(lhs->isComplexIntegerType());
760 QualType result = Context.getComplexType(rhs);
761
762 // _Complex int -> _Complex float
763 if (!isCompAssign)
Richard Trieu67e29332011-08-02 04:35:43 +0000764 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
765 CK_IntegralComplexToFloatingComplex);
John McCallcf33b242010-11-13 08:17:45 +0000766
767 // float -> _Complex float
Richard Trieu67e29332011-08-02 04:35:43 +0000768 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
769 CK_FloatingRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000770
771 return result;
772 }
773
774 // Handle GCC complex int extension.
775 // FIXME: if the operands are (int, _Complex long), we currently
776 // don't promote the complex. Also, signedness?
777 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
778 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
779 if (lhsComplexInt && rhsComplexInt) {
780 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
781 rhsComplexInt->getElementType());
782 assert(order && "inequal types with equal element ordering");
783 if (order > 0) {
784 // _Complex int -> _Complex long
John Wiegley429bb272011-04-08 18:41:53 +0000785 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000786 return lhs;
787 }
788
789 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000790 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCallcf33b242010-11-13 08:17:45 +0000791 return rhs;
792 } else if (lhsComplexInt) {
793 // int -> _Complex int
John Wiegley429bb272011-04-08 18:41:53 +0000794 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000795 return lhs;
796 } else if (rhsComplexInt) {
797 // int -> _Complex int
798 if (!isCompAssign)
Richard Trieu67e29332011-08-02 04:35:43 +0000799 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
800 CK_IntegralRealToComplex);
John McCallcf33b242010-11-13 08:17:45 +0000801 return rhs;
802 }
803
804 // Finally, we have two differing integer types.
805 // The rules for this case are in C99 6.3.1.8
806 int compare = Context.getIntegerTypeOrder(lhs, rhs);
807 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
808 rhsSigned = rhs->hasSignedIntegerRepresentation();
809 if (lhsSigned == rhsSigned) {
810 // Same signedness; use the higher-ranked type
811 if (compare >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000812 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000813 return lhs;
814 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000815 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000816 return rhs;
817 } else if (compare != (lhsSigned ? 1 : -1)) {
818 // The unsigned type has greater than or equal rank to the
819 // signed type, so use the unsigned type
820 if (rhsSigned) {
John Wiegley429bb272011-04-08 18:41:53 +0000821 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000822 return lhs;
823 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000824 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000825 return rhs;
826 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
827 // The two types are different widths; if we are here, that
828 // means the signed type is larger than the unsigned type, so
829 // use the signed type.
830 if (lhsSigned) {
John Wiegley429bb272011-04-08 18:41:53 +0000831 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000832 return lhs;
833 } else if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000834 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000835 return rhs;
836 } else {
837 // The signed type is higher-ranked than the unsigned type,
838 // but isn't actually any bigger (like unsigned int and long
839 // on most 32-bit systems). Use the unsigned type corresponding
840 // to the signed type.
841 QualType result =
842 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley429bb272011-04-08 18:41:53 +0000843 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000844 if (!isCompAssign)
John Wiegley429bb272011-04-08 18:41:53 +0000845 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCallcf33b242010-11-13 08:17:45 +0000846 return result;
847 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000848}
849
Chris Lattnere7a2e912008-07-25 21:10:04 +0000850//===----------------------------------------------------------------------===//
851// Semantic Analysis for various Expression Types
852//===----------------------------------------------------------------------===//
853
854
Peter Collingbournef111d932011-04-15 00:35:48 +0000855ExprResult
856Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
857 SourceLocation DefaultLoc,
858 SourceLocation RParenLoc,
859 Expr *ControllingExpr,
860 MultiTypeArg types,
861 MultiExprArg exprs) {
862 unsigned NumAssocs = types.size();
863 assert(NumAssocs == exprs.size());
864
865 ParsedType *ParsedTypes = types.release();
866 Expr **Exprs = exprs.release();
867
868 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
869 for (unsigned i = 0; i < NumAssocs; ++i) {
870 if (ParsedTypes[i])
871 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
872 else
873 Types[i] = 0;
874 }
875
876 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
877 ControllingExpr, Types, Exprs,
878 NumAssocs);
Benjamin Kramer5bf47f72011-04-15 11:21:57 +0000879 delete [] Types;
Peter Collingbournef111d932011-04-15 00:35:48 +0000880 return ER;
881}
882
883ExprResult
884Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
885 SourceLocation DefaultLoc,
886 SourceLocation RParenLoc,
887 Expr *ControllingExpr,
888 TypeSourceInfo **Types,
889 Expr **Exprs,
890 unsigned NumAssocs) {
891 bool TypeErrorFound = false,
892 IsResultDependent = ControllingExpr->isTypeDependent(),
893 ContainsUnexpandedParameterPack
894 = ControllingExpr->containsUnexpandedParameterPack();
895
896 for (unsigned i = 0; i < NumAssocs; ++i) {
897 if (Exprs[i]->containsUnexpandedParameterPack())
898 ContainsUnexpandedParameterPack = true;
899
900 if (Types[i]) {
901 if (Types[i]->getType()->containsUnexpandedParameterPack())
902 ContainsUnexpandedParameterPack = true;
903
904 if (Types[i]->getType()->isDependentType()) {
905 IsResultDependent = true;
906 } else {
907 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
908 // complete object type other than a variably modified type."
909 unsigned D = 0;
910 if (Types[i]->getType()->isIncompleteType())
911 D = diag::err_assoc_type_incomplete;
912 else if (!Types[i]->getType()->isObjectType())
913 D = diag::err_assoc_type_nonobject;
914 else if (Types[i]->getType()->isVariablyModifiedType())
915 D = diag::err_assoc_type_variably_modified;
916
917 if (D != 0) {
918 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
919 << Types[i]->getTypeLoc().getSourceRange()
920 << Types[i]->getType();
921 TypeErrorFound = true;
922 }
923
924 // C1X 6.5.1.1p2 "No two generic associations in the same generic
925 // selection shall specify compatible types."
926 for (unsigned j = i+1; j < NumAssocs; ++j)
927 if (Types[j] && !Types[j]->getType()->isDependentType() &&
928 Context.typesAreCompatible(Types[i]->getType(),
929 Types[j]->getType())) {
930 Diag(Types[j]->getTypeLoc().getBeginLoc(),
931 diag::err_assoc_compatible_types)
932 << Types[j]->getTypeLoc().getSourceRange()
933 << Types[j]->getType()
934 << Types[i]->getType();
935 Diag(Types[i]->getTypeLoc().getBeginLoc(),
936 diag::note_compat_assoc)
937 << Types[i]->getTypeLoc().getSourceRange()
938 << Types[i]->getType();
939 TypeErrorFound = true;
940 }
941 }
942 }
943 }
944 if (TypeErrorFound)
945 return ExprError();
946
947 // If we determined that the generic selection is result-dependent, don't
948 // try to compute the result expression.
949 if (IsResultDependent)
950 return Owned(new (Context) GenericSelectionExpr(
951 Context, KeyLoc, ControllingExpr,
952 Types, Exprs, NumAssocs, DefaultLoc,
953 RParenLoc, ContainsUnexpandedParameterPack));
954
Chris Lattner5f9e2722011-07-23 10:55:15 +0000955 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbournef111d932011-04-15 00:35:48 +0000956 unsigned DefaultIndex = -1U;
957 for (unsigned i = 0; i < NumAssocs; ++i) {
958 if (!Types[i])
959 DefaultIndex = i;
960 else if (Context.typesAreCompatible(ControllingExpr->getType(),
961 Types[i]->getType()))
962 CompatIndices.push_back(i);
963 }
964
965 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
966 // type compatible with at most one of the types named in its generic
967 // association list."
968 if (CompatIndices.size() > 1) {
969 // We strip parens here because the controlling expression is typically
970 // parenthesized in macro definitions.
971 ControllingExpr = ControllingExpr->IgnoreParens();
972 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
973 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
974 << (unsigned) CompatIndices.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000975 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbournef111d932011-04-15 00:35:48 +0000976 E = CompatIndices.end(); I != E; ++I) {
977 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
978 diag::note_compat_assoc)
979 << Types[*I]->getTypeLoc().getSourceRange()
980 << Types[*I]->getType();
981 }
982 return ExprError();
983 }
984
985 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
986 // its controlling expression shall have type compatible with exactly one of
987 // the types named in its generic association list."
988 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
989 // We strip parens here because the controlling expression is typically
990 // parenthesized in macro definitions.
991 ControllingExpr = ControllingExpr->IgnoreParens();
992 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
993 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
994 return ExprError();
995 }
996
997 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
998 // type name that is compatible with the type of the controlling expression,
999 // then the result expression of the generic selection is the expression
1000 // in that generic association. Otherwise, the result expression of the
1001 // generic selection is the expression in the default generic association."
1002 unsigned ResultIndex =
1003 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1004
1005 return Owned(new (Context) GenericSelectionExpr(
1006 Context, KeyLoc, ControllingExpr,
1007 Types, Exprs, NumAssocs, DefaultLoc,
1008 RParenLoc, ContainsUnexpandedParameterPack,
1009 ResultIndex));
1010}
1011
Steve Narofff69936d2007-09-16 03:34:24 +00001012/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +00001013/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1014/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1015/// multiple tokens. However, the common case is that StringToks points to one
1016/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001017///
John McCall60d7b3a2010-08-24 06:29:42 +00001018ExprResult
Sean Hunt6cf75022010-08-30 17:47:05 +00001019Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001020 assert(NumStringToks && "Must have at least one string!");
1021
Chris Lattnerbbee00b2009-01-16 18:51:42 +00001022 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001023 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001024 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001025
Chris Lattner5f9e2722011-07-23 10:55:15 +00001026 SmallVector<SourceLocation, 4> StringTokLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +00001027 for (unsigned i = 0; i != NumStringToks; ++i)
1028 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001029
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001030 QualType StrTy = Context.CharTy;
Douglas Gregor5cee1192011-07-27 05:40:30 +00001031 if (Literal.isWide())
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001032 StrTy = Context.getWCharType();
Douglas Gregor5cee1192011-07-27 05:40:30 +00001033 else if (Literal.isUTF16())
1034 StrTy = Context.Char16Ty;
1035 else if (Literal.isUTF32())
1036 StrTy = Context.Char32Ty;
Anders Carlsson96b4adc2011-04-06 18:42:48 +00001037 else if (Literal.Pascal)
1038 StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +00001039
Douglas Gregor5cee1192011-07-27 05:40:30 +00001040 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1041 if (Literal.isWide())
1042 Kind = StringLiteral::Wide;
1043 else if (Literal.isUTF8())
1044 Kind = StringLiteral::UTF8;
1045 else if (Literal.isUTF16())
1046 Kind = StringLiteral::UTF16;
1047 else if (Literal.isUTF32())
1048 Kind = StringLiteral::UTF32;
1049
Douglas Gregor77a52232008-09-12 00:47:35 +00001050 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattner7dc480f2010-06-15 18:05:34 +00001051 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregor77a52232008-09-12 00:47:35 +00001052 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001053
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001054 // Get an array type for the string, according to C99 6.4.5. This includes
1055 // the nul terminator character as well as the string length for pascal
1056 // strings.
1057 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001058 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001059 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001060
Reid Spencer5f016e22007-07-11 17:01:13 +00001061 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Sean Hunt6cf75022010-08-30 17:47:05 +00001062 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00001063 Kind, Literal.Pascal, StrTy,
Sean Hunt6cf75022010-08-30 17:47:05 +00001064 &StringTokLocs[0],
1065 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001066}
1067
John McCall469a1eb2011-02-02 13:00:07 +00001068enum CaptureResult {
1069 /// No capture is required.
1070 CR_NoCapture,
1071
1072 /// A capture is required.
1073 CR_Capture,
1074
John McCall6b5a61b2011-02-07 10:33:21 +00001075 /// A by-ref capture is required.
1076 CR_CaptureByRef,
1077
John McCall469a1eb2011-02-02 13:00:07 +00001078 /// An error occurred when trying to capture the given variable.
1079 CR_Error
1080};
1081
1082/// Diagnose an uncapturable value reference.
Chris Lattner639e2d32008-10-20 05:16:36 +00001083///
John McCall469a1eb2011-02-02 13:00:07 +00001084/// \param var - the variable referenced
1085/// \param DC - the context which we couldn't capture through
1086static CaptureResult
John McCall6b5a61b2011-02-07 10:33:21 +00001087diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001088 VarDecl *var, DeclContext *DC) {
1089 switch (S.ExprEvalContexts.back().Context) {
1090 case Sema::Unevaluated:
1091 // The argument will never be evaluated, so don't complain.
1092 return CR_NoCapture;
Mike Stump1eb44332009-09-09 15:08:12 +00001093
John McCall469a1eb2011-02-02 13:00:07 +00001094 case Sema::PotentiallyEvaluated:
1095 case Sema::PotentiallyEvaluatedIfUsed:
1096 break;
Chris Lattner639e2d32008-10-20 05:16:36 +00001097
John McCall469a1eb2011-02-02 13:00:07 +00001098 case Sema::PotentiallyPotentiallyEvaluated:
1099 // FIXME: delay these!
1100 break;
Chris Lattner17f3a6d2009-04-21 22:26:47 +00001101 }
Mike Stump1eb44332009-09-09 15:08:12 +00001102
John McCall469a1eb2011-02-02 13:00:07 +00001103 // Don't diagnose about capture if we're not actually in code right
1104 // now; in general, there are more appropriate places that will
1105 // diagnose this.
1106 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1107
John McCall4f38f412011-03-22 23:15:50 +00001108 // Certain madnesses can happen with parameter declarations, which
1109 // we want to ignore.
1110 if (isa<ParmVarDecl>(var)) {
1111 // - If the parameter still belongs to the translation unit, then
1112 // we're actually just using one parameter in the declaration of
1113 // the next. This is useful in e.g. VLAs.
1114 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1115 return CR_NoCapture;
1116
1117 // - This particular madness can happen in ill-formed default
1118 // arguments; claim it's okay and let downstream code handle it.
1119 if (S.CurContext == var->getDeclContext()->getParent())
1120 return CR_NoCapture;
1121 }
John McCall469a1eb2011-02-02 13:00:07 +00001122
1123 DeclarationName functionName;
1124 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1125 functionName = fn->getDeclName();
1126 // FIXME: variable from enclosing block that we couldn't capture from!
1127
1128 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1129 << var->getIdentifier() << functionName;
1130 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1131 << var->getIdentifier();
1132
1133 return CR_Error;
Mike Stump1eb44332009-09-09 15:08:12 +00001134}
1135
John McCall6b5a61b2011-02-07 10:33:21 +00001136/// There is a well-formed capture at a particular scope level;
1137/// propagate it through all the nested blocks.
1138static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1139 const BlockDecl::Capture &capture) {
1140 VarDecl *var = capture.getVariable();
1141
1142 // Update all the inner blocks with the capture information.
1143 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1144 i != e; ++i) {
1145 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1146 innerBlock->Captures.push_back(
1147 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1148 /*nested*/ true, capture.getCopyExpr()));
1149 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1150 }
1151
1152 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1153}
1154
1155/// shouldCaptureValueReference - Determine if a reference to the
John McCall469a1eb2011-02-02 13:00:07 +00001156/// given value in the current context requires a variable capture.
1157///
1158/// This also keeps the captures set in the BlockScopeInfo records
1159/// up-to-date.
John McCall6b5a61b2011-02-07 10:33:21 +00001160static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCall469a1eb2011-02-02 13:00:07 +00001161 ValueDecl *value) {
1162 // Only variables ever require capture.
1163 VarDecl *var = dyn_cast<VarDecl>(value);
John McCall76a40212011-02-09 01:13:10 +00001164 if (!var) return CR_NoCapture;
John McCall469a1eb2011-02-02 13:00:07 +00001165
1166 // Fast path: variables from the current context never require capture.
1167 DeclContext *DC = S.CurContext;
1168 if (var->getDeclContext() == DC) return CR_NoCapture;
1169
1170 // Only variables with local storage require capture.
1171 // FIXME: What about 'const' variables in C++?
1172 if (!var->hasLocalStorage()) return CR_NoCapture;
1173
1174 // Otherwise, we need to capture.
1175
1176 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCall469a1eb2011-02-02 13:00:07 +00001177 do {
1178 // Only blocks (and eventually C++0x closures) can capture; other
1179 // scopes don't work.
1180 if (!isa<BlockDecl>(DC))
John McCall6b5a61b2011-02-07 10:33:21 +00001181 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCall469a1eb2011-02-02 13:00:07 +00001182
1183 BlockScopeInfo *blockScope =
1184 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1185 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1186
John McCall6b5a61b2011-02-07 10:33:21 +00001187 // Check whether we've already captured it in this block. If so,
1188 // we're done.
1189 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1190 return propagateCapture(S, functionScopesIndex,
1191 blockScope->Captures[indexPlus1 - 1]);
John McCall469a1eb2011-02-02 13:00:07 +00001192
1193 functionScopesIndex--;
1194 DC = cast<BlockDecl>(DC)->getDeclContext();
1195 } while (var->getDeclContext() != DC);
1196
John McCall6b5a61b2011-02-07 10:33:21 +00001197 // Okay, we descended all the way to the block that defines the variable.
1198 // Actually try to capture it.
1199 QualType type = var->getType();
1200
1201 // Prohibit variably-modified types.
1202 if (type->isVariablyModifiedType()) {
1203 S.Diag(loc, diag::err_ref_vm_type);
1204 S.Diag(var->getLocation(), diag::note_declared_at);
1205 return CR_Error;
1206 }
1207
1208 // Prohibit arrays, even in __block variables, but not references to
1209 // them.
1210 if (type->isArrayType()) {
1211 S.Diag(loc, diag::err_ref_array_type);
1212 S.Diag(var->getLocation(), diag::note_declared_at);
1213 return CR_Error;
1214 }
1215
1216 S.MarkDeclarationReferenced(loc, var);
1217
1218 // The BlocksAttr indicates the variable is bound by-reference.
1219 bool byRef = var->hasAttr<BlocksAttr>();
1220
1221 // Build a copy expression.
1222 Expr *copyExpr = 0;
John McCall642a75f2011-04-28 02:15:35 +00001223 const RecordType *rtype;
1224 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1225 (rtype = type->getAs<RecordType>())) {
1226
1227 // The capture logic needs the destructor, so make sure we mark it.
1228 // Usually this is unnecessary because most local variables have
1229 // their destructors marked at declaration time, but parameters are
1230 // an exception because it's technically only the call site that
1231 // actually requires the destructor.
1232 if (isa<ParmVarDecl>(var))
1233 S.FinalizeVarWithDestructor(var, rtype);
1234
John McCall6b5a61b2011-02-07 10:33:21 +00001235 // According to the blocks spec, the capture of a variable from
1236 // the stack requires a const copy constructor. This is not true
1237 // of the copy/move done to move a __block variable to the heap.
1238 type.addConst();
1239
1240 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1241 ExprResult result =
1242 S.PerformCopyInitialization(
1243 InitializedEntity::InitializeBlock(var->getLocation(),
1244 type, false),
1245 loc, S.Owned(declRef));
1246
1247 // Build a full-expression copy expression if initialization
1248 // succeeded and used a non-trivial constructor. Recover from
1249 // errors by pretending that the copy isn't necessary.
1250 if (!result.isInvalid() &&
1251 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1252 result = S.MaybeCreateExprWithCleanups(result);
1253 copyExpr = result.take();
1254 }
1255 }
1256
1257 // We're currently at the declarer; go back to the closure.
1258 functionScopesIndex++;
1259 BlockScopeInfo *blockScope =
1260 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1261
1262 // Build a valid capture in this scope.
1263 blockScope->Captures.push_back(
1264 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1265 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1266
1267 // Propagate that to inner captures if necessary.
1268 return propagateCapture(S, functionScopesIndex,
1269 blockScope->Captures.back());
1270}
1271
1272static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1273 const DeclarationNameInfo &NameInfo,
1274 bool byRef) {
1275 assert(isa<VarDecl>(vd) && "capturing non-variable");
1276
1277 VarDecl *var = cast<VarDecl>(vd);
1278 assert(var->hasLocalStorage() && "capturing non-local");
1279 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1280
1281 QualType exprType = var->getType().getNonReferenceType();
1282
1283 BlockDeclRefExpr *BDRE;
1284 if (!byRef) {
1285 // The variable will be bound by copy; make it const within the
1286 // closure, but record that this was done in the expression.
1287 bool constAdded = !exprType.isConstQualified();
1288 exprType.addConst();
1289
1290 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1291 NameInfo.getLoc(), false,
1292 constAdded);
1293 } else {
1294 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1295 NameInfo.getLoc(), true);
1296 }
1297
1298 return S.Owned(BDRE);
John McCall469a1eb2011-02-02 13:00:07 +00001299}
Chris Lattner639e2d32008-10-20 05:16:36 +00001300
John McCall60d7b3a2010-08-24 06:29:42 +00001301ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001302Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCall76a40212011-02-09 01:13:10 +00001303 SourceLocation Loc,
1304 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001305 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCallf89e55a2010-11-18 06:31:45 +00001306 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnara25777432010-08-11 22:01:17 +00001307}
1308
John McCall76a40212011-02-09 01:13:10 +00001309/// BuildDeclRefExpr - Build an expression that references a
1310/// declaration that does not require a closure capture.
John McCall60d7b3a2010-08-24 06:29:42 +00001311ExprResult
John McCall76a40212011-02-09 01:13:10 +00001312Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnara25777432010-08-11 22:01:17 +00001313 const DeclarationNameInfo &NameInfo,
1314 const CXXScopeSpec *SS) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001315 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump1eb44332009-09-09 15:08:12 +00001316
John McCall7eb0a9e2010-11-24 05:12:34 +00001317 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregor40d96a62011-02-28 21:54:11 +00001318 SS? SS->getWithLocInContext(Context)
1319 : NestedNameSpecifierLoc(),
John McCall7eb0a9e2010-11-24 05:12:34 +00001320 D, NameInfo, Ty, VK);
1321
1322 // Just in case we're building an illegal pointer-to-member.
1323 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1324 E->setObjectKind(OK_BitField);
1325
1326 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +00001327}
1328
Abramo Bagnara25777432010-08-11 22:01:17 +00001329/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall129e2df2009-11-30 22:42:35 +00001330/// possibly a list of template arguments.
1331///
1332/// If this produces template arguments, it is permitted to call
1333/// DecomposeTemplateName.
1334///
1335/// This actually loses a lot of source location information for
1336/// non-standard name kinds; we should consider preserving that in
1337/// some way.
Richard Trieu67e29332011-08-02 04:35:43 +00001338void
1339Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1340 TemplateArgumentListInfo &Buffer,
1341 DeclarationNameInfo &NameInfo,
1342 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall129e2df2009-11-30 22:42:35 +00001343 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1344 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1345 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1346
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001347 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall129e2df2009-11-30 22:42:35 +00001348 Id.TemplateId->getTemplateArgs(),
1349 Id.TemplateId->NumArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001350 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall129e2df2009-11-30 22:42:35 +00001351 TemplateArgsPtr.release();
1352
John McCall2b5289b2010-08-23 07:28:44 +00001353 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00001354 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001355 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall129e2df2009-11-30 22:42:35 +00001356 TemplateArgs = &Buffer;
1357 } else {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001358 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall129e2df2009-11-30 22:42:35 +00001359 TemplateArgs = 0;
1360 }
1361}
1362
John McCall578b69b2009-12-16 08:11:27 +00001363/// Diagnose an empty lookup.
1364///
1365/// \return false if new lookup candidates were found
Nick Lewycky03d98c52010-07-06 19:51:49 +00001366bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001367 CorrectTypoContext CTC, Expr **Args,
1368 unsigned NumArgs) {
John McCall578b69b2009-12-16 08:11:27 +00001369 DeclarationName Name = R.getLookupName();
1370
John McCall578b69b2009-12-16 08:11:27 +00001371 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001372 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +00001373 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1374 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001375 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +00001376 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001377 diagnostic_suggest = diag::err_undeclared_use_suggest;
1378 }
John McCall578b69b2009-12-16 08:11:27 +00001379
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001380 // If the original lookup was an unqualified lookup, fake an
1381 // unqualified lookup. This is useful when (for example) the
1382 // original lookup would not have found something because it was a
1383 // dependent name.
Nick Lewycky03d98c52010-07-06 19:51:49 +00001384 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001385 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +00001386 if (isa<CXXRecordDecl>(DC)) {
1387 LookupQualifiedName(R, DC);
1388
1389 if (!R.empty()) {
1390 // Don't give errors about ambiguities in this lookup.
1391 R.suppressDiagnostics();
1392
1393 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1394 bool isInstance = CurMethod &&
1395 CurMethod->isInstance() &&
1396 DC == CurMethod->getParent();
1397
1398 // Give a code modification hint to insert 'this->'.
1399 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1400 // Actually quite difficult!
Nick Lewycky03d98c52010-07-06 19:51:49 +00001401 if (isInstance) {
Nick Lewycky03d98c52010-07-06 19:51:49 +00001402 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1403 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001404 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewycky03d98c52010-07-06 19:51:49 +00001405 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedmana7e68452010-08-22 01:00:03 +00001406 if (DepMethod) {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001407 Diag(R.getNameLoc(), diagnostic) << Name
1408 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1409 QualType DepThisType = DepMethod->getThisType(Context);
1410 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1411 R.getNameLoc(), DepThisType, false);
1412 TemplateArgumentListInfo TList;
1413 if (ULE->hasExplicitTemplateArgs())
1414 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001415
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001416 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00001417 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001418 CXXDependentScopeMemberExpr *DepExpr =
1419 CXXDependentScopeMemberExpr::Create(
1420 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregor7c3179c2011-02-28 18:50:33 +00001421 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001422 R.getLookupNameInfo(), &TList);
1423 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedmana7e68452010-08-22 01:00:03 +00001424 } else {
Nick Lewyckyd9ca4ab2010-08-20 20:54:15 +00001425 // FIXME: we should be able to handle this case too. It is correct
1426 // to add this-> here. This is a workaround for PR7947.
1427 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedmana7e68452010-08-22 01:00:03 +00001428 }
Nick Lewycky03d98c52010-07-06 19:51:49 +00001429 } else {
John McCall578b69b2009-12-16 08:11:27 +00001430 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewycky03d98c52010-07-06 19:51:49 +00001431 }
John McCall578b69b2009-12-16 08:11:27 +00001432
1433 // Do we really want to note all of these?
1434 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1435 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1436
1437 // Tell the callee to try to recover.
1438 return false;
1439 }
Douglas Gregore26f0432010-08-09 22:38:14 +00001440
1441 R.clear();
John McCall578b69b2009-12-16 08:11:27 +00001442 }
1443 }
1444
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001445 // We didn't find anything, so try to correct for a typo.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001446 TypoCorrection Corrected;
1447 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1448 S, &SS, NULL, false, CTC))) {
1449 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1450 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1451 R.setLookupName(Corrected.getCorrection());
1452
Hans Wennborg701d1e72011-07-12 08:45:31 +00001453 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001454 if (Corrected.isOverloaded()) {
1455 OverloadCandidateSet OCS(R.getNameLoc());
1456 OverloadCandidateSet::iterator Best;
1457 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1458 CDEnd = Corrected.end();
1459 CD != CDEnd; ++CD) {
1460 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1461 AddOverloadCandidate(FD, DeclAccessPair::make(*CD, AS_none),
1462 Args, NumArgs, OCS);
1463 // TODO: Handle FunctionTemplateDecl and other Decl types that
1464 // support overloading and could be corrected by CorrectTypo.
1465 }
1466 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1467 case OR_Success:
1468 ND = Best->Function;
1469 break;
1470 default:
Kaelyn Uhrain844d5722011-08-04 23:30:54 +00001471 break;
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00001472 }
1473 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001474 R.addDecl(ND);
1475 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001476 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001477 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1478 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregoraaf87162010-04-14 20:04:41 +00001479 else
1480 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001481 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001482 << SS.getRange()
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001483 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1484 if (ND)
Douglas Gregoraaf87162010-04-14 20:04:41 +00001485 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001486 << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001487
1488 // Tell the callee to try to recover.
1489 return false;
1490 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001491
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001492 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +00001493 // FIXME: If we ended up with a typo for a type name or
1494 // Objective-C class name, we're in trouble because the parser
1495 // is in the wrong place to recover. Suggest the typo
1496 // correction, but don't make it a fix-it since we're not going
1497 // to recover well anyway.
1498 if (SS.isEmpty())
Richard Trieu67e29332011-08-02 04:35:43 +00001499 Diag(R.getNameLoc(), diagnostic_suggest)
1500 << Name << CorrectedQuotedStr;
Douglas Gregoraaf87162010-04-14 20:04:41 +00001501 else
1502 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001503 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001504 << SS.getRange();
1505
1506 // Don't try to recover; it won't work.
1507 return true;
1508 }
1509 } else {
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001510 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregoraaf87162010-04-14 20:04:41 +00001511 // because we aren't able to recover.
Douglas Gregord203a162010-01-01 00:15:04 +00001512 if (SS.isEmpty())
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001513 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001514 else
Douglas Gregord203a162010-01-01 00:15:04 +00001515 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001516 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregoraaf87162010-04-14 20:04:41 +00001517 << SS.getRange();
Douglas Gregord203a162010-01-01 00:15:04 +00001518 return true;
1519 }
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001520 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001521 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001522
1523 // Emit a special diagnostic for failed member lookups.
1524 // FIXME: computing the declaration context might fail here (?)
1525 if (!SS.isEmpty()) {
1526 Diag(R.getNameLoc(), diag::err_no_member)
1527 << Name << computeDeclContext(SS, false)
1528 << SS.getRange();
1529 return true;
1530 }
1531
John McCall578b69b2009-12-16 08:11:27 +00001532 // Give up, we can't recover.
1533 Diag(R.getNameLoc(), diagnostic) << Name;
1534 return true;
1535}
1536
Douglas Gregorca45da02010-11-02 20:36:02 +00001537ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1538 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001539 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1540 if (!IDecl)
1541 return 0;
1542 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1543 if (!ClassImpDecl)
1544 return 0;
Douglas Gregorca45da02010-11-02 20:36:02 +00001545 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001546 if (!property)
1547 return 0;
1548 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregorca45da02010-11-02 20:36:02 +00001549 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1550 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001551 return 0;
1552 return property;
1553}
1554
Douglas Gregorca45da02010-11-02 20:36:02 +00001555bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1556 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1557 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1558 if (!IDecl)
1559 return false;
1560 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1561 if (!ClassImpDecl)
1562 return false;
1563 if (ObjCPropertyImplDecl *PIDecl
1564 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1565 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1566 PIDecl->getPropertyIvarDecl())
1567 return false;
1568
1569 return true;
1570}
1571
Douglas Gregor312eadb2011-04-24 05:37:28 +00001572ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1573 IdentifierInfo *II,
1574 SourceLocation NameLoc) {
1575 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001576 bool LookForIvars;
1577 if (Lookup.empty())
1578 LookForIvars = true;
1579 else if (CurMeth->isClassMethod())
1580 LookForIvars = false;
1581 else
1582 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahaniand0fbadd2011-01-26 00:57:01 +00001583 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1584 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian73f666f2010-07-30 16:59:05 +00001585 if (!LookForIvars)
1586 return 0;
1587
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001588 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1589 if (!IDecl)
1590 return 0;
1591 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian84ef4b22010-07-19 16:14:33 +00001592 if (!ClassImpDecl)
1593 return 0;
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001594 bool DynamicImplSeen = false;
Douglas Gregor312eadb2011-04-24 05:37:28 +00001595 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001596 if (!property)
1597 return 0;
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001598 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001599 DynamicImplSeen =
1600 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanian43e1b462010-10-19 19:08:23 +00001601 // property implementation has a designated ivar. No need to assume a new
1602 // one.
1603 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1604 return 0;
1605 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001606 if (!DynamicImplSeen) {
Douglas Gregor312eadb2011-04-24 05:37:28 +00001607 QualType PropType = Context.getCanonicalType(property->getType());
1608 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001609 NameLoc, NameLoc,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001610 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian75049662010-12-15 23:29:04 +00001611 ObjCIvarDecl::Private,
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001612 (Expr *)0, true);
1613 ClassImpDecl->addDecl(Ivar);
1614 IDecl->makeDeclVisibleInContext(Ivar, false);
1615 property->setPropertyIvarDecl(Ivar);
1616 return Ivar;
1617 }
1618 return 0;
1619}
1620
John McCall60d7b3a2010-08-24 06:29:42 +00001621ExprResult Sema::ActOnIdExpression(Scope *S,
John McCallfb97e752010-08-24 22:52:39 +00001622 CXXScopeSpec &SS,
1623 UnqualifiedId &Id,
1624 bool HasTrailingLParen,
1625 bool isAddressOfOperand) {
John McCallf7a1a742009-11-24 19:00:30 +00001626 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1627 "cannot be direct & operand and have a trailing lparen");
1628
1629 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001630 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001631
John McCall129e2df2009-11-30 22:42:35 +00001632 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001633
1634 // Decompose the UnqualifiedId into the following data.
Abramo Bagnara25777432010-08-11 22:01:17 +00001635 DeclarationNameInfo NameInfo;
John McCallf7a1a742009-11-24 19:00:30 +00001636 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001637 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001638
Abramo Bagnara25777432010-08-11 22:01:17 +00001639 DeclarationName Name = NameInfo.getName();
Douglas Gregor10c42622008-11-18 15:03:34 +00001640 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnara25777432010-08-11 22:01:17 +00001641 SourceLocation NameLoc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00001642
John McCallf7a1a742009-11-24 19:00:30 +00001643 // C++ [temp.dep.expr]p3:
1644 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001645 // -- an identifier that was declared with a dependent type,
1646 // (note: handled after lookup)
1647 // -- a template-id that is dependent,
1648 // (note: handled in BuildTemplateIdExpr)
1649 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001650 // -- a nested-name-specifier that contains a class-name that
1651 // names a dependent type.
1652 // Determine whether this is a member of an unknown specialization;
1653 // we need to handle these differently.
Eli Friedman647c8b32010-08-06 23:41:47 +00001654 bool DependentID = false;
1655 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1656 Name.getCXXNameType()->isDependentType()) {
1657 DependentID = true;
1658 } else if (SS.isSet()) {
Chris Lattner337e5502011-02-18 01:27:55 +00001659 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman647c8b32010-08-06 23:41:47 +00001660 if (RequireCompleteDeclContext(SS, DC))
1661 return ExprError();
Eli Friedman647c8b32010-08-06 23:41:47 +00001662 } else {
1663 DependentID = true;
1664 }
1665 }
1666
Chris Lattner337e5502011-02-18 01:27:55 +00001667 if (DependentID)
Abramo Bagnara25777432010-08-11 22:01:17 +00001668 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001669 TemplateArgs);
Chris Lattner337e5502011-02-18 01:27:55 +00001670
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001671 bool IvarLookupFollowUp = false;
John McCallf7a1a742009-11-24 19:00:30 +00001672 // Perform the required lookup.
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001673 LookupResult R(*this, NameInfo,
1674 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1675 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001676 if (TemplateArgs) {
Douglas Gregord2235f62010-05-20 20:58:56 +00001677 // Lookup the template name again to correctly establish the context in
1678 // which it was found. This is really unfortunate as we already did the
1679 // lookup to determine that it was a template name in the first place. If
1680 // this becomes a performance hit, we can work harder to preserve those
1681 // results until we get here but it's likely not worth it.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001682 bool MemberOfUnknownSpecialization;
1683 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1684 MemberOfUnknownSpecialization);
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001685
1686 if (MemberOfUnknownSpecialization ||
1687 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1688 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1689 TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +00001690 } else {
Fariborz Jahanian69d56242010-07-22 23:33:21 +00001691 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001692 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Douglas Gregor2f9f89c2011-02-04 13:35:07 +00001694 // If the result might be in a dependent base class, this is a dependent
1695 // id-expression.
1696 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1697 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1698 TemplateArgs);
1699
John McCallf7a1a742009-11-24 19:00:30 +00001700 // If this reference is in an Objective-C method, then we need to do
1701 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001702 if (IvarLookupFollowUp) {
John McCall60d7b3a2010-08-24 06:29:42 +00001703 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001704 if (E.isInvalid())
1705 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001706
Chris Lattner337e5502011-02-18 01:27:55 +00001707 if (Expr *Ex = E.takeAs<Expr>())
1708 return Owned(Ex);
1709
1710 // Synthesize ivars lazily.
Fariborz Jahaniane776f882011-01-03 18:08:02 +00001711 if (getLangOptions().ObjCDefaultSynthProperties &&
1712 getLangOptions().ObjCNonFragileABI2) {
Douglas Gregor312eadb2011-04-24 05:37:28 +00001713 if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
Fariborz Jahaniande267602010-11-17 19:41:23 +00001714 if (const ObjCPropertyDecl *Property =
1715 canSynthesizeProvisionalIvar(II)) {
1716 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1717 Diag(Property->getLocation(), diag::note_property_declare);
1718 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001719 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1720 isAddressOfOperand);
Fariborz Jahaniande267602010-11-17 19:41:23 +00001721 }
Fariborz Jahanianad51e742010-07-17 00:59:30 +00001722 }
Fariborz Jahanianf759b4d2010-08-13 18:09:39 +00001723 // for further use, this must be set to false if in class method.
1724 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffe3e9add2008-06-02 23:03:37 +00001725 }
Chris Lattner8a934232008-03-31 00:36:02 +00001726 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001727
John McCallf7a1a742009-11-24 19:00:30 +00001728 if (R.isAmbiguous())
1729 return ExprError();
1730
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001731 // Determine whether this name might be a candidate for
1732 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001733 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001734
John McCallf7a1a742009-11-24 19:00:30 +00001735 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001736 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001737 // in C90, extension in C99, forbidden in C++).
1738 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1739 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1740 if (D) R.addDecl(D);
1741 }
1742
1743 // If this name wasn't predeclared and if this is not a function
1744 // call, diagnose the problem.
1745 if (R.empty()) {
Douglas Gregor91f7ac72010-05-18 16:14:23 +00001746 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCall578b69b2009-12-16 08:11:27 +00001747 return ExprError();
1748
1749 assert(!R.empty() &&
1750 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001751
1752 // If we found an Objective-C instance variable, let
1753 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001754 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001755 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1756 R.clear();
John McCall60d7b3a2010-08-24 06:29:42 +00001757 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001758 assert(E.isInvalid() || E.get());
1759 return move(E);
1760 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001761 }
1762 }
Mike Stump1eb44332009-09-09 15:08:12 +00001763
John McCallf7a1a742009-11-24 19:00:30 +00001764 // This is guaranteed from this point on.
1765 assert(!R.empty() || ADL);
1766
John McCallaa81e162009-12-01 22:10:20 +00001767 // Check whether this might be a C++ implicit instance member access.
John McCallfb97e752010-08-24 22:52:39 +00001768 // C++ [class.mfct.non-static]p3:
1769 // When an id-expression that is not part of a class member access
1770 // syntax and not used to form a pointer to member is used in the
1771 // body of a non-static member function of class X, if name lookup
1772 // resolves the name in the id-expression to a non-static non-type
1773 // member of some class C, the id-expression is transformed into a
1774 // class member access expression using (*this) as the
1775 // postfix-expression to the left of the . operator.
John McCall9c72c602010-08-27 09:08:28 +00001776 //
1777 // But we don't actually need to do this for '&' operands if R
1778 // resolved to a function or overloaded function set, because the
1779 // expression is ill-formed if it actually works out to be a
1780 // non-static member function:
1781 //
1782 // C++ [expr.ref]p4:
1783 // Otherwise, if E1.E2 refers to a non-static member function. . .
1784 // [t]he expression can be used only as the left-hand operand of a
1785 // member function call.
1786 //
1787 // There are other safeguards against such uses, but it's important
1788 // to get this right here so that we don't end up making a
1789 // spuriously dependent expression if we're inside a dependent
1790 // instance method.
John McCall3b4294e2009-12-16 12:17:52 +00001791 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall9c72c602010-08-27 09:08:28 +00001792 bool MightBeImplicitMember;
1793 if (!isAddressOfOperand)
1794 MightBeImplicitMember = true;
1795 else if (!SS.isEmpty())
1796 MightBeImplicitMember = false;
1797 else if (R.isOverloadedResult())
1798 MightBeImplicitMember = false;
Douglas Gregore2248be2010-08-30 16:00:47 +00001799 else if (R.isUnresolvableResult())
1800 MightBeImplicitMember = true;
John McCall9c72c602010-08-27 09:08:28 +00001801 else
Francois Pichet87c2e122010-11-21 06:08:52 +00001802 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1803 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall9c72c602010-08-27 09:08:28 +00001804
1805 if (MightBeImplicitMember)
John McCall3b4294e2009-12-16 12:17:52 +00001806 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001807 }
1808
John McCallf7a1a742009-11-24 19:00:30 +00001809 if (TemplateArgs)
1810 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001811
John McCallf7a1a742009-11-24 19:00:30 +00001812 return BuildDeclarationNameExpr(SS, R, ADL);
1813}
1814
John McCall129e2df2009-11-30 22:42:35 +00001815/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1816/// declaration name, generally during template instantiation.
1817/// There's a large number of things which don't need to be done along
1818/// this path.
John McCall60d7b3a2010-08-24 06:29:42 +00001819ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001820Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001821 const DeclarationNameInfo &NameInfo) {
John McCallf7a1a742009-11-24 19:00:30 +00001822 DeclContext *DC;
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001823 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara25777432010-08-11 22:01:17 +00001824 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCallf7a1a742009-11-24 19:00:30 +00001825
John McCall77bb1aa2010-05-01 00:40:08 +00001826 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregore6ec5c42010-04-28 07:04:26 +00001827 return ExprError();
1828
Abramo Bagnara25777432010-08-11 22:01:17 +00001829 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +00001830 LookupQualifiedName(R, DC);
1831
1832 if (R.isAmbiguous())
1833 return ExprError();
1834
1835 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001836 Diag(NameInfo.getLoc(), diag::err_no_member)
1837 << NameInfo.getName() << DC << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001838 return ExprError();
1839 }
1840
1841 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1842}
1843
1844/// LookupInObjCMethod - The parser has read a name in, and Sema has
1845/// detected that we're currently inside an ObjC method. Perform some
1846/// additional lookup.
1847///
1848/// Ideally, most of this would be done by lookup, but there's
1849/// actually quite a lot of extra work involved.
1850///
1851/// Returns a null sentinel to indicate trivial success.
John McCall60d7b3a2010-08-24 06:29:42 +00001852ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001853Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnereb483eb2010-04-11 08:28:14 +00001854 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001855 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattneraec43db2010-04-12 05:10:17 +00001856 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00001857
John McCallf7a1a742009-11-24 19:00:30 +00001858 // There are two cases to handle here. 1) scoped lookup could have failed,
1859 // in which case we should look for an ivar. 2) scoped lookup could have
1860 // found a decl, but that decl is outside the current instance method (i.e.
1861 // a global variable). In these two cases, we do a lookup for an ivar with
1862 // this name, if the lookup sucedes, we replace it our current decl.
1863
1864 // If we're in a class method, we don't normally want to look for
1865 // ivars. But if we don't find anything else, and there's an
1866 // ivar, that's an error.
Chris Lattneraec43db2010-04-12 05:10:17 +00001867 bool IsClassMethod = CurMethod->isClassMethod();
John McCallf7a1a742009-11-24 19:00:30 +00001868
1869 bool LookForIvars;
1870 if (Lookup.empty())
1871 LookForIvars = true;
1872 else if (IsClassMethod)
1873 LookForIvars = false;
1874 else
1875 LookForIvars = (Lookup.isSingleResult() &&
1876 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001877 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001878 if (LookForIvars) {
Chris Lattneraec43db2010-04-12 05:10:17 +00001879 IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001880 ObjCInterfaceDecl *ClassDeclared;
1881 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1882 // Diagnose using an ivar in a class method.
1883 if (IsClassMethod)
1884 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1885 << IV->getDeclName());
1886
1887 // If we're referencing an invalid decl, just return this as a silent
1888 // error node. The error diagnostic was already emitted on the decl.
1889 if (IV->isInvalidDecl())
1890 return ExprError();
1891
1892 // Check if referencing a field with __attribute__((deprecated)).
1893 if (DiagnoseUseOfDecl(IV, Loc))
1894 return ExprError();
1895
1896 // Diagnose the use of an ivar outside of the declaring class.
1897 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1898 ClassDeclared != IFace)
1899 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1900
1901 // FIXME: This should use a new expr for a direct reference, don't
1902 // turn this into Self->ivar, just return a BareIVarExpr or something.
1903 IdentifierInfo &II = Context.Idents.get("self");
1904 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001905 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001906 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCallf7a1a742009-11-24 19:00:30 +00001907 CXXScopeSpec SelfScopeSpec;
John McCall60d7b3a2010-08-24 06:29:42 +00001908 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregore45bb6a2010-09-22 16:33:13 +00001909 SelfName, false, false);
1910 if (SelfExpr.isInvalid())
1911 return ExprError();
1912
John Wiegley429bb272011-04-08 18:41:53 +00001913 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1914 if (SelfExpr.isInvalid())
1915 return ExprError();
John McCall409fa9a2010-12-06 20:48:59 +00001916
John McCallf7a1a742009-11-24 19:00:30 +00001917 MarkDeclarationReferenced(Loc, IV);
1918 return Owned(new (Context)
1919 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley429bb272011-04-08 18:41:53 +00001920 SelfExpr.take(), true, true));
John McCallf7a1a742009-11-24 19:00:30 +00001921 }
Chris Lattneraec43db2010-04-12 05:10:17 +00001922 } else if (CurMethod->isInstanceMethod()) {
John McCallf7a1a742009-11-24 19:00:30 +00001923 // We should warn if a local variable hides an ivar.
Chris Lattneraec43db2010-04-12 05:10:17 +00001924 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001925 ObjCInterfaceDecl *ClassDeclared;
1926 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1927 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1928 IFace == ClassDeclared)
1929 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1930 }
1931 }
1932
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001933 if (Lookup.empty() && II && AllowBuiltinCreation) {
1934 // FIXME. Consolidate this with similar code in LookupName.
1935 if (unsigned BuiltinID = II->getBuiltinID()) {
1936 if (!(getLangOptions().CPlusPlus &&
1937 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1938 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1939 S, Lookup.isForRedeclaration(),
1940 Lookup.getNameLoc());
1941 if (D) Lookup.addDecl(D);
1942 }
1943 }
1944 }
John McCallf7a1a742009-11-24 19:00:30 +00001945 // Sentinel value saying that we didn't do anything special.
1946 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001947}
John McCallba135432009-11-21 08:51:07 +00001948
John McCall6bb80172010-03-30 21:47:33 +00001949/// \brief Cast a base object to a member's actual type.
1950///
1951/// Logically this happens in three phases:
1952///
1953/// * First we cast from the base type to the naming class.
1954/// The naming class is the class into which we were looking
1955/// when we found the member; it's the qualifier type if a
1956/// qualifier was provided, and otherwise it's the base type.
1957///
1958/// * Next we cast from the naming class to the declaring class.
1959/// If the member we found was brought into a class's scope by
1960/// a using declaration, this is that class; otherwise it's
1961/// the class declaring the member.
1962///
1963/// * Finally we cast from the declaring class to the "true"
1964/// declaring class of the member. This conversion does not
1965/// obey access control.
John Wiegley429bb272011-04-08 18:41:53 +00001966ExprResult
1967Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001968 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00001969 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001970 NamedDecl *Member) {
1971 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1972 if (!RD)
John Wiegley429bb272011-04-08 18:41:53 +00001973 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001974
Douglas Gregor5fccd362010-03-03 23:55:11 +00001975 QualType DestRecordType;
1976 QualType DestType;
1977 QualType FromRecordType;
1978 QualType FromType = From->getType();
1979 bool PointerConversions = false;
1980 if (isa<FieldDecl>(Member)) {
1981 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001982
Douglas Gregor5fccd362010-03-03 23:55:11 +00001983 if (FromType->getAs<PointerType>()) {
1984 DestType = Context.getPointerType(DestRecordType);
1985 FromRecordType = FromType->getPointeeType();
1986 PointerConversions = true;
1987 } else {
1988 DestType = DestRecordType;
1989 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001990 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001991 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1992 if (Method->isStatic())
John Wiegley429bb272011-04-08 18:41:53 +00001993 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001994
Douglas Gregor5fccd362010-03-03 23:55:11 +00001995 DestType = Method->getThisType(Context);
1996 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001997
Douglas Gregor5fccd362010-03-03 23:55:11 +00001998 if (FromType->getAs<PointerType>()) {
1999 FromRecordType = FromType->getPointeeType();
2000 PointerConversions = true;
2001 } else {
2002 FromRecordType = FromType;
2003 DestType = DestRecordType;
2004 }
2005 } else {
2006 // No conversion necessary.
John Wiegley429bb272011-04-08 18:41:53 +00002007 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002008 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002009
Douglas Gregor5fccd362010-03-03 23:55:11 +00002010 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley429bb272011-04-08 18:41:53 +00002011 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002012
Douglas Gregor5fccd362010-03-03 23:55:11 +00002013 // If the unqualified types are the same, no conversion is necessary.
2014 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002015 return Owned(From);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002016
John McCall6bb80172010-03-30 21:47:33 +00002017 SourceRange FromRange = From->getSourceRange();
2018 SourceLocation FromLoc = FromRange.getBegin();
2019
John McCall5baba9d2010-08-25 10:28:54 +00002020 ExprValueKind VK = CastCategory(From);
Sebastian Redl906082e2010-07-20 04:20:21 +00002021
Douglas Gregor5fccd362010-03-03 23:55:11 +00002022 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002023 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00002024 // class name.
2025 //
2026 // If the member was a qualified name and the qualified referred to a
2027 // specific base subobject type, we'll cast to that intermediate type
2028 // first and then to the object in which the member is declared. That allows
2029 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2030 //
2031 // class Base { public: int x; };
2032 // class Derived1 : public Base { };
2033 // class Derived2 : public Base { };
2034 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2035 //
2036 // void VeryDerived::f() {
2037 // x = 17; // error: ambiguous base subobjects
2038 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2039 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00002040 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00002041 QualType QType = QualType(Qualifier->getAsType(), 0);
2042 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2043 assert(QType->isRecordType() && "lookup done with non-record type");
2044
2045 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2046
2047 // In C++98, the qualifier type doesn't actually have to be a base
2048 // type of the object type, in which case we just ignore it.
2049 // Otherwise build the appropriate casts.
2050 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallf871d0c2010-08-07 06:22:56 +00002051 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002052 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002053 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002054 return ExprError();
John McCall6bb80172010-03-30 21:47:33 +00002055
Douglas Gregor5fccd362010-03-03 23:55:11 +00002056 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00002057 QType = Context.getPointerType(QType);
John Wiegley429bb272011-04-08 18:41:53 +00002058 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2059 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002060
2061 FromType = QType;
2062 FromRecordType = QRecordType;
2063
2064 // If the qualifier type was the same as the destination type,
2065 // we're done.
2066 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley429bb272011-04-08 18:41:53 +00002067 return Owned(From);
Douglas Gregor5fccd362010-03-03 23:55:11 +00002068 }
2069 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002070
John McCall6bb80172010-03-30 21:47:33 +00002071 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002072
John McCall6bb80172010-03-30 21:47:33 +00002073 // If we actually found the member through a using declaration, cast
2074 // down to the using declaration's type.
2075 //
2076 // Pointer equality is fine here because only one declaration of a
2077 // class ever has member declarations.
2078 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2079 assert(isa<UsingShadowDecl>(FoundDecl));
2080 QualType URecordType = Context.getTypeDeclType(
2081 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2082
2083 // We only need to do this if the naming-class to declaring-class
2084 // conversion is non-trivial.
2085 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2086 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallf871d0c2010-08-07 06:22:56 +00002087 CXXCastPath BasePath;
John McCall6bb80172010-03-30 21:47:33 +00002088 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssoncee22422010-04-24 19:22:20 +00002089 FromLoc, FromRange, &BasePath))
John Wiegley429bb272011-04-08 18:41:53 +00002090 return ExprError();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00002091
John McCall6bb80172010-03-30 21:47:33 +00002092 QualType UType = URecordType;
2093 if (PointerConversions)
2094 UType = Context.getPointerType(UType);
John Wiegley429bb272011-04-08 18:41:53 +00002095 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2096 VK, &BasePath).take();
John McCall6bb80172010-03-30 21:47:33 +00002097 FromType = UType;
2098 FromRecordType = URecordType;
2099 }
2100
2101 // We don't do access control for the conversion from the
2102 // declaring class to the true declaring class.
2103 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00002104 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002105
John McCallf871d0c2010-08-07 06:22:56 +00002106 CXXCastPath BasePath;
Anders Carlssoncee22422010-04-24 19:22:20 +00002107 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2108 FromLoc, FromRange, &BasePath,
John McCall6bb80172010-03-30 21:47:33 +00002109 IgnoreAccess))
John Wiegley429bb272011-04-08 18:41:53 +00002110 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002111
John Wiegley429bb272011-04-08 18:41:53 +00002112 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2113 VK, &BasePath);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00002114}
Douglas Gregor751f9a42009-06-30 15:47:41 +00002115
John McCallf7a1a742009-11-24 19:00:30 +00002116bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002117 const LookupResult &R,
2118 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00002119 // Only when used directly as the postfix-expression of a call.
2120 if (!HasTrailingLParen)
2121 return false;
2122
2123 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00002124 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00002125 return false;
2126
2127 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00002128 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00002129 return false;
2130
2131 // Turn off ADL when we find certain kinds of declarations during
2132 // normal lookup:
2133 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2134 NamedDecl *D = *I;
2135
2136 // C++0x [basic.lookup.argdep]p3:
2137 // -- a declaration of a class member
2138 // Since using decls preserve this property, we check this on the
2139 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00002140 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00002141 return false;
2142
2143 // C++0x [basic.lookup.argdep]p3:
2144 // -- a block-scope function declaration that is not a
2145 // using-declaration
2146 // NOTE: we also trigger this for function templates (in fact, we
2147 // don't check the decl type at all, since all other decl types
2148 // turn off ADL anyway).
2149 if (isa<UsingShadowDecl>(D))
2150 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2151 else if (D->getDeclContext()->isFunctionOrMethod())
2152 return false;
2153
2154 // C++0x [basic.lookup.argdep]p3:
2155 // -- a declaration that is neither a function or a function
2156 // template
2157 // And also for builtin functions.
2158 if (isa<FunctionDecl>(D)) {
2159 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2160
2161 // But also builtin functions.
2162 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2163 return false;
2164 } else if (!isa<FunctionTemplateDecl>(D))
2165 return false;
2166 }
2167
2168 return true;
2169}
2170
2171
John McCallba135432009-11-21 08:51:07 +00002172/// Diagnoses obvious problems with the use of the given declaration
2173/// as an expression. This is only actually called for lookups that
2174/// were not overloaded, and it doesn't promise that the declaration
2175/// will in fact be used.
2176static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smith162e1c12011-04-15 14:24:37 +00002177 if (isa<TypedefNameDecl>(D)) {
John McCallba135432009-11-21 08:51:07 +00002178 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2179 return true;
2180 }
2181
2182 if (isa<ObjCInterfaceDecl>(D)) {
2183 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2184 return true;
2185 }
2186
2187 if (isa<NamespaceDecl>(D)) {
2188 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2189 return true;
2190 }
2191
2192 return false;
2193}
2194
John McCall60d7b3a2010-08-24 06:29:42 +00002195ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002196Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00002197 LookupResult &R,
2198 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00002199 // If this is a single, fully-resolved result and we don't need ADL,
2200 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00002201 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnara25777432010-08-11 22:01:17 +00002202 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2203 R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00002204
2205 // We only need to check the declaration if there's exactly one
2206 // result, because in the overloaded case the results can only be
2207 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00002208 if (R.isSingleResult() &&
2209 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00002210 return ExprError();
2211
John McCallc373d482010-01-27 01:50:18 +00002212 // Otherwise, just build an unresolved lookup expression. Suppress
2213 // any lookup-related diagnostics; we'll hash these out later, when
2214 // we've picked a target.
2215 R.suppressDiagnostics();
2216
John McCallba135432009-11-21 08:51:07 +00002217 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00002218 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor4c9be892011-02-28 20:01:57 +00002219 SS.getWithLocInContext(Context),
2220 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00002221 NeedsADL, R.isOverloadedResult(),
2222 R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00002223
2224 return Owned(ULE);
2225}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002226
John McCallba135432009-11-21 08:51:07 +00002227/// \brief Complete semantic analysis for a reference to the given declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00002228ExprResult
John McCallf7a1a742009-11-24 19:00:30 +00002229Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00002230 const DeclarationNameInfo &NameInfo,
2231 NamedDecl *D) {
John McCallba135432009-11-21 08:51:07 +00002232 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00002233 assert(!isa<FunctionTemplateDecl>(D) &&
2234 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00002235
Abramo Bagnara25777432010-08-11 22:01:17 +00002236 SourceLocation Loc = NameInfo.getLoc();
John McCallba135432009-11-21 08:51:07 +00002237 if (CheckDeclInExpr(*this, Loc, D))
2238 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002239
Douglas Gregor9af2f522009-12-01 16:58:18 +00002240 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2241 // Specifically diagnose references to class templates that are missing
2242 // a template argument list.
2243 Diag(Loc, diag::err_template_decl_ref)
2244 << Template << SS.getRange();
2245 Diag(Template->getLocation(), diag::note_template_decl_here);
2246 return ExprError();
2247 }
2248
2249 // Make sure that we're referring to a value.
2250 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2251 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002252 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00002253 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00002254 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00002255 return ExprError();
2256 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002257
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002258 // Check whether this declaration can be used. Note that we suppress
2259 // this check when we're going to perform argument-dependent lookup
2260 // on this function name, because this might not be the function
2261 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00002262 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002263 return ExprError();
2264
Steve Naroffdd972f22008-09-05 22:11:13 +00002265 // Only create DeclRefExpr's for valid Decl's.
2266 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002267 return ExprError();
2268
John McCall5808ce42011-02-03 08:15:49 +00002269 // Handle members of anonymous structs and unions. If we got here,
2270 // and the reference is to a class member indirect field, then this
2271 // must be the subject of a pointer-to-member expression.
2272 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2273 if (!indirectField->isCXXClassMember())
2274 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2275 indirectField);
Francois Pichet87c2e122010-11-21 06:08:52 +00002276
Chris Lattner639e2d32008-10-20 05:16:36 +00002277 // If the identifier reference is inside a block, and it refers to a value
2278 // that is outside the block, create a BlockDeclRefExpr instead of a
2279 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2280 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00002281 //
Chris Lattner639e2d32008-10-20 05:16:36 +00002282 // We do not do this for things like enum constants, global variables, etc,
2283 // as they do not get snapshotted.
2284 //
John McCall6b5a61b2011-02-07 10:33:21 +00002285 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCall469a1eb2011-02-02 13:00:07 +00002286 case CR_Error:
2287 return ExprError();
Mike Stump0d6fd572010-01-05 02:56:35 +00002288
John McCall469a1eb2011-02-02 13:00:07 +00002289 case CR_Capture:
John McCall6b5a61b2011-02-07 10:33:21 +00002290 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2291 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2292
2293 case CR_CaptureByRef:
2294 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2295 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCall76a40212011-02-09 01:13:10 +00002296
2297 case CR_NoCapture: {
2298 // If this reference is not in a block or if the referenced
2299 // variable is within the block, create a normal DeclRefExpr.
2300
2301 QualType type = VD->getType();
Daniel Dunbarb20de812011-02-10 18:29:28 +00002302 ExprValueKind valueKind = VK_RValue;
John McCall76a40212011-02-09 01:13:10 +00002303
2304 switch (D->getKind()) {
2305 // Ignore all the non-ValueDecl kinds.
2306#define ABSTRACT_DECL(kind)
2307#define VALUE(type, base)
2308#define DECL(type, base) \
2309 case Decl::type:
2310#include "clang/AST/DeclNodes.inc"
2311 llvm_unreachable("invalid value decl kind");
2312 return ExprError();
2313
2314 // These shouldn't make it here.
2315 case Decl::ObjCAtDefsField:
2316 case Decl::ObjCIvar:
2317 llvm_unreachable("forming non-member reference to ivar?");
2318 return ExprError();
2319
2320 // Enum constants are always r-values and never references.
2321 // Unresolved using declarations are dependent.
2322 case Decl::EnumConstant:
2323 case Decl::UnresolvedUsingValue:
2324 valueKind = VK_RValue;
2325 break;
2326
2327 // Fields and indirect fields that got here must be for
2328 // pointer-to-member expressions; we just call them l-values for
2329 // internal consistency, because this subexpression doesn't really
2330 // exist in the high-level semantics.
2331 case Decl::Field:
2332 case Decl::IndirectField:
2333 assert(getLangOptions().CPlusPlus &&
2334 "building reference to field in C?");
2335
2336 // These can't have reference type in well-formed programs, but
2337 // for internal consistency we do this anyway.
2338 type = type.getNonReferenceType();
2339 valueKind = VK_LValue;
2340 break;
2341
2342 // Non-type template parameters are either l-values or r-values
2343 // depending on the type.
2344 case Decl::NonTypeTemplateParm: {
2345 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2346 type = reftype->getPointeeType();
2347 valueKind = VK_LValue; // even if the parameter is an r-value reference
2348 break;
2349 }
2350
2351 // For non-references, we need to strip qualifiers just in case
2352 // the template parameter was declared as 'const int' or whatever.
2353 valueKind = VK_RValue;
2354 type = type.getUnqualifiedType();
2355 break;
2356 }
2357
2358 case Decl::Var:
2359 // In C, "extern void blah;" is valid and is an r-value.
2360 if (!getLangOptions().CPlusPlus &&
2361 !type.hasQualifiers() &&
2362 type->isVoidType()) {
2363 valueKind = VK_RValue;
2364 break;
2365 }
2366 // fallthrough
2367
2368 case Decl::ImplicitParam:
2369 case Decl::ParmVar:
2370 // These are always l-values.
2371 valueKind = VK_LValue;
2372 type = type.getNonReferenceType();
2373 break;
2374
2375 case Decl::Function: {
John McCall755d8492011-04-12 00:42:48 +00002376 const FunctionType *fty = type->castAs<FunctionType>();
2377
2378 // If we're referring to a function with an __unknown_anytype
2379 // result type, make the entire expression __unknown_anytype.
2380 if (fty->getResultType() == Context.UnknownAnyTy) {
2381 type = Context.UnknownAnyTy;
2382 valueKind = VK_RValue;
2383 break;
2384 }
2385
John McCall76a40212011-02-09 01:13:10 +00002386 // Functions are l-values in C++.
2387 if (getLangOptions().CPlusPlus) {
2388 valueKind = VK_LValue;
2389 break;
2390 }
2391
2392 // C99 DR 316 says that, if a function type comes from a
2393 // function definition (without a prototype), that type is only
2394 // used for checking compatibility. Therefore, when referencing
2395 // the function, we pretend that we don't have the full function
2396 // type.
John McCall755d8492011-04-12 00:42:48 +00002397 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2398 isa<FunctionProtoType>(fty))
2399 type = Context.getFunctionNoProtoType(fty->getResultType(),
2400 fty->getExtInfo());
John McCall76a40212011-02-09 01:13:10 +00002401
2402 // Functions are r-values in C.
2403 valueKind = VK_RValue;
2404 break;
2405 }
2406
2407 case Decl::CXXMethod:
John McCall755d8492011-04-12 00:42:48 +00002408 // If we're referring to a method with an __unknown_anytype
2409 // result type, make the entire expression __unknown_anytype.
2410 // This should only be possible with a type written directly.
Richard Trieu67e29332011-08-02 04:35:43 +00002411 if (const FunctionProtoType *proto
2412 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall755d8492011-04-12 00:42:48 +00002413 if (proto->getResultType() == Context.UnknownAnyTy) {
2414 type = Context.UnknownAnyTy;
2415 valueKind = VK_RValue;
2416 break;
2417 }
2418
John McCall76a40212011-02-09 01:13:10 +00002419 // C++ methods are l-values if static, r-values if non-static.
2420 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2421 valueKind = VK_LValue;
2422 break;
2423 }
2424 // fallthrough
2425
2426 case Decl::CXXConversion:
2427 case Decl::CXXDestructor:
2428 case Decl::CXXConstructor:
2429 valueKind = VK_RValue;
2430 break;
2431 }
2432
2433 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2434 }
2435
John McCall469a1eb2011-02-02 13:00:07 +00002436 }
John McCallf89e55a2010-11-18 06:31:45 +00002437
John McCall6b5a61b2011-02-07 10:33:21 +00002438 llvm_unreachable("unknown capture result");
2439 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002440}
2441
John McCall755d8492011-04-12 00:42:48 +00002442ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00002443 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002444
Reid Spencer5f016e22007-07-11 17:01:13 +00002445 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00002446 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00002447 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2448 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2449 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002450 }
Chris Lattner1423ea42008-01-12 18:39:25 +00002451
Chris Lattnerfa28b302008-01-12 08:14:25 +00002452 // Pre-defined identifiers are of type char[x], where x is the length of the
2453 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00002454
Anders Carlsson3a082d82009-09-08 18:24:21 +00002455 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanianeb024ac2010-07-23 21:53:24 +00002456 if (!currentDecl && getCurBlock())
2457 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson3a082d82009-09-08 18:24:21 +00002458 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00002459 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00002460 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00002461 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002462
Anders Carlsson773f3972009-09-11 01:22:35 +00002463 QualType ResTy;
2464 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2465 ResTy = Context.DependentTy;
2466 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00002467 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002468
Anders Carlsson773f3972009-09-11 01:22:35 +00002469 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00002470 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00002471 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2472 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00002473 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00002474}
2475
John McCall60d7b3a2010-08-24 06:29:42 +00002476ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002477 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00002478 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002479 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregor453091c2010-03-16 22:30:13 +00002480 if (Invalid)
2481 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002482
Benjamin Kramerddeea562010-02-27 13:44:12 +00002483 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002484 PP, Tok.getKind());
Reid Spencer5f016e22007-07-11 17:01:13 +00002485 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002486 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002487
Chris Lattnere8337df2009-12-30 21:19:39 +00002488 QualType Ty;
2489 if (!getLangOptions().CPlusPlus)
2490 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2491 else if (Literal.isWide())
2492 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregor5cee1192011-07-27 05:40:30 +00002493 else if (Literal.isUTF16())
2494 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2495 else if (Literal.isUTF32())
2496 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedman136b0cd2010-02-03 18:21:45 +00002497 else if (Literal.isMultiChar())
2498 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00002499 else
2500 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00002501
Douglas Gregor5cee1192011-07-27 05:40:30 +00002502 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2503 if (Literal.isWide())
2504 Kind = CharacterLiteral::Wide;
2505 else if (Literal.isUTF16())
2506 Kind = CharacterLiteral::UTF16;
2507 else if (Literal.isUTF32())
2508 Kind = CharacterLiteral::UTF32;
2509
2510 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2511 Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002512}
2513
John McCall60d7b3a2010-08-24 06:29:42 +00002514ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002515 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00002516 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2517 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00002518 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00002519 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002520 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00002521 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002522 }
Ted Kremenek28396602009-01-13 23:19:12 +00002523
Reid Spencer5f016e22007-07-11 17:01:13 +00002524 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00002525 // Add padding so that NumericLiteralParser can overread by one character.
2526 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00002527 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00002528
Reid Spencer5f016e22007-07-11 17:01:13 +00002529 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00002530 bool Invalid = false;
2531 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2532 if (Invalid)
2533 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002534
Mike Stump1eb44332009-09-09 15:08:12 +00002535 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00002536 Tok.getLocation(), PP);
2537 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00002538 return ExprError();
2539
Chris Lattner5d661452007-08-26 03:42:43 +00002540 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00002541
Chris Lattner5d661452007-08-26 03:42:43 +00002542 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00002543 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002544 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00002545 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002546 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00002547 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002548 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00002549 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00002550
2551 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2552
John McCall94c939d2009-12-24 09:08:04 +00002553 using llvm::APFloat;
2554 APFloat Val(Format);
2555
2556 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00002557
2558 // Overflow is always an error, but underflow is only an error if
2559 // we underflowed to zero (APFloat reports denormals as underflow).
2560 if ((result & APFloat::opOverflow) ||
2561 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00002562 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002563 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00002564 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00002565 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00002566 APFloat::getLargest(Format).toString(buffer);
2567 } else {
John McCall2a0d7572010-02-26 23:35:57 +00002568 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00002569 APFloat::getSmallest(Format).toString(buffer);
2570 }
2571
2572 Diag(Tok.getLocation(), diagnostic)
2573 << Ty
Chris Lattner5f9e2722011-07-23 10:55:15 +00002574 << StringRef(buffer.data(), buffer.size());
John McCall94c939d2009-12-24 09:08:04 +00002575 }
2576
2577 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002578 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00002579
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002580 if (Ty == Context.DoubleTy) {
2581 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley429bb272011-04-08 18:41:53 +00002582 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002583 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2584 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley429bb272011-04-08 18:41:53 +00002585 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournef4f7cb82011-03-11 19:24:59 +00002586 }
2587 }
Chris Lattner5d661452007-08-26 03:42:43 +00002588 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00002589 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00002590 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002591 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00002592
Neil Boothb9449512007-08-29 22:00:19 +00002593 // long long is a C99 feature.
2594 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00002595 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00002596 Diag(Tok.getLocation(), diag::ext_longlong);
2597
Reid Spencer5f016e22007-07-11 17:01:13 +00002598 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00002599 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00002600
Reid Spencer5f016e22007-07-11 17:01:13 +00002601 if (Literal.GetIntegerValue(ResultVal)) {
2602 // If this value didn't fit into uintmax_t, warn and force to ull.
2603 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002604 Ty = Context.UnsignedLongLongTy;
2605 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00002606 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00002607 } else {
2608 // If this value fits into a ULL, try to figure out what else it fits into
2609 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00002610
Reid Spencer5f016e22007-07-11 17:01:13 +00002611 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2612 // be an unsigned int.
2613 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2614
2615 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002616 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00002617 if (!Literal.isLong && !Literal.isLongLong) {
2618 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002619 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002620
Reid Spencer5f016e22007-07-11 17:01:13 +00002621 // Does it fit in a unsigned int?
2622 if (ResultVal.isIntN(IntSize)) {
2623 // Does it fit in a signed int?
2624 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002625 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002626 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002627 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002628 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002629 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002630 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002631
Reid Spencer5f016e22007-07-11 17:01:13 +00002632 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00002633 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002634 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002635
Reid Spencer5f016e22007-07-11 17:01:13 +00002636 // Does it fit in a unsigned long?
2637 if (ResultVal.isIntN(LongSize)) {
2638 // Does it fit in a signed long?
2639 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002640 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002641 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002642 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002643 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002644 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002645 }
2646
Reid Spencer5f016e22007-07-11 17:01:13 +00002647 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002648 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002649 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00002650
Reid Spencer5f016e22007-07-11 17:01:13 +00002651 // Does it fit in a unsigned long long?
2652 if (ResultVal.isIntN(LongLongSize)) {
2653 // Does it fit in a signed long long?
Francois Pichet24323202011-01-11 23:38:13 +00002654 // To be compatible with MSVC, hex integer literals ending with the
2655 // LL or i64 suffix are always signed in Microsoft mode.
Francois Picheta15a5ee2011-01-11 12:23:00 +00002656 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2657 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattnerf0467b32008-04-02 04:24:33 +00002658 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002659 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00002660 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002661 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00002662 }
2663 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002664
Reid Spencer5f016e22007-07-11 17:01:13 +00002665 // If we still couldn't decide a type, we probably have something that
2666 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00002667 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002668 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002669 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002670 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00002671 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002672
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00002673 if (ResultVal.getBitWidth() != Width)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002674 ResultVal = ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00002675 }
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00002676 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002677 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00002678
Chris Lattner5d661452007-08-26 03:42:43 +00002679 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2680 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00002681 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002682 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00002683
2684 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00002685}
2686
John McCall60d7b3a2010-08-24 06:29:42 +00002687ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCall9ae2f072010-08-23 23:25:46 +00002688 SourceLocation R, Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00002689 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002690 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002691}
2692
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002693static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2694 SourceLocation Loc,
2695 SourceRange ArgRange) {
2696 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2697 // scalar or vector data type argument..."
2698 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2699 // type (C99 6.2.5p18) or void.
2700 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2701 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2702 << T << ArgRange;
2703 return true;
2704 }
2705
2706 assert((T->isVoidType() || !T->isIncompleteType()) &&
2707 "Scalar types should always be complete");
2708 return false;
2709}
2710
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002711static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2712 SourceLocation Loc,
2713 SourceRange ArgRange,
2714 UnaryExprOrTypeTrait TraitKind) {
2715 // C99 6.5.3.4p1:
2716 if (T->isFunctionType()) {
2717 // alignof(function) is allowed as an extension.
2718 if (TraitKind == UETT_SizeOf)
2719 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2720 return false;
2721 }
2722
2723 // Allow sizeof(void)/alignof(void) as an extension.
2724 if (T->isVoidType()) {
2725 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2726 return false;
2727 }
2728
2729 return true;
2730}
2731
2732static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2733 SourceLocation Loc,
2734 SourceRange ArgRange,
2735 UnaryExprOrTypeTrait TraitKind) {
2736 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2737 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2738 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2739 << T << (TraitKind == UETT_SizeOf)
2740 << ArgRange;
2741 return true;
2742 }
2743
2744 return false;
2745}
2746
Chandler Carruth9d342d02011-05-26 08:53:10 +00002747/// \brief Check the constrains on expression operands to unary type expression
2748/// and type traits.
2749///
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002750/// Completes any types necessary and validates the constraints on the operand
2751/// expression. The logic mostly mirrors the type-based overload, but may modify
2752/// the expression as it completes the type for that expression through template
2753/// instantiation, etc.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002754bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op,
2755 UnaryExprOrTypeTrait ExprKind) {
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002756 QualType ExprTy = Op->getType();
2757
2758 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2759 // the result is the size of the referenced type."
2760 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2761 // result shall be the alignment of the referenced type."
2762 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2763 ExprTy = Ref->getPointeeType();
2764
2765 if (ExprKind == UETT_VecStep)
2766 return CheckVecStepTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2767 Op->getSourceRange());
2768
2769 // Whitelist some types as extensions
2770 if (!CheckExtensionTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2771 Op->getSourceRange(), ExprKind))
2772 return false;
2773
2774 if (RequireCompleteExprType(Op,
2775 PDiag(diag::err_sizeof_alignof_incomplete_type)
2776 << ExprKind << Op->getSourceRange(),
2777 std::make_pair(SourceLocation(), PDiag(0))))
2778 return true;
2779
2780 // Completeing the expression's type may have changed it.
2781 ExprTy = Op->getType();
2782 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2783 ExprTy = Ref->getPointeeType();
2784
2785 if (CheckObjCTraitOperandConstraints(*this, ExprTy, Op->getExprLoc(),
2786 Op->getSourceRange(), ExprKind))
2787 return true;
2788
Nico Webercf739922011-06-15 02:47:03 +00002789 if (ExprKind == UETT_SizeOf) {
2790 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Op->IgnoreParens())) {
2791 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2792 QualType OType = PVD->getOriginalType();
2793 QualType Type = PVD->getType();
2794 if (Type->isPointerType() && OType->isArrayType()) {
2795 Diag(Op->getExprLoc(), diag::warn_sizeof_array_param)
2796 << Type << OType;
2797 Diag(PVD->getLocation(), diag::note_declared_at);
2798 }
2799 }
2800 }
2801 }
2802
Chandler Carruthe4d645c2011-05-27 01:33:31 +00002803 return false;
Chandler Carruth9d342d02011-05-26 08:53:10 +00002804}
2805
2806/// \brief Check the constraints on operands to unary expression and type
2807/// traits.
2808///
2809/// This will complete any types necessary, and validate the various constraints
2810/// on those operands.
2811///
Reid Spencer5f016e22007-07-11 17:01:13 +00002812/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002813/// C99 6.3.2.1p[2-4] all state:
2814/// Except when it is the operand of the sizeof operator ...
2815///
2816/// C++ [expr.sizeof]p4
2817/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2818/// standard conversions are not applied to the operand of sizeof.
2819///
2820/// This policy is followed for all of the unary trait expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002821bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2822 SourceLocation OpLoc,
2823 SourceRange ExprRange,
2824 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl28507842009-02-26 14:39:58 +00002825 if (exprType->isDependentType())
2826 return false;
2827
Sebastian Redl5d484e82009-11-23 17:18:46 +00002828 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2829 // the result is the size of the referenced type."
2830 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2831 // result shall be the alignment of the referenced type."
2832 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2833 exprType = Ref->getPointeeType();
2834
Chandler Carruthdf1f3772011-05-26 08:53:12 +00002835 if (ExprKind == UETT_VecStep)
2836 return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002837
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002838 // Whitelist some types as extensions
2839 if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange,
2840 ExprKind))
Chris Lattner01072922009-01-24 19:46:37 +00002841 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002842
Chris Lattner1efaa952009-04-24 00:30:45 +00002843 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002844 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002845 << ExprKind << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002846 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002847
Chandler Carruth42ec65d2011-05-26 08:53:16 +00002848 if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange,
2849 ExprKind))
Chris Lattner5cb10d32009-04-24 22:30:50 +00002850 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002851
Chris Lattner1efaa952009-04-24 00:30:45 +00002852 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002853}
2854
Chandler Carruth9d342d02011-05-26 08:53:10 +00002855static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner31e21e02009-01-24 20:17:12 +00002856 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002857
Mike Stump1eb44332009-09-09 15:08:12 +00002858 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002859 if (isa<DeclRefExpr>(E))
2860 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002861
2862 // Cannot know anything else if the expression is dependent.
2863 if (E->isTypeDependent())
2864 return false;
2865
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002866 if (E->getBitField()) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002867 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2868 << 1 << E->getSourceRange();
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002869 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002870 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002871
2872 // Alignment of a field access is always okay, so long as it isn't a
2873 // bit-field.
2874 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002875 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002876 return false;
2877
Chandler Carruth9d342d02011-05-26 08:53:10 +00002878 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002879}
2880
Chandler Carruth9d342d02011-05-26 08:53:10 +00002881bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002882 E = E->IgnoreParens();
2883
2884 // Cannot know anything else if the expression is dependent.
2885 if (E->isTypeDependent())
2886 return false;
2887
Chandler Carruth9d342d02011-05-26 08:53:10 +00002888 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner31e21e02009-01-24 20:17:12 +00002889}
2890
Douglas Gregorba498172009-03-13 21:01:28 +00002891/// \brief Build a sizeof or alignof expression given a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002892ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002893Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2894 SourceLocation OpLoc,
2895 UnaryExprOrTypeTrait ExprKind,
2896 SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002897 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002898 return ExprError();
2899
John McCalla93c9342009-12-07 02:54:59 +00002900 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002901
Douglas Gregorba498172009-03-13 21:01:28 +00002902 if (!T->isDependentType() &&
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002903 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregorba498172009-03-13 21:01:28 +00002904 return ExprError();
2905
2906 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002907 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2908 Context.getSizeType(),
2909 OpLoc, R.getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002910}
2911
2912/// \brief Build a sizeof or alignof expression given an expression
2913/// operand.
John McCall60d7b3a2010-08-24 06:29:42 +00002914ExprResult
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002915Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2916 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor4f0845e2011-06-22 23:21:00 +00002917 ExprResult PE = CheckPlaceholderExpr(E);
2918 if (PE.isInvalid())
2919 return ExprError();
2920
2921 E = PE.get();
2922
Douglas Gregorba498172009-03-13 21:01:28 +00002923 // Verify that the operand is valid.
2924 bool isInvalid = false;
2925 if (E->isTypeDependent()) {
2926 // Delay type-checking for type-dependent expressions.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002927 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002928 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002929 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002930 isInvalid = CheckVecStepExpr(E);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002931 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002932 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregorba498172009-03-13 21:01:28 +00002933 isInvalid = true;
2934 } else {
Chandler Carruth9d342d02011-05-26 08:53:10 +00002935 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregorba498172009-03-13 21:01:28 +00002936 }
2937
2938 if (isInvalid)
2939 return ExprError();
2940
2941 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth9d342d02011-05-26 08:53:10 +00002942 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002943 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth9d342d02011-05-26 08:53:10 +00002944 E->getSourceRange().getEnd()));
Douglas Gregorba498172009-03-13 21:01:28 +00002945}
2946
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002947/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2948/// expr and the same for @c alignof and @c __alignof
Sebastian Redl05189992008-11-11 17:56:53 +00002949/// Note that the ArgRange is invalid if isType is false.
John McCall60d7b3a2010-08-24 06:29:42 +00002950ExprResult
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002951Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2952 UnaryExprOrTypeTrait ExprKind, bool isType,
2953 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002954 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002955 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002956
Sebastian Redl05189992008-11-11 17:56:53 +00002957 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00002958 TypeSourceInfo *TInfo;
John McCallb3d87482010-08-24 05:47:05 +00002959 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002960 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00002961 }
Sebastian Redl05189992008-11-11 17:56:53 +00002962
Douglas Gregorba498172009-03-13 21:01:28 +00002963 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carruthe72c55b2011-05-29 07:32:14 +00002964 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregorba498172009-03-13 21:01:28 +00002965 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002966}
2967
John Wiegley429bb272011-04-08 18:41:53 +00002968static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall09431682010-11-18 19:01:18 +00002969 bool isReal) {
John Wiegley429bb272011-04-08 18:41:53 +00002970 if (V.get()->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00002971 return S.Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002972
John McCallf6a16482010-12-04 03:47:34 +00002973 // _Real and _Imag are only l-values for normal l-values.
John Wiegley429bb272011-04-08 18:41:53 +00002974 if (V.get()->getObjectKind() != OK_Ordinary) {
2975 V = S.DefaultLvalueConversion(V.take());
2976 if (V.isInvalid())
2977 return QualType();
2978 }
John McCallf6a16482010-12-04 03:47:34 +00002979
Chris Lattnercc26ed72007-08-26 05:39:26 +00002980 // These operators return the element type of a complex type.
John Wiegley429bb272011-04-08 18:41:53 +00002981 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00002982 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002983
Chris Lattnercc26ed72007-08-26 05:39:26 +00002984 // Otherwise they pass through real integer and floating point types here.
John Wiegley429bb272011-04-08 18:41:53 +00002985 if (V.get()->getType()->isArithmeticType())
2986 return V.get()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002987
John McCall2cd11fe2010-10-12 02:09:17 +00002988 // Test for placeholders.
John McCallfb8721c2011-04-10 19:13:55 +00002989 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall2cd11fe2010-10-12 02:09:17 +00002990 if (PR.isInvalid()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00002991 if (PR.get() != V.get()) {
2992 V = move(PR);
John McCall09431682010-11-18 19:01:18 +00002993 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall2cd11fe2010-10-12 02:09:17 +00002994 }
2995
Chris Lattnercc26ed72007-08-26 05:39:26 +00002996 // Reject anything else.
John Wiegley429bb272011-04-08 18:41:53 +00002997 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattnerba27e2a2009-02-17 08:12:06 +00002998 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00002999 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00003000}
3001
3002
Reid Spencer5f016e22007-07-11 17:01:13 +00003003
John McCall60d7b3a2010-08-24 06:29:42 +00003004ExprResult
Sebastian Redl0eb23302009-01-19 00:08:26 +00003005Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall9ae2f072010-08-23 23:25:46 +00003006 tok::TokenKind Kind, Expr *Input) {
John McCall2de56d12010-08-25 11:45:40 +00003007 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00003008 switch (Kind) {
3009 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00003010 case tok::plusplus: Opc = UO_PostInc; break;
3011 case tok::minusminus: Opc = UO_PostDec; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003012 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003013
John McCall9ae2f072010-08-23 23:25:46 +00003014 return BuildUnaryOp(S, OpLoc, Opc, Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003015}
3016
John McCall60d7b3a2010-08-24 06:29:42 +00003017ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003018Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3019 Expr *Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003020 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003021 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00003022 if (Result.isInvalid()) return ExprError();
3023 Base = Result.take();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003024
John McCall9ae2f072010-08-23 23:25:46 +00003025 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump1eb44332009-09-09 15:08:12 +00003026
Douglas Gregor337c6b92008-11-19 17:17:41 +00003027 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003028 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003029 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003030 Context.DependentTy,
3031 VK_LValue, OK_Ordinary,
3032 RLoc));
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003033 }
3034
Mike Stump1eb44332009-09-09 15:08:12 +00003035 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00003036 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00003037 LHSExp->getType()->isEnumeralType() ||
3038 RHSExp->getType()->isRecordType() ||
3039 RHSExp->getType()->isEnumeralType())) {
John McCall9ae2f072010-08-23 23:25:46 +00003040 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor337c6b92008-11-19 17:17:41 +00003041 }
3042
John McCall9ae2f072010-08-23 23:25:46 +00003043 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00003044}
3045
3046
John McCall60d7b3a2010-08-24 06:29:42 +00003047ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003048Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3049 Expr *Idx, SourceLocation RLoc) {
3050 Expr *LHSExp = Base;
3051 Expr *RHSExp = Idx;
Sebastian Redlf322ed62009-10-29 20:17:01 +00003052
Chris Lattner12d9ff62007-07-16 00:14:47 +00003053 // Perform default conversions.
John Wiegley429bb272011-04-08 18:41:53 +00003054 if (!LHSExp->getType()->getAs<VectorType>()) {
3055 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3056 if (Result.isInvalid())
3057 return ExprError();
3058 LHSExp = Result.take();
3059 }
3060 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3061 if (Result.isInvalid())
3062 return ExprError();
3063 RHSExp = Result.take();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003064
Chris Lattner12d9ff62007-07-16 00:14:47 +00003065 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCallf89e55a2010-11-18 06:31:45 +00003066 ExprValueKind VK = VK_LValue;
3067 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00003068
Reid Spencer5f016e22007-07-11 17:01:13 +00003069 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003070 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00003071 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00003072 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00003073 Expr *BaseExpr, *IndexExpr;
3074 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00003075 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3076 BaseExpr = LHSExp;
3077 IndexExpr = RHSExp;
3078 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003079 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00003080 BaseExpr = LHSExp;
3081 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003082 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003083 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00003084 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00003085 BaseExpr = RHSExp;
3086 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00003087 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003088 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003089 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003090 BaseExpr = LHSExp;
3091 IndexExpr = RHSExp;
3092 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003093 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00003094 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003095 // Handle the uncommon case of "123[Ptr]".
3096 BaseExpr = RHSExp;
3097 IndexExpr = LHSExp;
3098 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00003099 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00003100 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00003101 IndexExpr = RHSExp;
John McCallf89e55a2010-11-18 06:31:45 +00003102 VK = LHSExp->getValueKind();
3103 if (VK != VK_RValue)
3104 OK = OK_VectorComponent;
Nate Begeman334a8022009-01-18 00:45:31 +00003105
Chris Lattner12d9ff62007-07-16 00:14:47 +00003106 // FIXME: need to deal with const...
3107 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003108 } else if (LHSTy->isArrayType()) {
3109 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00003110 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003111 // wasn't promoted because of the C90 rule that doesn't
3112 // allow promoting non-lvalue arrays. Warn, then
3113 // force the promotion here.
3114 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3115 LHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003116 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3117 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003118 LHSTy = LHSExp->getType();
3119
3120 BaseExpr = LHSExp;
3121 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003122 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003123 } else if (RHSTy->isArrayType()) {
3124 // Same as previous, except for 123[f().a] case
3125 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3126 RHSExp->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00003127 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3128 CK_ArrayToPointerDecay).take();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00003129 RHSTy = RHSExp->getType();
3130
3131 BaseExpr = RHSExp;
3132 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00003133 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003134 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00003135 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3136 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003137 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003138 // C99 6.5.2.1p1
Douglas Gregorf6094622010-07-23 15:58:24 +00003139 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00003140 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3141 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00003142
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003143 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00003144 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3145 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00003146 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3147
Douglas Gregore7450f52009-03-24 19:52:54 +00003148 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00003149 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3150 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00003151 // incomplete types are not object types.
3152 if (ResultType->isFunctionType()) {
3153 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3154 << ResultType << BaseExpr->getSourceRange();
3155 return ExprError();
3156 }
Mike Stump1eb44332009-09-09 15:08:12 +00003157
Abramo Bagnara46358452010-09-13 06:50:07 +00003158 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3159 // GNU extension: subscripting on pointer to void
Chandler Carruth66289692011-06-27 16:32:27 +00003160 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3161 << BaseExpr->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00003162
3163 // C forbids expressions of unqualified void type from being l-values.
3164 // See IsCForbiddenLValueType.
3165 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara46358452010-09-13 06:50:07 +00003166 } else if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003167 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003168 PDiag(diag::err_subscript_incomplete_type)
3169 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00003170 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003171
Chris Lattner1efaa952009-04-24 00:30:45 +00003172 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00003173 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner1efaa952009-04-24 00:30:45 +00003174 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3175 << ResultType << BaseExpr->getSourceRange();
3176 return ExprError();
3177 }
Mike Stump1eb44332009-09-09 15:08:12 +00003178
John McCall09431682010-11-18 19:01:18 +00003179 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00003180 !ResultType.isCForbiddenLValueType());
John McCall09431682010-11-18 19:01:18 +00003181
Mike Stumpeed9cac2009-02-19 03:04:26 +00003182 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCallf89e55a2010-11-18 06:31:45 +00003183 ResultType, VK, OK, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003184}
3185
John McCall60d7b3a2010-08-24 06:29:42 +00003186ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber08e41a62010-11-29 18:19:25 +00003187 FunctionDecl *FD,
3188 ParmVarDecl *Param) {
Anders Carlsson56c5e332009-08-25 03:49:14 +00003189 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003190 Diag(CallLoc,
Nico Weber15d5c832010-11-30 04:44:33 +00003191 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson56c5e332009-08-25 03:49:14 +00003192 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003193 Diag(UnparsedDefaultArgLocs[Param],
Nico Weber15d5c832010-11-30 04:44:33 +00003194 diag::note_default_argument_declared_here);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003195 return ExprError();
3196 }
3197
3198 if (Param->hasUninstantiatedDefaultArg()) {
3199 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson56c5e332009-08-25 03:49:14 +00003200
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003201 // Instantiate the expression.
3202 MultiLevelTemplateArgumentList ArgList
3203 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003204
Nico Weber08e41a62010-11-29 18:19:25 +00003205 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003206 = ArgList.getInnermost();
3207 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3208 Innermost.second);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003209
Nico Weber08e41a62010-11-29 18:19:25 +00003210 ExprResult Result;
3211 {
3212 // C++ [dcl.fct.default]p5:
3213 // The names in the [default argument] expression are bound, and
3214 // the semantic constraints are checked, at the point where the
3215 // default argument expression appears.
Nico Weber15d5c832010-11-30 04:44:33 +00003216 ContextRAII SavedContext(*this, FD);
Nico Weber08e41a62010-11-29 18:19:25 +00003217 Result = SubstExpr(UninstExpr, ArgList);
3218 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003219 if (Result.isInvalid())
3220 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003221
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003222 // Check the expression as an initializer for the parameter.
3223 InitializedEntity Entity
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003224 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003225 InitializationKind Kind
3226 = InitializationKind::CreateCopy(Param->getLocation(),
3227 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3228 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor65222e82009-12-23 18:19:08 +00003229
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003230 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3231 Result = InitSeq.Perform(*this, Entity, Kind,
3232 MultiExprArg(*this, &ResultE, 1));
3233 if (Result.isInvalid())
3234 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003235
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003236 // Build the default argument expression.
3237 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3238 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003239 }
3240
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003241 // If the default expression creates temporaries, we need to
3242 // push them to the current stack of expression temporaries so they'll
3243 // be properly destroyed.
3244 // FIXME: We should really be rebuilding the default argument with new
3245 // bound temporaries; see the comment in PR5810.
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003246 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3247 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3248 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3249 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3250 ExprTemporaries.push_back(Temporary);
John McCallf85e1932011-06-15 23:02:42 +00003251 ExprNeedsCleanups = true;
Douglas Gregor5833b0b2010-09-14 22:55:20 +00003252 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003253
3254 // We already type-checked the argument, so we know it works.
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00003255 // Just mark all of the declarations in this potentially-evaluated expression
3256 // as being "referenced".
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00003257 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor036aed12009-12-23 23:03:06 +00003258 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003259}
3260
Douglas Gregor88a35142008-12-22 05:46:06 +00003261/// ConvertArgumentsForCall - Converts the arguments specified in
3262/// Args/NumArgs to the parameter types of the function FDecl with
3263/// function prototype Proto. Call is the call expression itself, and
3264/// Fn is the function expression. For a C++ member function, this
3265/// routine does not attempt to convert the object argument. Returns
3266/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003267bool
3268Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003269 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003270 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003271 Expr **Args, unsigned NumArgs,
3272 SourceLocation RParenLoc) {
John McCall8e10f3b2011-02-26 05:39:39 +00003273 // Bail out early if calling a builtin with custom typechecking.
3274 // We don't need to do this in the
3275 if (FDecl)
3276 if (unsigned ID = FDecl->getBuiltinID())
3277 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3278 return false;
3279
Mike Stumpeed9cac2009-02-19 03:04:26 +00003280 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003281 // assignment, to the types of the corresponding parameter, ...
3282 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003283 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003284
Douglas Gregor88a35142008-12-22 05:46:06 +00003285 // If too few arguments are available (and we don't have default
3286 // arguments for the remaining parameters), don't make the call.
3287 if (NumArgs < NumArgsInProto) {
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003288 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) {
3289 Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003290 << Fn->getType()->isBlockPointerType()
Eric Christopherd77b9a22010-04-16 04:48:22 +00003291 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003292
3293 // Emit the location of the prototype.
3294 if (FDecl && !FDecl->getBuiltinID())
3295 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3296 << FDecl;
3297
3298 return true;
3299 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00003300 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003301 }
3302
3303 // If too many are passed and not variadic, error on the extras and drop
3304 // them.
3305 if (NumArgs > NumArgsInProto) {
3306 if (!Proto->isVariadic()) {
3307 Diag(Args[NumArgsInProto]->getLocStart(),
3308 diag::err_typecheck_call_too_many_args)
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00003309 << Fn->getType()->isBlockPointerType()
Eric Christopherccfa9632010-04-16 04:56:46 +00003310 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor88a35142008-12-22 05:46:06 +00003311 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3312 Args[NumArgs-1]->getLocEnd());
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003313
3314 // Emit the location of the prototype.
3315 if (FDecl && !FDecl->getBuiltinID())
Peter Collingbourne9aab1482011-07-29 00:24:42 +00003316 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3317 << FDecl;
Ted Kremenek5862f0e2011-04-04 17:22:27 +00003318
Douglas Gregor88a35142008-12-22 05:46:06 +00003319 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003320 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003321 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003322 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003323 }
Chris Lattner5f9e2722011-07-23 10:55:15 +00003324 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003325 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003326 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3327 if (Fn->getType()->isBlockPointerType())
3328 CallType = VariadicBlock; // Block
3329 else if (isa<MemberExpr>(Fn))
3330 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003331 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003332 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003333 if (Invalid)
3334 return true;
3335 unsigned TotalNumArgs = AllArgs.size();
3336 for (unsigned i = 0; i < TotalNumArgs; ++i)
3337 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003338
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003339 return false;
3340}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003341
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003342bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3343 FunctionDecl *FDecl,
3344 const FunctionProtoType *Proto,
3345 unsigned FirstProtoArg,
3346 Expr **Args, unsigned NumArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003347 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003348 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003349 unsigned NumArgsInProto = Proto->getNumArgs();
3350 unsigned NumArgsToCheck = NumArgs;
3351 bool Invalid = false;
3352 if (NumArgs != NumArgsInProto)
3353 // Use default arguments for missing arguments
3354 NumArgsToCheck = NumArgsInProto;
3355 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003356 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003357 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003358 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003359
Douglas Gregor88a35142008-12-22 05:46:06 +00003360 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003361 if (ArgIx < NumArgs) {
3362 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003363
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003364 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3365 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003366 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003367 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003368 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003369
Douglas Gregora188ff22009-12-22 16:09:06 +00003370 // Pass the argument
3371 ParmVarDecl *Param = 0;
3372 if (FDecl && i < FDecl->getNumParams())
3373 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003374
Douglas Gregora188ff22009-12-22 16:09:06 +00003375 InitializedEntity Entity =
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003376 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCallf85e1932011-06-15 23:02:42 +00003377 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3378 Proto->isArgConsumed(i));
John McCall60d7b3a2010-08-24 06:29:42 +00003379 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCallf6a16482010-12-04 03:47:34 +00003380 SourceLocation(),
3381 Owned(Arg));
Douglas Gregora188ff22009-12-22 16:09:06 +00003382 if (ArgE.isInvalid())
3383 return true;
3384
3385 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003386 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003387 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003388
John McCall60d7b3a2010-08-24 06:29:42 +00003389 ExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003390 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003391 if (ArgExpr.isInvalid())
3392 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003393
Anders Carlsson56c5e332009-08-25 03:49:14 +00003394 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003395 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003396 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003397 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003398
Douglas Gregor88a35142008-12-22 05:46:06 +00003399 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003400 if (CallType != VariadicDoesNotApply) {
John McCall755d8492011-04-12 00:42:48 +00003401
3402 // Assume that extern "C" functions with variadic arguments that
3403 // return __unknown_anytype aren't *really* variadic.
3404 if (Proto->getResultType() == Context.UnknownAnyTy &&
3405 FDecl && FDecl->isExternC()) {
3406 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3407 ExprResult arg;
3408 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3409 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3410 else
3411 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3412 Invalid |= arg.isInvalid();
3413 AllArgs.push_back(arg.take());
3414 }
3415
3416 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3417 } else {
3418 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieu67e29332011-08-02 04:35:43 +00003419 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3420 FDecl);
John McCall755d8492011-04-12 00:42:48 +00003421 Invalid |= Arg.isInvalid();
3422 AllArgs.push_back(Arg.take());
3423 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003424 }
3425 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003426 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003427}
3428
John McCall755d8492011-04-12 00:42:48 +00003429/// Given a function expression of unknown-any type, try to rebuild it
3430/// to have a function type.
3431static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3432
Steve Narofff69936d2007-09-16 03:34:24 +00003433/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003434/// This provides the location of the left/right parens and a list of comma
3435/// locations.
John McCall60d7b3a2010-08-24 06:29:42 +00003436ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003437Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003438 MultiExprArg args, SourceLocation RParenLoc,
3439 Expr *ExecConfig) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00003440 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003441
3442 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00003443 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCall9ae2f072010-08-23 23:25:46 +00003444 if (Result.isInvalid()) return ExprError();
3445 Fn = Result.take();
Mike Stump1eb44332009-09-09 15:08:12 +00003446
John McCall9ae2f072010-08-23 23:25:46 +00003447 Expr **Args = args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003448
Douglas Gregor88a35142008-12-22 05:46:06 +00003449 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003450 // If this is a pseudo-destructor expression, build the call immediately.
3451 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3452 if (NumArgs > 0) {
3453 // Pseudo-destructor calls should not have any arguments.
3454 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregor849b2432010-03-31 17:46:05 +00003455 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00003456 SourceRange(Args[0]->getLocStart(),
3457 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003458
Douglas Gregora71d8192009-09-04 17:36:40 +00003459 NumArgs = 0;
3460 }
Mike Stump1eb44332009-09-09 15:08:12 +00003461
Douglas Gregora71d8192009-09-04 17:36:40 +00003462 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCallf89e55a2010-11-18 06:31:45 +00003463 VK_RValue, RParenLoc));
Douglas Gregora71d8192009-09-04 17:36:40 +00003464 }
Mike Stump1eb44332009-09-09 15:08:12 +00003465
Douglas Gregor17330012009-02-04 15:01:18 +00003466 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003467 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003468 // FIXME: Will need to cache the results of name lookup (including ADL) in
3469 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003470 bool Dependent = false;
3471 if (Fn->isTypeDependent())
3472 Dependent = true;
3473 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3474 Dependent = true;
3475
Peter Collingbournee08ce652011-02-09 21:07:24 +00003476 if (Dependent) {
3477 if (ExecConfig) {
3478 return Owned(new (Context) CUDAKernelCallExpr(
3479 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3480 Context.DependentTy, VK_RValue, RParenLoc));
3481 } else {
3482 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3483 Context.DependentTy, VK_RValue,
3484 RParenLoc));
3485 }
3486 }
Douglas Gregor17330012009-02-04 15:01:18 +00003487
3488 // Determine whether this is a call to an object (C++ [over.call.object]).
3489 if (Fn->getType()->isRecordType())
3490 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003491 RParenLoc));
Douglas Gregor17330012009-02-04 15:01:18 +00003492
John McCall755d8492011-04-12 00:42:48 +00003493 if (Fn->getType() == Context.UnknownAnyTy) {
3494 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3495 if (result.isInvalid()) return ExprError();
3496 Fn = result.take();
3497 }
3498
John McCall864c0412011-04-26 20:42:42 +00003499 if (Fn->getType() == Context.BoundMemberTy) {
John McCallaa81e162009-12-01 22:10:20 +00003500 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003501 RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003502 }
John McCall864c0412011-04-26 20:42:42 +00003503 }
John McCall129e2df2009-11-30 22:42:35 +00003504
John McCall864c0412011-04-26 20:42:42 +00003505 // Check for overloaded calls. This can happen even in C due to extensions.
3506 if (Fn->getType() == Context.OverloadTy) {
3507 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3508
3509 // We aren't supposed to apply this logic if there's an '&' involved.
3510 if (!find.IsAddressOfOperand) {
3511 OverloadExpr *ovl = find.Expression;
3512 if (isa<UnresolvedLookupExpr>(ovl)) {
3513 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3514 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3515 RParenLoc, ExecConfig);
3516 } else {
John McCallaa81e162009-12-01 22:10:20 +00003517 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00003518 RParenLoc);
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003519 }
3520 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003521 }
3522
Douglas Gregorfa047642009-02-04 00:32:51 +00003523 // If we're directly calling a function, get the appropriate declaration.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003524
Eli Friedmanefa42f72009-12-26 03:35:45 +00003525 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregoref9b1492010-11-09 20:03:54 +00003526
John McCall3b4294e2009-12-16 12:17:52 +00003527 NamedDecl *NDecl = 0;
Douglas Gregord8f0ade2010-10-25 20:48:33 +00003528 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3529 if (UnOp->getOpcode() == UO_AddrOf)
3530 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3531
John McCall3b4294e2009-12-16 12:17:52 +00003532 if (isa<DeclRefExpr>(NakedFn))
3533 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall864c0412011-04-26 20:42:42 +00003534 else if (isa<MemberExpr>(NakedFn))
3535 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall3b4294e2009-12-16 12:17:52 +00003536
Peter Collingbournee08ce652011-02-09 21:07:24 +00003537 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3538 ExecConfig);
3539}
3540
3541ExprResult
3542Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3543 MultiExprArg execConfig, SourceLocation GGGLoc) {
3544 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3545 if (!ConfigDecl)
3546 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3547 << "cudaConfigureCall");
3548 QualType ConfigQTy = ConfigDecl->getType();
3549
3550 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3551 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3552
3553 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCallaa81e162009-12-01 22:10:20 +00003554}
3555
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003556/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3557///
3558/// __builtin_astype( value, dst type )
3559///
3560ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty,
3561 SourceLocation BuiltinLoc,
3562 SourceLocation RParenLoc) {
3563 ExprValueKind VK = VK_RValue;
3564 ExprObjectKind OK = OK_Ordinary;
3565 QualType DstTy = GetTypeFromParser(destty);
3566 QualType SrcTy = expr->getType();
3567 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3568 return ExprError(Diag(BuiltinLoc,
3569 diag::err_invalid_astype_of_different_size)
Peter Collingbourneaf9cddf2011-06-08 15:15:17 +00003570 << DstTy
3571 << SrcTy
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003572 << expr->getSourceRange());
Richard Trieu67e29332011-08-02 04:35:43 +00003573 return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc,
3574 RParenLoc));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003575}
3576
John McCall3b4294e2009-12-16 12:17:52 +00003577/// BuildResolvedCallExpr - Build a call to a resolved expression,
3578/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003579/// unary-convert to an expression of function-pointer or
3580/// block-pointer type.
3581///
3582/// \param NDecl the declaration being called, if available
John McCall60d7b3a2010-08-24 06:29:42 +00003583ExprResult
John McCallaa81e162009-12-01 22:10:20 +00003584Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3585 SourceLocation LParenLoc,
3586 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00003587 SourceLocation RParenLoc,
3588 Expr *Config) {
John McCallaa81e162009-12-01 22:10:20 +00003589 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3590
Chris Lattner04421082008-04-08 04:40:51 +00003591 // Promote the function operand.
John Wiegley429bb272011-04-08 18:41:53 +00003592 ExprResult Result = UsualUnaryConversions(Fn);
3593 if (Result.isInvalid())
3594 return ExprError();
3595 Fn = Result.take();
Chris Lattner04421082008-04-08 04:40:51 +00003596
Chris Lattner925e60d2007-12-28 05:29:59 +00003597 // Make the call expr early, before semantic checks. This guarantees cleanup
3598 // of arguments and function on error.
Peter Collingbournee08ce652011-02-09 21:07:24 +00003599 CallExpr *TheCall;
3600 if (Config) {
3601 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3602 cast<CallExpr>(Config),
3603 Args, NumArgs,
3604 Context.BoolTy,
3605 VK_RValue,
3606 RParenLoc);
3607 } else {
3608 TheCall = new (Context) CallExpr(Context, Fn,
3609 Args, NumArgs,
3610 Context.BoolTy,
3611 VK_RValue,
3612 RParenLoc);
3613 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003614
John McCall8e10f3b2011-02-26 05:39:39 +00003615 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3616
3617 // Bail out early if calling a builtin with custom typechecking.
3618 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3619 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3620
John McCall1de4d4e2011-04-07 08:22:57 +00003621 retry:
Steve Naroffdd972f22008-09-05 22:11:13 +00003622 const FunctionType *FuncT;
John McCall8e10f3b2011-02-26 05:39:39 +00003623 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00003624 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3625 // have type pointer to function".
John McCall183700f2009-09-21 23:43:11 +00003626 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCall8e10f3b2011-02-26 05:39:39 +00003627 if (FuncT == 0)
3628 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3629 << Fn->getType() << Fn->getSourceRange());
3630 } else if (const BlockPointerType *BPT =
3631 Fn->getType()->getAs<BlockPointerType>()) {
3632 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3633 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00003634 // Handle calls to expressions of unknown-any type.
3635 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall755d8492011-04-12 00:42:48 +00003636 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003637 if (rewrite.isInvalid()) return ExprError();
3638 Fn = rewrite.take();
John McCalla5fc4722011-04-09 22:50:59 +00003639 TheCall->setCallee(Fn);
John McCall1de4d4e2011-04-07 08:22:57 +00003640 goto retry;
3641 }
3642
Sebastian Redl0eb23302009-01-19 00:08:26 +00003643 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3644 << Fn->getType() << Fn->getSourceRange());
John McCall8e10f3b2011-02-26 05:39:39 +00003645 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003646
Peter Collingbourne0423fc62011-02-23 01:53:29 +00003647 if (getLangOptions().CUDA) {
3648 if (Config) {
3649 // CUDA: Kernel calls must be to global functions
3650 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3651 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3652 << FDecl->getName() << Fn->getSourceRange());
3653
3654 // CUDA: Kernel function must have 'void' return type
3655 if (!FuncT->getResultType()->isVoidType())
3656 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3657 << Fn->getType() << Fn->getSourceRange());
3658 }
3659 }
3660
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003661 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003662 if (CheckCallReturnType(FuncT->getResultType(),
John McCall9ae2f072010-08-23 23:25:46 +00003663 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003664 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003665 return ExprError();
3666
Chris Lattner925e60d2007-12-28 05:29:59 +00003667 // We know the result type of the call, set it.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003668 TheCall->setType(FuncT->getCallResultType(Context));
John McCallf89e55a2010-11-18 06:31:45 +00003669 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003670
Douglas Gregor72564e72009-02-26 23:50:07 +00003671 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCall9ae2f072010-08-23 23:25:46 +00003672 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003673 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003674 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003675 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003676 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003677
Douglas Gregor74734d52009-04-02 15:37:10 +00003678 if (FDecl) {
3679 // Check if we have too few/too many template arguments, based
3680 // on our knowledge of the function definition.
3681 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00003682 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor46542412010-10-25 20:39:23 +00003683 const FunctionProtoType *Proto
3684 = Def->getType()->getAs<FunctionProtoType>();
3685 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003686 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3687 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003688 }
Douglas Gregor46542412010-10-25 20:39:23 +00003689
3690 // If the function we're calling isn't a function prototype, but we have
3691 // a function prototype from a prior declaratiom, use that prototype.
3692 if (!FDecl->hasPrototype())
3693 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregor74734d52009-04-02 15:37:10 +00003694 }
3695
Steve Naroffb291ab62007-08-28 23:30:39 +00003696 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003697 for (unsigned i = 0; i != NumArgs; i++) {
3698 Expr *Arg = Args[i];
Douglas Gregor46542412010-10-25 20:39:23 +00003699
3700 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor46542412010-10-25 20:39:23 +00003701 InitializedEntity Entity
3702 = InitializedEntity::InitializeParameter(Context,
John McCallf85e1932011-06-15 23:02:42 +00003703 Proto->getArgType(i),
3704 Proto->isArgConsumed(i));
Douglas Gregor46542412010-10-25 20:39:23 +00003705 ExprResult ArgE = PerformCopyInitialization(Entity,
3706 SourceLocation(),
3707 Owned(Arg));
3708 if (ArgE.isInvalid())
3709 return true;
3710
3711 Arg = ArgE.takeAs<Expr>();
3712
3713 } else {
John Wiegley429bb272011-04-08 18:41:53 +00003714 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3715
3716 if (ArgE.isInvalid())
3717 return true;
3718
3719 Arg = ArgE.takeAs<Expr>();
Douglas Gregor46542412010-10-25 20:39:23 +00003720 }
3721
Douglas Gregor0700bbf2010-10-26 05:45:40 +00003722 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3723 Arg->getType(),
3724 PDiag(diag::err_call_incomplete_argument)
3725 << Arg->getSourceRange()))
3726 return ExprError();
3727
Chris Lattner925e60d2007-12-28 05:29:59 +00003728 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003729 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003730 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003731
Douglas Gregor88a35142008-12-22 05:46:06 +00003732 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3733 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003734 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3735 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003736
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003737 // Check for sentinels
3738 if (NDecl)
3739 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003740
Chris Lattner59907c42007-08-10 20:18:51 +00003741 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003742 if (FDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003743 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003744 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003745
John McCall8e10f3b2011-02-26 05:39:39 +00003746 if (BuiltinID)
Fariborz Jahanian67aba812010-11-30 17:35:24 +00003747 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssond406bf02009-08-16 01:56:34 +00003748 } else if (NDecl) {
John McCall9ae2f072010-08-23 23:25:46 +00003749 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00003750 return ExprError();
3751 }
Chris Lattner59907c42007-08-10 20:18:51 +00003752
John McCall9ae2f072010-08-23 23:25:46 +00003753 return MaybeBindToTemporary(TheCall);
Reid Spencer5f016e22007-07-11 17:01:13 +00003754}
3755
John McCall60d7b3a2010-08-24 06:29:42 +00003756ExprResult
John McCallb3d87482010-08-24 05:47:05 +00003757Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCall9ae2f072010-08-23 23:25:46 +00003758 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003759 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00003760 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003761 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00003762
3763 TypeSourceInfo *TInfo;
3764 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3765 if (!TInfo)
3766 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3767
John McCall9ae2f072010-08-23 23:25:46 +00003768 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCall42f56b52010-01-18 19:35:47 +00003769}
3770
John McCall60d7b3a2010-08-24 06:29:42 +00003771ExprResult
John McCall42f56b52010-01-18 19:35:47 +00003772Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCall9ae2f072010-08-23 23:25:46 +00003773 SourceLocation RParenLoc, Expr *literalExpr) {
John McCall42f56b52010-01-18 19:35:47 +00003774 QualType literalType = TInfo->getType();
Anders Carlssond35c8322007-12-05 07:24:19 +00003775
Eli Friedman6223c222008-05-20 05:22:08 +00003776 if (literalType->isArrayType()) {
Argyrios Kyrtzidise6fe9a22010-11-08 19:14:19 +00003777 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3778 PDiag(diag::err_illegal_decl_array_incomplete_type)
3779 << SourceRange(LParenLoc,
3780 literalExpr->getSourceRange().getEnd())))
3781 return ExprError();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003782 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003783 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3784 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003785 } else if (!literalType->isDependentType() &&
3786 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003787 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003788 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003789 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003790 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003791
Douglas Gregor99a2e602009-12-16 01:38:02 +00003792 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00003793 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003794 InitializationKind Kind
John McCallf85e1932011-06-15 23:02:42 +00003795 = InitializationKind::CreateCStyleCast(LParenLoc,
3796 SourceRange(LParenLoc, RParenLoc));
Eli Friedman08544622009-12-22 02:35:53 +00003797 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00003798 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00003799 MultiExprArg(*this, &literalExpr, 1),
Eli Friedman08544622009-12-22 02:35:53 +00003800 &literalType);
3801 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003802 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00003803 literalExpr = Result.get();
Steve Naroffe9b12192008-01-14 18:19:28 +00003804
Chris Lattner371f2582008-12-04 23:50:19 +00003805 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003806 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003807 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003808 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003809 }
Eli Friedman08544622009-12-22 02:35:53 +00003810
John McCallf89e55a2010-11-18 06:31:45 +00003811 // In C, compound literals are l-values for some reason.
3812 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3813
Douglas Gregor751ec9b2011-06-17 04:59:12 +00003814 return MaybeBindToTemporary(
3815 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
3816 VK, literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003817}
3818
John McCall60d7b3a2010-08-24 06:29:42 +00003819ExprResult
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003820Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003821 SourceLocation RBraceLoc) {
3822 unsigned NumInit = initlist.size();
John McCall9ae2f072010-08-23 23:25:46 +00003823 Expr **InitList = initlist.release();
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003824
Steve Naroff08d92e42007-09-15 18:49:24 +00003825 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003826 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003827
Ted Kremenek709210f2010-04-13 23:39:13 +00003828 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3829 NumInit, RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003830 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003831 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003832}
3833
John McCallf3ea8cf2010-11-14 08:17:51 +00003834/// Prepares for a scalar cast, performing all the necessary stages
3835/// except the final cast and returning the kind required.
John Wiegley429bb272011-04-08 18:41:53 +00003836static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCallf3ea8cf2010-11-14 08:17:51 +00003837 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3838 // Also, callers should have filtered out the invalid cases with
3839 // pointers. Everything else should be possible.
3840
John Wiegley429bb272011-04-08 18:41:53 +00003841 QualType SrcTy = Src.get()->getType();
John McCallf3ea8cf2010-11-14 08:17:51 +00003842 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCall2de56d12010-08-25 11:45:40 +00003843 return CK_NoOp;
Anders Carlsson82debc72009-10-18 18:12:03 +00003844
John McCalldaa8e4e2010-11-15 09:13:47 +00003845 switch (SrcTy->getScalarTypeKind()) {
3846 case Type::STK_MemberPointer:
3847 llvm_unreachable("member pointer type in C");
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003848
John McCalldaa8e4e2010-11-15 09:13:47 +00003849 case Type::STK_Pointer:
3850 switch (DestTy->getScalarTypeKind()) {
3851 case Type::STK_Pointer:
3852 return DestTy->isObjCObjectPointerType() ?
John McCallf3ea8cf2010-11-14 08:17:51 +00003853 CK_AnyPointerToObjCPointerCast :
3854 CK_BitCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003855 case Type::STK_Bool:
3856 return CK_PointerToBoolean;
3857 case Type::STK_Integral:
3858 return CK_PointerToIntegral;
3859 case Type::STK_Floating:
3860 case Type::STK_FloatingComplex:
3861 case Type::STK_IntegralComplex:
3862 case Type::STK_MemberPointer:
3863 llvm_unreachable("illegal cast from pointer");
3864 }
3865 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003866
John McCalldaa8e4e2010-11-15 09:13:47 +00003867 case Type::STK_Bool: // casting from bool is like casting from an integer
3868 case Type::STK_Integral:
3869 switch (DestTy->getScalarTypeKind()) {
3870 case Type::STK_Pointer:
Richard Trieu67e29332011-08-02 04:35:43 +00003871 if (Src.get()->isNullPointerConstant(S.Context,
3872 Expr::NPC_ValueDependentIsNull))
John McCall404cd162010-11-13 01:35:44 +00003873 return CK_NullToPointer;
John McCall2de56d12010-08-25 11:45:40 +00003874 return CK_IntegralToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00003875 case Type::STK_Bool:
3876 return CK_IntegralToBoolean;
3877 case Type::STK_Integral:
John McCallf3ea8cf2010-11-14 08:17:51 +00003878 return CK_IntegralCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003879 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00003880 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00003881 case Type::STK_IntegralComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003882 Src = S.ImpCastExprToType(Src.take(),
3883 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003884 CK_IntegralCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00003885 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003886 case Type::STK_FloatingComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003887 Src = S.ImpCastExprToType(Src.take(),
3888 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003889 CK_IntegralToFloating);
John McCallf3ea8cf2010-11-14 08:17:51 +00003890 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003891 case Type::STK_MemberPointer:
3892 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003893 }
3894 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003895
John McCalldaa8e4e2010-11-15 09:13:47 +00003896 case Type::STK_Floating:
3897 switch (DestTy->getScalarTypeKind()) {
3898 case Type::STK_Floating:
John McCall2de56d12010-08-25 11:45:40 +00003899 return CK_FloatingCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003900 case Type::STK_Bool:
3901 return CK_FloatingToBoolean;
3902 case Type::STK_Integral:
John McCall2de56d12010-08-25 11:45:40 +00003903 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00003904 case Type::STK_FloatingComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003905 Src = S.ImpCastExprToType(Src.take(),
3906 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003907 CK_FloatingCast);
John McCallf3ea8cf2010-11-14 08:17:51 +00003908 return CK_FloatingRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003909 case Type::STK_IntegralComplex:
Richard Trieu67e29332011-08-02 04:35:43 +00003910 Src = S.ImpCastExprToType(Src.take(),
3911 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003912 CK_FloatingToIntegral);
John McCallf3ea8cf2010-11-14 08:17:51 +00003913 return CK_IntegralRealToComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003914 case Type::STK_Pointer:
3915 llvm_unreachable("valid float->pointer cast?");
3916 case Type::STK_MemberPointer:
3917 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003918 }
3919 break;
3920
John McCalldaa8e4e2010-11-15 09:13:47 +00003921 case Type::STK_FloatingComplex:
3922 switch (DestTy->getScalarTypeKind()) {
3923 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003924 return CK_FloatingComplexCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00003925 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003926 return CK_FloatingComplexToIntegralComplex;
John McCall8786da72010-12-14 17:51:41 +00003927 case Type::STK_Floating: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003928 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00003929 if (S.Context.hasSameType(ET, DestTy))
3930 return CK_FloatingComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00003931 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00003932 return CK_FloatingCast;
3933 }
John McCalldaa8e4e2010-11-15 09:13:47 +00003934 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00003935 return CK_FloatingComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00003936 case Type::STK_Integral:
Richard Trieu67e29332011-08-02 04:35:43 +00003937 Src = S.ImpCastExprToType(Src.take(),
3938 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003939 CK_FloatingComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00003940 return CK_FloatingToIntegral;
John McCalldaa8e4e2010-11-15 09:13:47 +00003941 case Type::STK_Pointer:
3942 llvm_unreachable("valid complex float->pointer cast?");
3943 case Type::STK_MemberPointer:
3944 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003945 }
3946 break;
3947
John McCalldaa8e4e2010-11-15 09:13:47 +00003948 case Type::STK_IntegralComplex:
3949 switch (DestTy->getScalarTypeKind()) {
3950 case Type::STK_FloatingComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003951 return CK_IntegralComplexToFloatingComplex;
John McCalldaa8e4e2010-11-15 09:13:47 +00003952 case Type::STK_IntegralComplex:
John McCallf3ea8cf2010-11-14 08:17:51 +00003953 return CK_IntegralComplexCast;
John McCall8786da72010-12-14 17:51:41 +00003954 case Type::STK_Integral: {
Abramo Bagnarabb03f5d2011-01-04 09:50:03 +00003955 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00003956 if (S.Context.hasSameType(ET, DestTy))
3957 return CK_IntegralComplexToReal;
John Wiegley429bb272011-04-08 18:41:53 +00003958 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCall8786da72010-12-14 17:51:41 +00003959 return CK_IntegralCast;
3960 }
John McCalldaa8e4e2010-11-15 09:13:47 +00003961 case Type::STK_Bool:
John McCallf3ea8cf2010-11-14 08:17:51 +00003962 return CK_IntegralComplexToBoolean;
John McCalldaa8e4e2010-11-15 09:13:47 +00003963 case Type::STK_Floating:
Richard Trieu67e29332011-08-02 04:35:43 +00003964 Src = S.ImpCastExprToType(Src.take(),
3965 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley429bb272011-04-08 18:41:53 +00003966 CK_IntegralComplexToReal);
John McCallf3ea8cf2010-11-14 08:17:51 +00003967 return CK_IntegralToFloating;
John McCalldaa8e4e2010-11-15 09:13:47 +00003968 case Type::STK_Pointer:
3969 llvm_unreachable("valid complex int->pointer cast?");
3970 case Type::STK_MemberPointer:
3971 llvm_unreachable("member pointer type in C");
John McCallf3ea8cf2010-11-14 08:17:51 +00003972 }
3973 break;
Anders Carlsson82debc72009-10-18 18:12:03 +00003974 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003975
John McCallf3ea8cf2010-11-14 08:17:51 +00003976 llvm_unreachable("Unhandled scalar cast");
3977 return CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00003978}
3979
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003980/// CheckCastTypes - Check type constraints for casting between types.
John McCallf85e1932011-06-15 23:02:42 +00003981ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyR,
3982 QualType castType, Expr *castExpr,
3983 CastKind& Kind, ExprValueKind &VK,
John Wiegley429bb272011-04-08 18:41:53 +00003984 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall1de4d4e2011-04-07 08:22:57 +00003985 if (castExpr->getType() == Context.UnknownAnyTy)
3986 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
3987
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003988 if (getLangOptions().CPlusPlus)
John McCallf85e1932011-06-15 23:02:42 +00003989 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Douglas Gregor40749ee2010-11-03 00:35:38 +00003990 castExpr->getLocEnd()),
John McCallf89e55a2010-11-18 06:31:45 +00003991 castType, VK, castExpr, Kind, BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003992 FunctionalStyle);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003993
John McCallfb8721c2011-04-10 19:13:55 +00003994 assert(!castExpr->getType()->isPlaceholderType());
3995
John McCallf89e55a2010-11-18 06:31:45 +00003996 // We only support r-value casts in C.
3997 VK = VK_RValue;
3998
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003999 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4000 // type needs to be scalar.
4001 if (castType->isVoidType()) {
John McCallf6a16482010-12-04 03:47:34 +00004002 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley429bb272011-04-08 18:41:53 +00004003 ExprResult castExprRes = IgnoredValueConversions(castExpr);
4004 if (castExprRes.isInvalid())
4005 return ExprError();
4006 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00004007
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004008 // Cast to void allows any expr type.
John McCall2de56d12010-08-25 11:45:40 +00004009 Kind = CK_ToVoid;
John Wiegley429bb272011-04-08 18:41:53 +00004010 return Owned(castExpr);
Anders Carlssonebeaf202009-10-16 02:35:04 +00004011 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004012
John Wiegley429bb272011-04-08 18:41:53 +00004013 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
4014 if (castExprRes.isInvalid())
4015 return ExprError();
4016 castExpr = castExprRes.take();
John McCallf6a16482010-12-04 03:47:34 +00004017
Eli Friedman8d438082010-07-17 20:43:49 +00004018 if (RequireCompleteType(TyR.getBegin(), castType,
4019 diag::err_typecheck_cast_to_incomplete))
John Wiegley429bb272011-04-08 18:41:53 +00004020 return ExprError();
Eli Friedman8d438082010-07-17 20:43:49 +00004021
Anders Carlssonebeaf202009-10-16 02:35:04 +00004022 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00004023 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004024 (castType->isStructureType() || castType->isUnionType())) {
4025 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004026 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004027 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4028 << castType << castExpr->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004029 Kind = CK_NoOp;
John Wiegley429bb272011-04-08 18:41:53 +00004030 return Owned(castExpr);
Anders Carlssonc3516322009-10-16 02:48:28 +00004031 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004032
Anders Carlssonc3516322009-10-16 02:48:28 +00004033 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004034 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00004035 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004036 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004037 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004038 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004039 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara8c4bfe52010-10-07 21:20:44 +00004040 castExpr->getType()) &&
4041 !Field->isUnnamedBitfield()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004042 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4043 << castExpr->getSourceRange();
4044 break;
4045 }
4046 }
John Wiegley429bb272011-04-08 18:41:53 +00004047 if (Field == FieldEnd) {
4048 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00004049 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004050 return ExprError();
4051 }
John McCall2de56d12010-08-25 11:45:40 +00004052 Kind = CK_ToUnion;
John Wiegley429bb272011-04-08 18:41:53 +00004053 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004054 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004055
Anders Carlssonc3516322009-10-16 02:48:28 +00004056 // Reject any other conversions to non-scalar types.
John Wiegley429bb272011-04-08 18:41:53 +00004057 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlssonc3516322009-10-16 02:48:28 +00004058 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004059 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00004060 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004061
John McCallf3ea8cf2010-11-14 08:17:51 +00004062 // The type we're casting to is known to be a scalar or vector.
4063
4064 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004065 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00004066 !castExpr->getType()->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004067 Diag(castExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004068 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00004069 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004070 return ExprError();
Anders Carlssonc3516322009-10-16 02:48:28 +00004071 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004072
4073 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00004074 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004075
Anton Yartsevd06fea82011-03-27 09:32:40 +00004076 if (castType->isVectorType()) {
4077 if (castType->getAs<VectorType>()->getVectorKind() ==
4078 VectorType::AltiVecVector &&
4079 (castExpr->getType()->isIntegerType() ||
4080 castExpr->getType()->isFloatingType())) {
4081 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004082 return Owned(castExpr);
4083 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
4084 return ExprError();
Anton Yartsevd06fea82011-03-27 09:32:40 +00004085 } else
John Wiegley429bb272011-04-08 18:41:53 +00004086 return Owned(castExpr);
Anton Yartsevd06fea82011-03-27 09:32:40 +00004087 }
John Wiegley429bb272011-04-08 18:41:53 +00004088 if (castExpr->getType()->isVectorType()) {
4089 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
4090 return ExprError();
4091 else
4092 return Owned(castExpr);
4093 }
Anders Carlssonc3516322009-10-16 02:48:28 +00004094
John McCallf3ea8cf2010-11-14 08:17:51 +00004095 // The source and target types are both scalars, i.e.
4096 // - arithmetic types (fundamental, enum, and complex)
4097 // - all kinds of pointers
4098 // Note that member pointers were filtered out with C++, above.
4099
John Wiegley429bb272011-04-08 18:41:53 +00004100 if (isa<ObjCSelectorExpr>(castExpr)) {
4101 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
4102 return ExprError();
4103 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004104
John McCallf3ea8cf2010-11-14 08:17:51 +00004105 // If either type is a pointer, the other type has to be either an
4106 // integer or a pointer.
John McCallf85e1932011-06-15 23:02:42 +00004107 QualType castExprType = castExpr->getType();
Anders Carlssonc3516322009-10-16 02:48:28 +00004108 if (!castType->isArithmeticType()) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00004109 if (!castExprType->isIntegralType(Context) &&
John Wiegley429bb272011-04-08 18:41:53 +00004110 castExprType->isArithmeticType()) {
4111 Diag(castExpr->getLocStart(),
4112 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00004113 << castExprType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004114 return ExprError();
4115 }
Eli Friedman41826bb2009-05-01 02:23:58 +00004116 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004117 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
4118 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedman41826bb2009-05-01 02:23:58 +00004119 << castType << castExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004120 return ExprError();
4121 }
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004122 }
Anders Carlsson82debc72009-10-18 18:12:03 +00004123
John McCallf85e1932011-06-15 23:02:42 +00004124 if (getLangOptions().ObjCAutoRefCount) {
4125 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
4126 CheckObjCARCConversion(SourceRange(CastStartLoc, castExpr->getLocEnd()),
4127 castType, castExpr, CCK_CStyleCast);
4128
4129 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
4130 if (const PointerType *ExprPtr = castExprType->getAs<PointerType>()) {
4131 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4132 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4133 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4134 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4135 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
4136 Diag(castExpr->getLocStart(),
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00004137 diag::err_typecheck_incompatible_ownership)
John McCallf85e1932011-06-15 23:02:42 +00004138 << castExprType << castType << AA_Casting
4139 << castExpr->getSourceRange();
4140
4141 return ExprError();
4142 }
4143 }
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00004144 }
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00004145 else if (!CheckObjCARCUnavailableWeakConversion(castType, castExprType)) {
4146 Diag(castExpr->getLocStart(),
Fariborz Jahanian82007c32011-07-08 17:41:42 +00004147 diag::err_arc_convesion_of_weak_unavailable) << 1
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00004148 << castExprType << castType
4149 << castExpr->getSourceRange();
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00004150 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00004151 }
4152 }
4153
John Wiegley429bb272011-04-08 18:41:53 +00004154 castExprRes = Owned(castExpr);
4155 Kind = PrepareScalarCast(*this, castExprRes, castType);
4156 if (castExprRes.isInvalid())
4157 return ExprError();
4158 castExpr = castExprRes.take();
John McCallb7f4ffe2010-08-12 21:44:57 +00004159
John McCallf3ea8cf2010-11-14 08:17:51 +00004160 if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00004161 CheckCastAlign(castExpr, castType, TyR);
4162
John Wiegley429bb272011-04-08 18:41:53 +00004163 return Owned(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00004164}
4165
Anders Carlssonc3516322009-10-16 02:48:28 +00004166bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +00004167 CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00004168 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00004169
Anders Carlssona64db8f2007-11-27 05:51:55 +00004170 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00004171 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00004172 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004173 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004174 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004175 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004176 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004177 } else
4178 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004179 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004180 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004181
John McCall2de56d12010-08-25 11:45:40 +00004182 Kind = CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004183 return false;
4184}
4185
John Wiegley429bb272011-04-08 18:41:53 +00004186ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4187 Expr *CastExpr, CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004188 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004189
Anders Carlsson16a89042009-10-16 05:23:41 +00004190 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004191
Nate Begeman9b10da62009-06-27 22:05:55 +00004192 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4193 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00004194 if (SrcTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004195 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
4196 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begeman58d29a42009-06-26 00:50:28 +00004197 << DestTy << SrcTy << R;
John Wiegley429bb272011-04-08 18:41:53 +00004198 return ExprError();
4199 }
John McCall2de56d12010-08-25 11:45:40 +00004200 Kind = CK_BitCast;
John Wiegley429bb272011-04-08 18:41:53 +00004201 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004202 }
4203
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004204 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004205 // conversion will take place first from scalar to elt type, and then
4206 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004207 if (SrcTy->isPointerType())
4208 return Diag(R.getBegin(),
4209 diag::err_invalid_conversion_between_vector_and_scalar)
4210 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004211
4212 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley429bb272011-04-08 18:41:53 +00004213 ExprResult CastExprRes = Owned(CastExpr);
4214 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4215 if (CastExprRes.isInvalid())
4216 return ExprError();
4217 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004218
John McCall2de56d12010-08-25 11:45:40 +00004219 Kind = CK_VectorSplat;
John Wiegley429bb272011-04-08 18:41:53 +00004220 return Owned(CastExpr);
Nate Begeman58d29a42009-06-26 00:50:28 +00004221}
4222
John McCall60d7b3a2010-08-24 06:29:42 +00004223ExprResult
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004224Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4225 Declarator &D, ParsedType &Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004226 SourceLocation RParenLoc, Expr *castExpr) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004227 assert(!D.isInvalidType() && (castExpr != 0) &&
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004228 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004229
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00004230 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, castExpr->getType());
4231 if (D.isInvalidType())
4232 return ExprError();
4233
4234 if (getLangOptions().CPlusPlus) {
4235 // Check that there are no default arguments (C++ only).
4236 CheckExtraCXXDefaultArguments(D);
4237 }
4238
4239 QualType castType = castTInfo->getType();
4240 Ty = CreateParsedType(castType, castTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00004241
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004242 bool isVectorLiteral = false;
4243
4244 // Check for an altivec or OpenCL literal,
4245 // i.e. all the elements are integer constants.
4246 ParenExpr *PE = dyn_cast<ParenExpr>(castExpr);
4247 ParenListExpr *PLE = dyn_cast<ParenListExpr>(castExpr);
4248 if (getLangOptions().AltiVec && castType->isVectorType() && (PE || PLE)) {
4249 if (PLE && PLE->getNumExprs() == 0) {
4250 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4251 return ExprError();
4252 }
4253 if (PE || PLE->getNumExprs() == 1) {
4254 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4255 if (!E->getType()->isVectorType())
4256 isVectorLiteral = true;
4257 }
4258 else
4259 isVectorLiteral = true;
4260 }
4261
4262 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4263 // then handle it as such.
4264 if (isVectorLiteral)
4265 return BuildVectorLiteral(LParenLoc, RParenLoc, castExpr, castTInfo);
4266
Nate Begeman2ef13e52009-08-10 23:49:36 +00004267 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004268 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4269 // sequence of BinOp comma operators.
4270 if (isa<ParenListExpr>(castExpr)) {
4271 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, castExpr);
4272 if (Result.isInvalid()) return ExprError();
4273 castExpr = Result.take();
4274 }
John McCallb042fdf2010-01-15 18:56:44 +00004275
John McCall9ae2f072010-08-23 23:25:46 +00004276 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallb042fdf2010-01-15 18:56:44 +00004277}
4278
John McCall60d7b3a2010-08-24 06:29:42 +00004279ExprResult
John McCallb042fdf2010-01-15 18:56:44 +00004280Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCall9ae2f072010-08-23 23:25:46 +00004281 SourceLocation RParenLoc, Expr *castExpr) {
John McCalldaa8e4e2010-11-15 09:13:47 +00004282 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +00004283 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +00004284 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +00004285 ExprResult CastResult =
John McCallf85e1932011-06-15 23:02:42 +00004286 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
4287 castExpr, Kind, VK, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +00004288 if (CastResult.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004289 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004290 castExpr = CastResult.take();
Anders Carlsson0aebc812009-09-09 21:33:21 +00004291
Richard Trieu67e29332011-08-02 04:35:43 +00004292 return Owned(CStyleCastExpr::Create(
4293 Context, Ty->getType().getNonLValueExprType(Context), VK, Kind, castExpr,
4294 &BasePath, Ty, LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00004295}
4296
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004297ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4298 SourceLocation RParenLoc, Expr *E,
4299 TypeSourceInfo *TInfo) {
4300 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4301 "Expected paren or paren list expression");
4302
4303 Expr **exprs;
4304 unsigned numExprs;
4305 Expr *subExpr;
4306 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4307 exprs = PE->getExprs();
4308 numExprs = PE->getNumExprs();
4309 } else {
4310 subExpr = cast<ParenExpr>(E)->getSubExpr();
4311 exprs = &subExpr;
4312 numExprs = 1;
4313 }
4314
4315 QualType Ty = TInfo->getType();
4316 assert(Ty->isVectorType() && "Expected vector type");
4317
Chris Lattner5f9e2722011-07-23 10:55:15 +00004318 SmallVector<Expr *, 8> initExprs;
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004319 const VectorType *VTy = Ty->getAs<VectorType>();
4320 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4321
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004322 // '(...)' form of vector initialization in AltiVec: the number of
4323 // initializers must be one or must match the size of the vector.
4324 // If a single value is specified in the initializer then it will be
4325 // replicated to all the components of the vector
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004326 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004327 // The number of initializers must be one or must match the size of the
4328 // vector. If a single value is specified in the initializer then it will
4329 // be replicated to all the components of the vector
4330 if (numExprs == 1) {
4331 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4332 ExprResult Literal = Owned(exprs[0]);
4333 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4334 PrepareScalarCast(*this, Literal, ElemTy));
4335 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4336 }
4337 else if (numExprs < numElems) {
4338 Diag(E->getExprLoc(),
4339 diag::err_incorrect_number_of_vector_initializers);
4340 return ExprError();
4341 }
4342 else
4343 for (unsigned i = 0, e = numExprs; i != e; ++i)
4344 initExprs.push_back(exprs[i]);
4345 }
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004346 else {
4347 // For OpenCL, when the number of initializers is a single value,
4348 // it will be replicated to all components of the vector.
4349 if (getLangOptions().OpenCL &&
4350 VTy->getVectorKind() == VectorType::GenericVector &&
4351 numExprs == 1) {
4352 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4353 ExprResult Literal = Owned(exprs[0]);
4354 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4355 PrepareScalarCast(*this, Literal, ElemTy));
4356 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4357 }
4358
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004359 for (unsigned i = 0, e = numExprs; i != e; ++i)
4360 initExprs.push_back(exprs[i]);
Tanya Lattner61b4bc82011-07-15 23:07:01 +00004361 }
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004362 // FIXME: This means that pretty-printing the final AST will produce curly
4363 // braces instead of the original commas.
4364 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4365 &initExprs[0],
4366 initExprs.size(), RParenLoc);
4367 initE->setType(Ty);
4368 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4369}
4370
Nate Begeman2ef13e52009-08-10 23:49:36 +00004371/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4372/// of comma binary operators.
John McCall60d7b3a2010-08-24 06:29:42 +00004373ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004374Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004375 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4376 if (!E)
4377 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00004378
John McCall60d7b3a2010-08-24 06:29:42 +00004379 ExprResult Result(E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004380
Nate Begeman2ef13e52009-08-10 23:49:36 +00004381 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCall9ae2f072010-08-23 23:25:46 +00004382 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4383 E->getExpr(i));
Mike Stump1eb44332009-09-09 15:08:12 +00004384
John McCall9ae2f072010-08-23 23:25:46 +00004385 if (Result.isInvalid()) return ExprError();
4386
4387 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004388}
4389
John McCall60d7b3a2010-08-24 06:29:42 +00004390ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00004391 SourceLocation R,
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004392 MultiExprArg Val) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004393 unsigned nexprs = Val.size();
4394 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004395 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4396 Expr *expr;
Argyrios Kyrtzidis707f1012011-07-01 22:22:54 +00004397 if (nexprs == 1)
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004398 expr = new (Context) ParenExpr(L, R, exprs[0]);
4399 else
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004400 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4401 exprs[nexprs-1]->getType());
Nate Begeman2ef13e52009-08-10 23:49:36 +00004402 return Owned(expr);
4403}
4404
Chandler Carruth82214a82011-02-18 23:54:50 +00004405/// \brief Emit a specialized diagnostic when one expression is a null pointer
4406/// constant and the other is not a pointer.
4407bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
4408 SourceLocation QuestionLoc) {
4409 Expr *NullExpr = LHS;
4410 Expr *NonPointerExpr = RHS;
4411 Expr::NullPointerConstantKind NullKind =
4412 NullExpr->isNullPointerConstant(Context,
4413 Expr::NPC_ValueDependentIsNotNull);
4414
4415 if (NullKind == Expr::NPCK_NotNull) {
4416 NullExpr = RHS;
4417 NonPointerExpr = LHS;
4418 NullKind =
4419 NullExpr->isNullPointerConstant(Context,
4420 Expr::NPC_ValueDependentIsNotNull);
4421 }
4422
4423 if (NullKind == Expr::NPCK_NotNull)
4424 return false;
4425
4426 if (NullKind == Expr::NPCK_ZeroInteger) {
4427 // In this case, check to make sure that we got here from a "NULL"
4428 // string in the source code.
4429 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall834e3f62011-03-08 07:59:04 +00004430 SourceLocation loc = NullExpr->getExprLoc();
4431 if (!findMacroSpelling(loc, "NULL"))
Chandler Carruth82214a82011-02-18 23:54:50 +00004432 return false;
4433 }
4434
4435 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4436 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4437 << NonPointerExpr->getType() << DiagType
4438 << NonPointerExpr->getSourceRange();
4439 return true;
4440}
4441
Sebastian Redl28507842009-02-26 14:39:58 +00004442/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4443/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004444/// C99 6.5.15
Richard Trieu67e29332011-08-02 04:35:43 +00004445QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4446 ExprResult &RHS, ExprValueKind &VK,
4447 ExprObjectKind &OK,
Chris Lattnera119a3b2009-02-18 04:38:20 +00004448 SourceLocation QuestionLoc) {
Douglas Gregorfadb53b2011-03-12 01:48:56 +00004449
John McCallfb8721c2011-04-10 19:13:55 +00004450 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00004451 if (!lhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004452 LHS = move(lhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004453
John McCallfb8721c2011-04-10 19:13:55 +00004454 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall1de4d4e2011-04-07 08:22:57 +00004455 if (!rhsResult.isUsable()) return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004456 RHS = move(rhsResult);
Douglas Gregor7ad5d422010-11-09 21:07:58 +00004457
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004458 // C++ is sufficiently different to merit its own checker.
4459 if (getLangOptions().CPlusPlus)
John McCall56ca35d2011-02-17 10:25:35 +00004460 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCallf89e55a2010-11-18 06:31:45 +00004461
4462 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004463 OK = OK_Ordinary;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004464
John Wiegley429bb272011-04-08 18:41:53 +00004465 Cond = UsualUnaryConversions(Cond.take());
4466 if (Cond.isInvalid())
4467 return QualType();
4468 LHS = UsualUnaryConversions(LHS.take());
4469 if (LHS.isInvalid())
4470 return QualType();
4471 RHS = UsualUnaryConversions(RHS.take());
4472 if (RHS.isInvalid())
4473 return QualType();
4474
4475 QualType CondTy = Cond.get()->getType();
4476 QualType LHSTy = LHS.get()->getType();
4477 QualType RHSTy = RHS.get()->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004478
Reid Spencer5f016e22007-07-11 17:01:13 +00004479 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004480 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begeman6155d732010-09-20 22:41:17 +00004481 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4482 // Throw an error if its not either.
4483 if (getLangOptions().OpenCL) {
4484 if (!CondTy->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004485 Diag(Cond.get()->getLocStart(),
Nate Begeman6155d732010-09-20 22:41:17 +00004486 diag::err_typecheck_cond_expect_scalar_or_vector)
4487 << CondTy;
4488 return QualType();
4489 }
4490 }
4491 else {
John Wiegley429bb272011-04-08 18:41:53 +00004492 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00004493 << CondTy;
4494 return QualType();
4495 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004496 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004497
Chris Lattner70d67a92008-01-06 22:42:25 +00004498 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004499 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004500 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor898574e2008-12-05 23:32:09 +00004501
Nate Begeman6155d732010-09-20 22:41:17 +00004502 // OpenCL: If the condition is a vector, and both operands are scalar,
4503 // attempt to implicity convert them to the vector type to act like the
4504 // built in select.
4505 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
4506 // Both operands should be of scalar type.
4507 if (!LHSTy->isScalarType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004508 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00004509 << CondTy;
4510 return QualType();
4511 }
4512 if (!RHSTy->isScalarType()) {
John Wiegley429bb272011-04-08 18:41:53 +00004513 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begeman6155d732010-09-20 22:41:17 +00004514 << CondTy;
4515 return QualType();
4516 }
4517 // Implicity convert these scalars to the type of the condition.
John Wiegley429bb272011-04-08 18:41:53 +00004518 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4519 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begeman6155d732010-09-20 22:41:17 +00004520 }
4521
Chris Lattner70d67a92008-01-06 22:42:25 +00004522 // If both operands have arithmetic type, do the usual arithmetic conversions
4523 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004524 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4525 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004526 if (LHS.isInvalid() || RHS.isInvalid())
4527 return QualType();
4528 return LHS.get()->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004529 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004530
Chris Lattner70d67a92008-01-06 22:42:25 +00004531 // If both operands are the same structure or union type, the result is that
4532 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004533 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4534 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004535 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004536 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004537 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004538 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004539 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004540 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004541
Chris Lattner70d67a92008-01-06 22:42:25 +00004542 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004543 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004544 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4545 if (!LHSTy->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +00004546 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4547 << RHS.get()->getSourceRange();
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004548 if (!RHSTy->isVoidType())
John Wiegley429bb272011-04-08 18:41:53 +00004549 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4550 << LHS.get()->getSourceRange();
4551 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
4552 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00004553 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00004554 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00004555 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4556 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004557 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Richard Trieu67e29332011-08-02 04:35:43 +00004558 RHS.get()->isNullPointerConstant(Context,
4559 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004560 // promote the null to a pointer.
John Wiegley429bb272011-04-08 18:41:53 +00004561 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004562 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004563 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004564 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Richard Trieu67e29332011-08-02 04:35:43 +00004565 LHS.get()->isNullPointerConstant(Context,
4566 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00004567 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004568 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004569 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004570
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004571 // All objective-c pointer type analysis is done here.
4572 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4573 QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00004574 if (LHS.isInvalid() || RHS.isInvalid())
4575 return QualType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004576 if (!compositeType.isNull())
4577 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004578
4579
Steve Naroff7154a772009-07-01 14:36:47 +00004580 // Handle block pointer types.
4581 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4582 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4583 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4584 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00004585 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4586 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004587 return destType;
4588 }
4589 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00004590 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4591 << RHS.get()->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00004592 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004593 }
Steve Naroff7154a772009-07-01 14:36:47 +00004594 // We have 2 block pointer types.
4595 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4596 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004597 return LHSTy;
4598 }
Steve Naroff7154a772009-07-01 14:36:47 +00004599 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00004600 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4601 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004602
Steve Naroff7154a772009-07-01 14:36:47 +00004603 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4604 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00004605 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00004606 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4607 << RHS.get()->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004608 // In this situation, we assume void* type. No especially good
4609 // reason, but this is what gcc does, and we do have to pick
4610 // to get a consistent AST.
4611 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00004612 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4613 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00004614 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004615 }
Steve Naroff7154a772009-07-01 14:36:47 +00004616 // The block pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00004617 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4618 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00004619 return LHSTy;
4620 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004621
Steve Naroff7154a772009-07-01 14:36:47 +00004622 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4623 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4624 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00004625 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4626 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00004627
4628 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4629 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4630 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00004631 QualType destPointee
4632 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004633 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004634 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004635 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004636 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004637 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004638 return destType;
4639 }
4640 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00004641 QualType destPointee
4642 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004643 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004644 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004645 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004646 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004647 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004648 return destType;
4649 }
4650
4651 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4652 // Two identical pointer types are always compatible.
4653 return LHSTy;
4654 }
4655 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4656 rhptee.getUnqualifiedType())) {
4657 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00004658 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4659 << RHS.get()->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00004660 // In this situation, we assume void* type. No especially good
4661 // reason, but this is what gcc does, and we do have to pick
4662 // to get a consistent AST.
4663 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley429bb272011-04-08 18:41:53 +00004664 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4665 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004666 return incompatTy;
4667 }
4668 // The pointer types are compatible.
4669 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4670 // differently qualified versions of compatible types, the result type is
4671 // a pointer to an appropriately qualified version of the *composite*
4672 // type.
4673 // FIXME: Need to calculate the composite type.
4674 // FIXME: Need to add qualifiers
John Wiegley429bb272011-04-08 18:41:53 +00004675 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4676 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004677 return LHSTy;
4678 }
Mike Stump1eb44332009-09-09 15:08:12 +00004679
John McCall404cd162010-11-13 01:35:44 +00004680 // GCC compatibility: soften pointer/integer mismatch. Note that
4681 // null pointers have been filtered out by this point.
Steve Naroff7154a772009-07-01 14:36:47 +00004682 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4683 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
Richard Trieu67e29332011-08-02 04:35:43 +00004684 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4685 << RHS.get()->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004686 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004687 return RHSTy;
4688 }
4689 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4690 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
Richard Trieu67e29332011-08-02 04:35:43 +00004691 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4692 << RHS.get()->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004693 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004694 return LHSTy;
4695 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004696
Chandler Carruth82214a82011-02-18 23:54:50 +00004697 // Emit a better diagnostic if one of the expressions is a null pointer
4698 // constant and the other is not a pointer type. In this case, the user most
4699 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00004700 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00004701 return QualType();
4702
Chris Lattner70d67a92008-01-06 22:42:25 +00004703 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004704 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieu67e29332011-08-02 04:35:43 +00004705 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4706 << RHS.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004707 return QualType();
4708}
4709
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004710/// FindCompositeObjCPointerType - Helper method to find composite type of
4711/// two objective-c pointer types of the two input expressions.
John Wiegley429bb272011-04-08 18:41:53 +00004712QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieu67e29332011-08-02 04:35:43 +00004713 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00004714 QualType LHSTy = LHS.get()->getType();
4715 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004716
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004717 // Handle things like Class and struct objc_class*. Here we case the result
4718 // to the pseudo-builtin, because that will be implicitly cast back to the
4719 // redefinition type if an attempt is made to access its fields.
4720 if (LHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00004721 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00004722 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004723 return LHSTy;
4724 }
4725 if (RHSTy->isObjCClassType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00004726 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00004727 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004728 return RHSTy;
4729 }
4730 // And the same for struct objc_object* / id
4731 if (LHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00004732 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00004733 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004734 return LHSTy;
4735 }
4736 if (RHSTy->isObjCIdType() &&
John McCall49f4e1c2010-12-10 11:01:00 +00004737 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00004738 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004739 return RHSTy;
4740 }
4741 // And the same for struct objc_selector* / SEL
4742 if (Context.isObjCSelType(LHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00004743 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00004744 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004745 return LHSTy;
4746 }
4747 if (Context.isObjCSelType(RHSTy) &&
John McCall49f4e1c2010-12-10 11:01:00 +00004748 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley429bb272011-04-08 18:41:53 +00004749 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004750 return RHSTy;
4751 }
4752 // Check constraints for Objective-C object pointers types.
4753 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004754
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004755 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4756 // Two identical object pointer types are always compatible.
4757 return LHSTy;
4758 }
4759 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4760 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4761 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004762
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004763 // If both operands are interfaces and either operand can be
4764 // assigned to the other, use that type as the composite
4765 // type. This allows
4766 // xxx ? (A*) a : (B*) b
4767 // where B is a subclass of A.
4768 //
4769 // Additionally, as for assignment, if either type is 'id'
4770 // allow silent coercion. Finally, if the types are
4771 // incompatible then make sure to use 'id' as the composite
4772 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004773
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004774 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4775 // It could return the composite type.
4776 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4777 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4778 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4779 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4780 } else if ((LHSTy->isObjCQualifiedIdType() ||
4781 RHSTy->isObjCQualifiedIdType()) &&
4782 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4783 // Need to handle "id<xx>" explicitly.
4784 // GCC allows qualified id and any Objective-C type to devolve to
4785 // id. Currently localizing to here until clear this should be
4786 // part of ObjCQualifiedIdTypesAreCompatible.
4787 compositeType = Context.getObjCIdType();
4788 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4789 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004790 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004791 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4792 ;
4793 else {
4794 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4795 << LHSTy << RHSTy
John Wiegley429bb272011-04-08 18:41:53 +00004796 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004797 QualType incompatTy = Context.getObjCIdType();
John Wiegley429bb272011-04-08 18:41:53 +00004798 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4799 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004800 return incompatTy;
4801 }
4802 // The object pointer types are compatible.
John Wiegley429bb272011-04-08 18:41:53 +00004803 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4804 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004805 return compositeType;
4806 }
4807 // Check Objective-C object pointer types and 'void *'
4808 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4809 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4810 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4811 QualType destPointee
4812 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4813 QualType destType = Context.getPointerType(destPointee);
4814 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004815 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004816 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004817 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004818 return destType;
4819 }
4820 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4821 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4822 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4823 QualType destPointee
4824 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4825 QualType destType = Context.getPointerType(destPointee);
4826 // Add qualifiers if necessary.
John Wiegley429bb272011-04-08 18:41:53 +00004827 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004828 // Promote to void*.
John Wiegley429bb272011-04-08 18:41:53 +00004829 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004830 return destType;
4831 }
4832 return QualType();
4833}
4834
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004835/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004836/// ParenRange in parentheses.
4837static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004838 const PartialDiagnostic &Note,
4839 SourceRange ParenRange) {
4840 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4841 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4842 EndLoc.isValid()) {
4843 Self.Diag(Loc, Note)
4844 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4845 << FixItHint::CreateInsertion(EndLoc, ")");
4846 } else {
4847 // We can't display the parentheses, so just show the bare note.
4848 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004849 }
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004850}
4851
4852static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4853 return Opc >= BO_Mul && Opc <= BO_Shr;
4854}
4855
Hans Wennborg2f072b42011-06-09 17:06:51 +00004856/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4857/// expression, either using a built-in or overloaded operator,
4858/// and sets *OpCode to the opcode and *RHS to the right-hand side expression.
4859static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
4860 Expr **RHS) {
4861 E = E->IgnoreParenImpCasts();
4862 E = E->IgnoreConversionOperator();
4863 E = E->IgnoreParenImpCasts();
4864
4865 // Built-in binary operator.
4866 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4867 if (IsArithmeticOp(OP->getOpcode())) {
4868 *Opcode = OP->getOpcode();
4869 *RHS = OP->getRHS();
4870 return true;
4871 }
4872 }
4873
4874 // Overloaded operator.
4875 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4876 if (Call->getNumArgs() != 2)
4877 return false;
4878
4879 // Make sure this is really a binary operator that is safe to pass into
4880 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4881 OverloadedOperatorKind OO = Call->getOperator();
4882 if (OO < OO_Plus || OO > OO_Arrow)
4883 return false;
4884
4885 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4886 if (IsArithmeticOp(OpKind)) {
4887 *Opcode = OpKind;
4888 *RHS = Call->getArg(1);
4889 return true;
4890 }
4891 }
4892
4893 return false;
4894}
4895
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004896static bool IsLogicOp(BinaryOperatorKind Opc) {
4897 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4898}
4899
Hans Wennborg2f072b42011-06-09 17:06:51 +00004900/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4901/// or is a logical expression such as (x==y) which has int type, but is
4902/// commonly interpreted as boolean.
4903static bool ExprLooksBoolean(Expr *E) {
4904 E = E->IgnoreParenImpCasts();
4905
4906 if (E->getType()->isBooleanType())
4907 return true;
4908 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4909 return IsLogicOp(OP->getOpcode());
4910 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4911 return OP->getOpcode() == UO_LNot;
4912
4913 return false;
4914}
4915
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004916/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4917/// and binary operator are mixed in a way that suggests the programmer assumed
4918/// the conditional operator has higher precedence, for example:
4919/// "int x = a + someBinaryCondition ? 1 : 2".
4920static void DiagnoseConditionalPrecedence(Sema &Self,
4921 SourceLocation OpLoc,
Chandler Carruth43bc78d2011-06-16 01:05:08 +00004922 Expr *Condition,
4923 Expr *LHS,
4924 Expr *RHS) {
Hans Wennborg2f072b42011-06-09 17:06:51 +00004925 BinaryOperatorKind CondOpcode;
4926 Expr *CondRHS;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004927
Chandler Carruth43bc78d2011-06-16 01:05:08 +00004928 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborg2f072b42011-06-09 17:06:51 +00004929 return;
4930 if (!ExprLooksBoolean(CondRHS))
4931 return;
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004932
Hans Wennborg2f072b42011-06-09 17:06:51 +00004933 // The condition is an arithmetic binary expression, with a right-
4934 // hand side that looks boolean, so warn.
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004935
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004936 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth43bc78d2011-06-16 01:05:08 +00004937 << Condition->getSourceRange()
Hans Wennborg2f072b42011-06-09 17:06:51 +00004938 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004939
Chandler Carruthf0b60d62011-06-16 01:05:14 +00004940 SuggestParentheses(Self, OpLoc,
4941 Self.PDiag(diag::note_precedence_conditional_silence)
4942 << BinaryOperator::getOpcodeStr(CondOpcode),
4943 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruth9d5353c2011-06-21 23:04:18 +00004944
4945 SuggestParentheses(Self, OpLoc,
4946 Self.PDiag(diag::note_precedence_conditional_first),
4947 SourceRange(CondRHS->getLocStart(), RHS->getLocEnd()));
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004948}
4949
Steve Narofff69936d2007-09-16 03:34:24 +00004950/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00004951/// in the case of a the GNU conditional expr extension.
John McCall60d7b3a2010-08-24 06:29:42 +00004952ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCall56ca35d2011-02-17 10:25:35 +00004953 SourceLocation ColonLoc,
4954 Expr *CondExpr, Expr *LHSExpr,
4955 Expr *RHSExpr) {
Chris Lattnera21ddb32007-11-26 01:40:58 +00004956 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4957 // was the condition.
John McCall56ca35d2011-02-17 10:25:35 +00004958 OpaqueValueExpr *opaqueValue = 0;
4959 Expr *commonExpr = 0;
4960 if (LHSExpr == 0) {
4961 commonExpr = CondExpr;
4962
4963 // We usually want to apply unary conversions *before* saving, except
4964 // in the special case of a C++ l-value conditional.
4965 if (!(getLangOptions().CPlusPlus
4966 && !commonExpr->isTypeDependent()
4967 && commonExpr->getValueKind() == RHSExpr->getValueKind()
4968 && commonExpr->isGLValue()
4969 && commonExpr->isOrdinaryOrBitFieldObject()
4970 && RHSExpr->isOrdinaryOrBitFieldObject()
4971 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley429bb272011-04-08 18:41:53 +00004972 ExprResult commonRes = UsualUnaryConversions(commonExpr);
4973 if (commonRes.isInvalid())
4974 return ExprError();
4975 commonExpr = commonRes.take();
John McCall56ca35d2011-02-17 10:25:35 +00004976 }
4977
4978 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
4979 commonExpr->getType(),
4980 commonExpr->getValueKind(),
4981 commonExpr->getObjectKind());
4982 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004983 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004984
John McCallf89e55a2010-11-18 06:31:45 +00004985 ExprValueKind VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004986 ExprObjectKind OK = OK_Ordinary;
John Wiegley429bb272011-04-08 18:41:53 +00004987 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
4988 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCall56ca35d2011-02-17 10:25:35 +00004989 VK, OK, QuestionLoc);
John Wiegley429bb272011-04-08 18:41:53 +00004990 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
4991 RHS.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004992 return ExprError();
4993
Hans Wennborg9cfdae32011-06-03 18:00:36 +00004994 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
4995 RHS.get());
4996
John McCall56ca35d2011-02-17 10:25:35 +00004997 if (!commonExpr)
John Wiegley429bb272011-04-08 18:41:53 +00004998 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
4999 LHS.take(), ColonLoc,
5000 RHS.take(), result, VK, OK));
John McCall56ca35d2011-02-17 10:25:35 +00005001
5002 return Owned(new (Context)
John Wiegley429bb272011-04-08 18:41:53 +00005003 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieu67e29332011-08-02 04:35:43 +00005004 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5005 OK));
Reid Spencer5f016e22007-07-11 17:01:13 +00005006}
5007
John McCalle4be87e2011-01-31 23:13:11 +00005008// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00005009// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00005010// routine is it effectively iqnores the qualifiers on the top level pointee.
5011// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5012// FIXME: add a couple examples in this comment.
John McCalle4be87e2011-01-31 23:13:11 +00005013static Sema::AssignConvertType
5014checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5015 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5016 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005017
Reid Spencer5f016e22007-07-11 17:01:13 +00005018 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall86c05f32011-02-01 00:10:29 +00005019 const Type *lhptee, *rhptee;
5020 Qualifiers lhq, rhq;
5021 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5022 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005023
John McCalle4be87e2011-01-31 23:13:11 +00005024 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005025
5026 // C99 6.5.16.1p1: This following citation is common to constraints
5027 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5028 // qualifiers of the type *pointed to* by the right;
John McCall86c05f32011-02-01 00:10:29 +00005029 Qualifiers lq;
5030
John McCallf85e1932011-06-15 23:02:42 +00005031 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5032 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5033 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5034 // Ignore lifetime for further calculation.
5035 lhq.removeObjCLifetime();
5036 rhq.removeObjCLifetime();
5037 }
5038
John McCall86c05f32011-02-01 00:10:29 +00005039 if (!lhq.compatiblyIncludes(rhq)) {
5040 // Treat address-space mismatches as fatal. TODO: address subspaces
5041 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5042 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5043
John McCallf85e1932011-06-15 23:02:42 +00005044 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall22348732011-03-26 02:56:45 +00005045 // and from void*.
John McCallf85e1932011-06-15 23:02:42 +00005046 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5047 .compatiblyIncludes(
5048 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall22348732011-03-26 02:56:45 +00005049 && (lhptee->isVoidType() || rhptee->isVoidType()))
5050 ; // keep old
5051
John McCallf85e1932011-06-15 23:02:42 +00005052 // Treat lifetime mismatches as fatal.
5053 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5054 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5055
John McCall86c05f32011-02-01 00:10:29 +00005056 // For GCC compatibility, other qualifier mismatches are treated
5057 // as still compatible in C.
5058 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5059 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005060
Mike Stumpeed9cac2009-02-19 03:04:26 +00005061 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5062 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00005063 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005064 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005065 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005066 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005067
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005068 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005069 assert(rhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005070 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005071 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005072
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005073 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00005074 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00005075 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005076
5077 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00005078 assert(lhptee->isFunctionType());
John McCalle4be87e2011-01-31 23:13:11 +00005079 return Sema::FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00005080 }
John McCall86c05f32011-02-01 00:10:29 +00005081
Mike Stumpeed9cac2009-02-19 03:04:26 +00005082 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00005083 // unqualified versions of compatible types, ...
John McCall86c05f32011-02-01 00:10:29 +00005084 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5085 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005086 // Check if the pointee types are compatible ignoring the sign.
5087 // We explicitly check for char so that we catch "char" vs
5088 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00005089 if (lhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005090 ltrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005091 else if (lhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005092 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005093
Chris Lattner6a2b9262009-10-17 20:33:28 +00005094 if (rhptee->isCharType())
John McCall86c05f32011-02-01 00:10:29 +00005095 rtrans = S.Context.UnsignedCharTy;
Douglas Gregorf6094622010-07-23 15:58:24 +00005096 else if (rhptee->hasSignedIntegerRepresentation())
John McCall86c05f32011-02-01 00:10:29 +00005097 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattner6a2b9262009-10-17 20:33:28 +00005098
John McCall86c05f32011-02-01 00:10:29 +00005099 if (ltrans == rtrans) {
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005100 // Types are compatible ignoring the sign. Qualifier incompatibility
5101 // takes priority over sign incompatibility because the sign
5102 // warning can be disabled.
John McCalle4be87e2011-01-31 23:13:11 +00005103 if (ConvTy != Sema::Compatible)
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005104 return ConvTy;
John McCall86c05f32011-02-01 00:10:29 +00005105
John McCalle4be87e2011-01-31 23:13:11 +00005106 return Sema::IncompatiblePointerSign;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005107 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005108
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005109 // If we are a multi-level pointer, it's possible that our issue is simply
5110 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5111 // the eventual target type is the same and the pointers have the same
5112 // level of indirection, this must be the issue.
John McCalle4be87e2011-01-31 23:13:11 +00005113 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005114 do {
John McCall86c05f32011-02-01 00:10:29 +00005115 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5116 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCalle4be87e2011-01-31 23:13:11 +00005117 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005118
John McCall86c05f32011-02-01 00:10:29 +00005119 if (lhptee == rhptee)
John McCalle4be87e2011-01-31 23:13:11 +00005120 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00005121 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005122
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005123 // General pointer incompatibility takes priority over qualifiers.
John McCalle4be87e2011-01-31 23:13:11 +00005124 return Sema::IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005125 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005126 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005127}
5128
John McCalle4be87e2011-01-31 23:13:11 +00005129/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff1c7d0672008-09-04 15:10:53 +00005130/// block pointer types are compatible or whether a block and normal pointer
5131/// are compatible. It is more restrict than comparing two function pointer
5132// types.
John McCalle4be87e2011-01-31 23:13:11 +00005133static Sema::AssignConvertType
5134checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5135 QualType rhsType) {
5136 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5137 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5138
Steve Naroff1c7d0672008-09-04 15:10:53 +00005139 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005140
Steve Naroff1c7d0672008-09-04 15:10:53 +00005141 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCalle4be87e2011-01-31 23:13:11 +00005142 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5143 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005144
John McCalle4be87e2011-01-31 23:13:11 +00005145 // In C++, the types have to match exactly.
5146 if (S.getLangOptions().CPlusPlus)
5147 return Sema::IncompatibleBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005148
John McCalle4be87e2011-01-31 23:13:11 +00005149 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005150
Steve Naroff1c7d0672008-09-04 15:10:53 +00005151 // For blocks we enforce that qualifiers are identical.
John McCalle4be87e2011-01-31 23:13:11 +00005152 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5153 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005154
John McCalle4be87e2011-01-31 23:13:11 +00005155 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5156 return Sema::IncompatibleBlockPointer;
5157
Steve Naroff1c7d0672008-09-04 15:10:53 +00005158 return ConvTy;
5159}
5160
John McCalle4be87e2011-01-31 23:13:11 +00005161/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005162/// for assignment compatibility.
John McCalle4be87e2011-01-31 23:13:11 +00005163static Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005164checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType,
5165 QualType rhsType) {
John McCalle4be87e2011-01-31 23:13:11 +00005166 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5167 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5168
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005169 if (lhsType->isObjCBuiltinType()) {
5170 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005171 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5172 !rhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005173 return Sema::IncompatiblePointer;
5174 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005175 }
5176 if (rhsType->isObjCBuiltinType()) {
5177 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00005178 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5179 !lhsType->isObjCQualifiedClassType())
John McCalle4be87e2011-01-31 23:13:11 +00005180 return Sema::IncompatiblePointer;
5181 return Sema::Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00005182 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005183 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005184 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005185 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005186 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005187
John McCalle4be87e2011-01-31 23:13:11 +00005188 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5189 return Sema::CompatiblePointerDiscardsQualifiers;
5190
5191 if (S.Context.typesAreCompatible(lhsType, rhsType))
5192 return Sema::Compatible;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005193 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCalle4be87e2011-01-31 23:13:11 +00005194 return Sema::IncompatibleObjCQualifiedId;
5195 return Sema::IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00005196}
5197
John McCall1c23e912010-11-16 02:32:08 +00005198Sema::AssignConvertType
Douglas Gregorb608b982011-01-28 02:26:04 +00005199Sema::CheckAssignmentConstraints(SourceLocation Loc,
5200 QualType lhsType, QualType rhsType) {
John McCall1c23e912010-11-16 02:32:08 +00005201 // Fake up an opaque expression. We don't actually care about what
5202 // cast operations are required, so if CheckAssignmentConstraints
5203 // adds casts to this they'll be wasted, but fortunately that doesn't
5204 // usually happen on valid code.
Douglas Gregorb608b982011-01-28 02:26:04 +00005205 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00005206 ExprResult rhsPtr = &rhs;
John McCall1c23e912010-11-16 02:32:08 +00005207 CastKind K = CK_Invalid;
5208
5209 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5210}
5211
Mike Stumpeed9cac2009-02-19 03:04:26 +00005212/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5213/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00005214/// pointers. Here are some objectionable examples that GCC considers warnings:
5215///
5216/// int a, *pint;
5217/// short *pshort;
5218/// struct foo *pfoo;
5219///
5220/// pint = pshort; // warning: assignment from incompatible pointer type
5221/// a = pint; // warning: assignment makes integer from pointer without a cast
5222/// pint = a; // warning: assignment makes pointer from integer without a cast
5223/// pint = pfoo; // warning: assignment from incompatible pointer type
5224///
5225/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00005226/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00005227///
John McCalldaa8e4e2010-11-15 09:13:47 +00005228/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner5cf216b2008-01-04 18:04:52 +00005229Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00005230Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCalldaa8e4e2010-11-15 09:13:47 +00005231 CastKind &Kind) {
John Wiegley429bb272011-04-08 18:41:53 +00005232 QualType rhsType = rhs.get()->getType();
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005233 QualType origLhsType = lhsType;
John McCall1c23e912010-11-16 02:32:08 +00005234
Chris Lattnerfc144e22008-01-04 23:18:45 +00005235 // Get canonical types. We're not formatting these types, just comparing
5236 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00005237 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5238 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005239
John McCallb6cfa242011-01-31 22:28:28 +00005240 // Common case: no conversion required.
John McCalldaa8e4e2010-11-15 09:13:47 +00005241 if (lhsType == rhsType) {
5242 Kind = CK_NoOp;
John McCalldaa8e4e2010-11-15 09:13:47 +00005243 return Compatible;
David Chisnall0f436562009-08-17 16:35:33 +00005244 }
5245
Douglas Gregor9d293df2008-10-28 00:22:11 +00005246 // If the left-hand side is a reference type, then we are in a
5247 // (rare!) case where we've allowed the use of references in C,
5248 // e.g., as a parameter type in a built-in function. In this case,
5249 // just make sure that the type referenced is compatible with the
5250 // right-hand side type. The caller is responsible for adjusting
5251 // lhsType so that the resulting expression does not have reference
5252 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00005253 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005254 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5255 Kind = CK_LValueBitCast;
Anders Carlsson793680e2007-10-12 23:56:29 +00005256 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005257 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00005258 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00005259 }
John McCallb6cfa242011-01-31 22:28:28 +00005260
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005261 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5262 // to the same ExtVector type.
5263 if (lhsType->isExtVectorType()) {
5264 if (rhsType->isExtVectorType())
John McCalldaa8e4e2010-11-15 09:13:47 +00005265 return Incompatible;
5266 if (rhsType->isArithmeticType()) {
John McCall1c23e912010-11-16 02:32:08 +00005267 // CK_VectorSplat does T -> vector T, so first cast to the
5268 // element type.
5269 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5270 if (elType != rhsType) {
5271 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley429bb272011-04-08 18:41:53 +00005272 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall1c23e912010-11-16 02:32:08 +00005273 }
5274 Kind = CK_VectorSplat;
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005275 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005276 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005277 }
Mike Stump1eb44332009-09-09 15:08:12 +00005278
John McCallb6cfa242011-01-31 22:28:28 +00005279 // Conversions to or from vector type.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005280 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor255210e2010-08-06 10:14:59 +00005281 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilsonde3deea2010-12-02 00:25:15 +00005282 // Allow assignments of an AltiVec vector type to an equivalent GCC
5283 // vector type and vice versa
5284 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5285 Kind = CK_BitCast;
5286 return Compatible;
5287 }
5288
Douglas Gregor255210e2010-08-06 10:14:59 +00005289 // If we are allowing lax vector conversions, and LHS and RHS are both
5290 // vectors, the total size only needs to be the same. This is a bitcast;
5291 // no bits are changed but the result type is different.
5292 if (getLangOptions().LaxVectorConversions &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005293 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall0c6d28d2010-11-15 10:08:00 +00005294 Kind = CK_BitCast;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005295 return IncompatibleVectors;
John McCalldaa8e4e2010-11-15 09:13:47 +00005296 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00005297 }
5298 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005299 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005300
John McCallb6cfa242011-01-31 22:28:28 +00005301 // Arithmetic conversions.
Douglas Gregor88623ad2010-05-23 21:53:47 +00005302 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00005303 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall1c23e912010-11-16 02:32:08 +00005304 Kind = PrepareScalarCast(*this, rhs, lhsType);
Reid Spencer5f016e22007-07-11 17:01:13 +00005305 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005306 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005307
John McCallb6cfa242011-01-31 22:28:28 +00005308 // Conversions to normal pointers.
5309 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5310 // U* -> T*
John McCalldaa8e4e2010-11-15 09:13:47 +00005311 if (isa<PointerType>(rhsType)) {
5312 Kind = CK_BitCast;
John McCalle4be87e2011-01-31 23:13:11 +00005313 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalldaa8e4e2010-11-15 09:13:47 +00005314 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005315
John McCallb6cfa242011-01-31 22:28:28 +00005316 // int -> T*
5317 if (rhsType->isIntegerType()) {
5318 Kind = CK_IntegralToPointer; // FIXME: null?
5319 return IntToPointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005320 }
John McCallb6cfa242011-01-31 22:28:28 +00005321
5322 // C pointers are not compatible with ObjC object pointers,
5323 // with two exceptions:
5324 if (isa<ObjCObjectPointerType>(rhsType)) {
5325 // - conversions to void*
5326 if (lhsPointer->getPointeeType()->isVoidType()) {
5327 Kind = CK_AnyPointerToObjCPointerCast;
5328 return Compatible;
5329 }
5330
5331 // - conversions from 'Class' to the redefinition type
5332 if (rhsType->isObjCClassType() &&
5333 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005334 Kind = CK_BitCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005335 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005336 }
Steve Naroffb4406862008-09-29 18:10:17 +00005337
John McCallb6cfa242011-01-31 22:28:28 +00005338 Kind = CK_BitCast;
5339 return IncompatiblePointer;
5340 }
5341
5342 // U^ -> void*
5343 if (rhsType->getAs<BlockPointerType>()) {
5344 if (lhsPointer->getPointeeType()->isVoidType()) {
5345 Kind = CK_BitCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005346 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005347 }
Steve Naroffb4406862008-09-29 18:10:17 +00005348 }
John McCallb6cfa242011-01-31 22:28:28 +00005349
Steve Naroff1c7d0672008-09-04 15:10:53 +00005350 return Incompatible;
5351 }
5352
John McCallb6cfa242011-01-31 22:28:28 +00005353 // Conversions to block pointers.
Steve Naroff1c7d0672008-09-04 15:10:53 +00005354 if (isa<BlockPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005355 // U^ -> T^
5356 if (rhsType->isBlockPointerType()) {
5357 Kind = CK_AnyPointerToBlockPointerCast;
John McCalle4be87e2011-01-31 23:13:11 +00005358 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCallb6cfa242011-01-31 22:28:28 +00005359 }
5360
5361 // int or null -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00005362 if (rhsType->isIntegerType()) {
5363 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedmand8f4f432009-02-25 04:20:42 +00005364 return IntToBlockPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005365 }
5366
John McCallb6cfa242011-01-31 22:28:28 +00005367 // id -> T^
5368 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5369 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroffb4406862008-09-29 18:10:17 +00005370 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005371 }
Steve Naroffb4406862008-09-29 18:10:17 +00005372
John McCallb6cfa242011-01-31 22:28:28 +00005373 // void* -> T^
John McCalldaa8e4e2010-11-15 09:13:47 +00005374 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCallb6cfa242011-01-31 22:28:28 +00005375 if (RHSPT->getPointeeType()->isVoidType()) {
5376 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregor63a94902008-11-27 00:44:28 +00005377 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005378 }
John McCalldaa8e4e2010-11-15 09:13:47 +00005379
Chris Lattnerfc144e22008-01-04 23:18:45 +00005380 return Incompatible;
5381 }
5382
John McCallb6cfa242011-01-31 22:28:28 +00005383 // Conversions to Objective-C pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00005384 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005385 // A* -> B*
5386 if (rhsType->isObjCObjectPointerType()) {
5387 Kind = CK_BitCast;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005388 Sema::AssignConvertType result =
5389 checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
5390 if (getLangOptions().ObjCAutoRefCount &&
5391 result == Compatible &&
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005392 !CheckObjCARCUnavailableWeakConversion(origLhsType, rhsType))
5393 result = IncompatibleObjCWeakRef;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00005394 return result;
John McCallb6cfa242011-01-31 22:28:28 +00005395 }
5396
5397 // int or null -> A*
John McCalldaa8e4e2010-11-15 09:13:47 +00005398 if (rhsType->isIntegerType()) {
5399 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff14108da2009-07-10 23:34:53 +00005400 return IntToPointer;
John McCalldaa8e4e2010-11-15 09:13:47 +00005401 }
5402
John McCallb6cfa242011-01-31 22:28:28 +00005403 // In general, C pointers are not compatible with ObjC object pointers,
5404 // with two exceptions:
Steve Naroff14108da2009-07-10 23:34:53 +00005405 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005406 // - conversions from 'void*'
5407 if (rhsType->isVoidPointerType()) {
5408 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005409 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005410 }
5411
5412 // - conversions to 'Class' from its redefinition type
5413 if (lhsType->isObjCClassType() &&
5414 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
5415 Kind = CK_BitCast;
5416 return Compatible;
5417 }
5418
5419 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005420 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00005421 }
John McCallb6cfa242011-01-31 22:28:28 +00005422
5423 // T^ -> A*
5424 if (rhsType->isBlockPointerType()) {
5425 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00005426 return Compatible;
John McCallb6cfa242011-01-31 22:28:28 +00005427 }
5428
Steve Naroff14108da2009-07-10 23:34:53 +00005429 return Incompatible;
5430 }
John McCallb6cfa242011-01-31 22:28:28 +00005431
5432 // Conversions from pointers that are not covered by the above.
Chris Lattner78eca282008-04-07 06:49:41 +00005433 if (isa<PointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005434 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00005435 if (lhsType == Context.BoolTy) {
5436 Kind = CK_PointerToBoolean;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005437 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005438 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005439
John McCallb6cfa242011-01-31 22:28:28 +00005440 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00005441 if (lhsType->isIntegerType()) {
5442 Kind = CK_PointerToIntegral;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005443 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005444 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005445
Chris Lattnerfc144e22008-01-04 23:18:45 +00005446 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00005447 }
John McCallb6cfa242011-01-31 22:28:28 +00005448
5449 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff14108da2009-07-10 23:34:53 +00005450 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCallb6cfa242011-01-31 22:28:28 +00005451 // T* -> _Bool
John McCalldaa8e4e2010-11-15 09:13:47 +00005452 if (lhsType == Context.BoolTy) {
5453 Kind = CK_PointerToBoolean;
Steve Naroff14108da2009-07-10 23:34:53 +00005454 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005455 }
Steve Naroff14108da2009-07-10 23:34:53 +00005456
John McCallb6cfa242011-01-31 22:28:28 +00005457 // T* -> int
John McCalldaa8e4e2010-11-15 09:13:47 +00005458 if (lhsType->isIntegerType()) {
5459 Kind = CK_PointerToIntegral;
Steve Naroff14108da2009-07-10 23:34:53 +00005460 return PointerToInt;
John McCalldaa8e4e2010-11-15 09:13:47 +00005461 }
5462
Steve Naroff14108da2009-07-10 23:34:53 +00005463 return Incompatible;
5464 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00005465
John McCallb6cfa242011-01-31 22:28:28 +00005466 // struct A -> struct B
Chris Lattnerfc144e22008-01-04 23:18:45 +00005467 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005468 if (Context.typesAreCompatible(lhsType, rhsType)) {
5469 Kind = CK_NoOp;
Reid Spencer5f016e22007-07-11 17:01:13 +00005470 return Compatible;
John McCalldaa8e4e2010-11-15 09:13:47 +00005471 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005472 }
John McCallb6cfa242011-01-31 22:28:28 +00005473
Reid Spencer5f016e22007-07-11 17:01:13 +00005474 return Incompatible;
5475}
5476
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005477/// \brief Constructs a transparent union from an expression that is
5478/// used to initialize the transparent union.
Richard Trieu67e29332011-08-02 04:35:43 +00005479static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5480 ExprResult &EResult, QualType UnionType,
5481 FieldDecl *Field) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005482 // Build an initializer list that designates the appropriate member
5483 // of the transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005484 Expr *E = EResult.take();
Ted Kremenek709210f2010-04-13 23:39:13 +00005485 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenekba7bc552010-02-19 01:50:18 +00005486 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005487 SourceLocation());
5488 Initializer->setType(UnionType);
5489 Initializer->setInitializedFieldInUnion(Field);
5490
5491 // Build a compound literal constructing a value of the transparent
5492 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00005493 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley429bb272011-04-08 18:41:53 +00005494 EResult = S.Owned(
5495 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5496 VK_RValue, Initializer, false));
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005497}
5498
5499Sema::AssignConvertType
Richard Trieu67e29332011-08-02 04:35:43 +00005500Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
5501 ExprResult &rExpr) {
John Wiegley429bb272011-04-08 18:41:53 +00005502 QualType FromType = rExpr.get()->getType();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005503
Mike Stump1eb44332009-09-09 15:08:12 +00005504 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005505 // transparent_union GCC extension.
5506 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005507 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005508 return Incompatible;
5509
5510 // The field to initialize within the transparent union.
5511 RecordDecl *UD = UT->getDecl();
5512 FieldDecl *InitField = 0;
5513 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005514 for (RecordDecl::field_iterator it = UD->field_begin(),
5515 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005516 it != itend; ++it) {
5517 if (it->getType()->isPointerType()) {
5518 // If the transparent union contains a pointer type, we allow:
5519 // 1) void pointer
5520 // 2) null pointer constant
5521 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00005522 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005523 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005524 InitField = *it;
5525 break;
5526 }
Mike Stump1eb44332009-09-09 15:08:12 +00005527
John Wiegley429bb272011-04-08 18:41:53 +00005528 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005529 Expr::NPC_ValueDependentIsNull)) {
Richard Trieu67e29332011-08-02 04:35:43 +00005530 rExpr = ImpCastExprToType(rExpr.take(), it->getType(),
5531 CK_NullToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005532 InitField = *it;
5533 break;
5534 }
5535 }
5536
John McCalldaa8e4e2010-11-15 09:13:47 +00005537 CastKind Kind = CK_Invalid;
John Wiegley429bb272011-04-08 18:41:53 +00005538 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005539 == Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +00005540 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005541 InitField = *it;
5542 break;
5543 }
5544 }
5545
5546 if (!InitField)
5547 return Incompatible;
5548
John Wiegley429bb272011-04-08 18:41:53 +00005549 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00005550 return Compatible;
5551}
5552
Chris Lattner5cf216b2008-01-04 18:04:52 +00005553Sema::AssignConvertType
John Wiegley429bb272011-04-08 18:41:53 +00005554Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00005555 if (getLangOptions().CPlusPlus) {
5556 if (!lhsType->isRecordType()) {
5557 // C++ 5.17p3: If the left operand is not of class type, the
5558 // expression is implicitly converted (C++ 4) to the
5559 // cv-unqualified type of the left operand.
John Wiegley429bb272011-04-08 18:41:53 +00005560 ExprResult Res = PerformImplicitConversion(rExpr.get(),
5561 lhsType.getUnqualifiedType(),
5562 AA_Assigning);
5563 if (Res.isInvalid())
Douglas Gregor98cd5992008-10-21 23:43:52 +00005564 return Incompatible;
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005565 Sema::AssignConvertType result = Compatible;
5566 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieu67e29332011-08-02 04:35:43 +00005567 !CheckObjCARCUnavailableWeakConversion(lhsType,
5568 rExpr.get()->getType()))
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005569 result = IncompatibleObjCWeakRef;
John Wiegley429bb272011-04-08 18:41:53 +00005570 rExpr = move(Res);
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00005571 return result;
Douglas Gregor98cd5992008-10-21 23:43:52 +00005572 }
5573
5574 // FIXME: Currently, we fall through and treat C++ classes like C
5575 // structures.
John McCallf6a16482010-12-04 03:47:34 +00005576 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00005577
Steve Naroff529a4ad2007-11-27 17:58:44 +00005578 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5579 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00005580 if ((lhsType->isPointerType() ||
5581 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00005582 lhsType->isBlockPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00005583 && rExpr.get()->isNullPointerConstant(Context,
Richard Trieu67e29332011-08-02 04:35:43 +00005584 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00005585 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff529a4ad2007-11-27 17:58:44 +00005586 return Compatible;
5587 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005588
Chris Lattner943140e2007-10-16 02:55:40 +00005589 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00005590 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00005591 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyc133e9e2010-08-05 06:27:49 +00005592 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00005593 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00005594 // Suppress this for references: C++ 8.5.3p5.
John Wiegley429bb272011-04-08 18:41:53 +00005595 if (!lhsType->isReferenceType()) {
5596 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
5597 if (rExpr.isInvalid())
5598 return Incompatible;
5599 }
Steve Narofff1120de2007-08-24 22:33:52 +00005600
John McCalldaa8e4e2010-11-15 09:13:47 +00005601 CastKind Kind = CK_Invalid;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005602 Sema::AssignConvertType result =
John McCall1c23e912010-11-16 02:32:08 +00005603 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005604
Steve Narofff1120de2007-08-24 22:33:52 +00005605 // C99 6.5.16.1p2: The value of the right operand is converted to the
5606 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00005607 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5608 // so that we can use references in built-in functions even in C.
5609 // The getNonReferenceType() call makes sure that the resulting expression
5610 // does not have reference type.
John Wiegley429bb272011-04-08 18:41:53 +00005611 if (result != Incompatible && rExpr.get()->getType() != lhsType)
Richard Trieu67e29332011-08-02 04:35:43 +00005612 rExpr = ImpCastExprToType(rExpr.take(),
5613 lhsType.getNonLValueExprType(Context), Kind);
Steve Narofff1120de2007-08-24 22:33:52 +00005614 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00005615}
5616
Richard Trieu67e29332011-08-02 04:35:43 +00005617QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex,
5618 ExprResult &rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005619 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley429bb272011-04-08 18:41:53 +00005620 << lex.get()->getType() << rex.get()->getType()
5621 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00005622 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005623}
5624
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005625QualType Sema::CheckVectorOperands(ExprResult &lex, ExprResult &rex,
5626 SourceLocation Loc, bool isCompAssign) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00005627 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005628 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00005629 QualType lhsType =
John Wiegley429bb272011-04-08 18:41:53 +00005630 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattnerb77792e2008-07-26 22:17:49 +00005631 QualType rhsType =
John Wiegley429bb272011-04-08 18:41:53 +00005632 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005633
Nate Begemanbe2341d2008-07-14 18:02:46 +00005634 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00005635 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00005636 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00005637
Douglas Gregor255210e2010-08-06 10:14:59 +00005638 // Handle the case of equivalent AltiVec and GCC vector types
5639 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5640 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005641 if (lhsType->isExtVectorType()) {
5642 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5643 return lhsType;
5644 }
5645
5646 if (!isCompAssign)
5647 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor255210e2010-08-06 10:14:59 +00005648 return rhsType;
5649 }
5650
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005651 if (getLangOptions().LaxVectorConversions &&
5652 Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) {
5653 // If we are allowing lax vector conversions, and LHS and RHS are both
5654 // vectors, the total size only needs to be the same. This is a
5655 // bitcast; no bits are changed but the result type is different.
5656 // FIXME: Should we really be allowing this?
5657 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5658 return lhsType;
5659 }
5660
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005661 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5662 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5663 bool swapped = false;
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005664 if (rhsType->isExtVectorType() && !isCompAssign) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005665 swapped = true;
5666 std::swap(rex, lex);
5667 std::swap(rhsType, lhsType);
5668 }
Mike Stump1eb44332009-09-09 15:08:12 +00005669
Nate Begemandde25982009-06-28 19:12:57 +00005670 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00005671 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005672 QualType EltTy = LV->getElementType();
Douglas Gregor9d3347a2010-06-16 00:35:25 +00005673 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005674 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5675 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00005676 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005677 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00005678 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005679 if (swapped) std::swap(rex, lex);
5680 return lhsType;
5681 }
5682 }
5683 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5684 rhsType->isRealFloatingType()) {
John McCalldaa8e4e2010-11-15 09:13:47 +00005685 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5686 if (order > 0)
John Wiegley429bb272011-04-08 18:41:53 +00005687 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCalldaa8e4e2010-11-15 09:13:47 +00005688 if (order >= 0) {
John Wiegley429bb272011-04-08 18:41:53 +00005689 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005690 if (swapped) std::swap(rex, lex);
5691 return lhsType;
5692 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00005693 }
5694 }
Mike Stump1eb44332009-09-09 15:08:12 +00005695
Nate Begemandde25982009-06-28 19:12:57 +00005696 // Vectors of different size or scalar and non-ext-vector are errors.
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005697 if (swapped) std::swap(rex, lex);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005698 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley429bb272011-04-08 18:41:53 +00005699 << lex.get()->getType() << rex.get()->getType()
5700 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005701 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00005702}
5703
Richard Trieu67e29332011-08-02 04:35:43 +00005704QualType Sema::CheckMultiplyDivideOperands(ExprResult &lex, ExprResult &rex,
5705 SourceLocation Loc,
5706 bool isCompAssign, bool isDiv) {
5707 if (lex.get()->getType()->isVectorType() ||
5708 rex.get()->getType()->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005709 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005710
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005711 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00005712 if (lex.isInvalid() || rex.isInvalid())
5713 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005714
John Wiegley429bb272011-04-08 18:41:53 +00005715 if (!lex.get()->getType()->isArithmeticType() ||
5716 !rex.get()->getType()->isArithmeticType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00005717 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005718
Chris Lattner7ef655a2010-01-12 21:23:57 +00005719 // Check for division by zero.
5720 if (isDiv &&
Richard Trieu67e29332011-08-02 04:35:43 +00005721 rex.get()->isNullPointerConstant(Context,
5722 Expr::NPC_ValueDependentIsNotNull))
John Wiegley429bb272011-04-08 18:41:53 +00005723 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
Richard Trieu67e29332011-08-02 04:35:43 +00005724 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005725
Chris Lattner7ef655a2010-01-12 21:23:57 +00005726 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005727}
5728
Chris Lattner7ef655a2010-01-12 21:23:57 +00005729QualType Sema::CheckRemainderOperands(
John Wiegley429bb272011-04-08 18:41:53 +00005730 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
Richard Trieu67e29332011-08-02 04:35:43 +00005731 if (lex.get()->getType()->isVectorType() ||
5732 rex.get()->getType()->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00005733 if (lex.get()->getType()->hasIntegerRepresentation() &&
5734 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005735 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Daniel Dunbar523aa602009-01-05 22:55:36 +00005736 return InvalidOperands(Loc, lex, rex);
5737 }
Steve Naroff90045e82007-07-13 23:32:42 +00005738
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005739 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00005740 if (lex.isInvalid() || rex.isInvalid())
5741 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005742
Richard Trieu67e29332011-08-02 04:35:43 +00005743 if (!lex.get()->getType()->isIntegerType() ||
5744 !rex.get()->getType()->isIntegerType())
Chris Lattner7ef655a2010-01-12 21:23:57 +00005745 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005746
Chris Lattner7ef655a2010-01-12 21:23:57 +00005747 // Check for remainder by zero.
Richard Trieu67e29332011-08-02 04:35:43 +00005748 if (rex.get()->isNullPointerConstant(Context,
5749 Expr::NPC_ValueDependentIsNotNull))
John Wiegley429bb272011-04-08 18:41:53 +00005750 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
5751 << rex.get()->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005752
Chris Lattner7ef655a2010-01-12 21:23:57 +00005753 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005754}
5755
Chandler Carruth13b21be2011-06-27 08:02:19 +00005756/// \brief Diagnose invalid arithmetic on two void pointers.
5757static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
5758 Expr *LHS, Expr *RHS) {
5759 S.Diag(Loc, S.getLangOptions().CPlusPlus
5760 ? diag::err_typecheck_pointer_arith_void_type
5761 : diag::ext_gnu_void_ptr)
5762 << 1 /* two pointers */ << LHS->getSourceRange() << RHS->getSourceRange();
5763}
5764
5765/// \brief Diagnose invalid arithmetic on a void pointer.
5766static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5767 Expr *Pointer) {
5768 S.Diag(Loc, S.getLangOptions().CPlusPlus
5769 ? diag::err_typecheck_pointer_arith_void_type
5770 : diag::ext_gnu_void_ptr)
5771 << 0 /* one pointer */ << Pointer->getSourceRange();
5772}
5773
5774/// \brief Diagnose invalid arithmetic on two function pointers.
5775static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5776 Expr *LHS, Expr *RHS) {
5777 assert(LHS->getType()->isAnyPointerType());
5778 assert(RHS->getType()->isAnyPointerType());
5779 S.Diag(Loc, S.getLangOptions().CPlusPlus
5780 ? diag::err_typecheck_pointer_arith_function_type
5781 : diag::ext_gnu_ptr_func_arith)
5782 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5783 // We only show the second type if it differs from the first.
5784 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5785 RHS->getType())
5786 << RHS->getType()->getPointeeType()
5787 << LHS->getSourceRange() << RHS->getSourceRange();
5788}
5789
5790/// \brief Diagnose invalid arithmetic on a function pointer.
5791static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5792 Expr *Pointer) {
5793 assert(Pointer->getType()->isAnyPointerType());
5794 S.Diag(Loc, S.getLangOptions().CPlusPlus
5795 ? diag::err_typecheck_pointer_arith_function_type
5796 : diag::ext_gnu_ptr_func_arith)
5797 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5798 << 0 /* one pointer, so only one type */
5799 << Pointer->getSourceRange();
5800}
5801
5802/// \brief Check the validity of an arithmetic pointer operand.
5803///
5804/// If the operand has pointer type, this code will check for pointer types
5805/// which are invalid in arithmetic operations. These will be diagnosed
5806/// appropriately, including whether or not the use is supported as an
5807/// extension.
5808///
5809/// \returns True when the operand is valid to use (even if as an extension).
5810static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5811 Expr *Operand) {
5812 if (!Operand->getType()->isAnyPointerType()) return true;
5813
5814 QualType PointeeTy = Operand->getType()->getPointeeType();
5815 if (PointeeTy->isVoidType()) {
5816 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5817 return !S.getLangOptions().CPlusPlus;
5818 }
5819 if (PointeeTy->isFunctionType()) {
5820 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5821 return !S.getLangOptions().CPlusPlus;
5822 }
5823
5824 if ((Operand->getType()->isPointerType() &&
5825 !Operand->getType()->isDependentType()) ||
5826 Operand->getType()->isObjCObjectPointerType()) {
5827 QualType PointeeTy = Operand->getType()->getPointeeType();
5828 if (S.RequireCompleteType(
5829 Loc, PointeeTy,
5830 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5831 << PointeeTy << Operand->getSourceRange()))
5832 return false;
5833 }
5834
5835 return true;
5836}
5837
5838/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5839/// operands.
5840///
5841/// This routine will diagnose any invalid arithmetic on pointer operands much
5842/// like \see checkArithmeticOpPointerOperand. However, it has special logic
5843/// for emitting a single diagnostic even for operations where both LHS and RHS
5844/// are (potentially problematic) pointers.
5845///
5846/// \returns True when the operand is valid to use (even if as an extension).
5847static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
5848 Expr *LHS, Expr *RHS) {
5849 bool isLHSPointer = LHS->getType()->isAnyPointerType();
5850 bool isRHSPointer = RHS->getType()->isAnyPointerType();
5851 if (!isLHSPointer && !isRHSPointer) return true;
5852
5853 QualType LHSPointeeTy, RHSPointeeTy;
5854 if (isLHSPointer) LHSPointeeTy = LHS->getType()->getPointeeType();
5855 if (isRHSPointer) RHSPointeeTy = RHS->getType()->getPointeeType();
5856
5857 // Check for arithmetic on pointers to incomplete types.
5858 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
5859 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
5860 if (isLHSVoidPtr || isRHSVoidPtr) {
5861 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHS);
5862 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHS);
5863 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHS, RHS);
5864
5865 return !S.getLangOptions().CPlusPlus;
5866 }
5867
5868 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
5869 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
5870 if (isLHSFuncPtr || isRHSFuncPtr) {
5871 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHS);
5872 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, RHS);
5873 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS, RHS);
5874
5875 return !S.getLangOptions().CPlusPlus;
5876 }
5877
5878 Expr *Operands[] = { LHS, RHS };
5879 for (unsigned i = 0; i < 2; ++i) {
5880 Expr *Operand = Operands[i];
5881 if ((Operand->getType()->isPointerType() &&
5882 !Operand->getType()->isDependentType()) ||
5883 Operand->getType()->isObjCObjectPointerType()) {
5884 QualType PointeeTy = Operand->getType()->getPointeeType();
5885 if (S.RequireCompleteType(
5886 Loc, PointeeTy,
5887 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5888 << PointeeTy << Operand->getSourceRange()))
5889 return false;
5890 }
5891 }
5892 return true;
5893}
5894
Chris Lattner7ef655a2010-01-12 21:23:57 +00005895QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00005896 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
Richard Trieu67e29332011-08-02 04:35:43 +00005897 if (lex.get()->getType()->isVectorType() ||
5898 rex.get()->getType()->isVectorType()) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005899 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00005900 if (CompLHSTy) *CompLHSTy = compType;
5901 return compType;
5902 }
Steve Naroff49b45262007-07-13 16:58:59 +00005903
Eli Friedmanab3a8522009-03-28 01:22:36 +00005904 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00005905 if (lex.isInvalid() || rex.isInvalid())
5906 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00005907
Reid Spencer5f016e22007-07-11 17:01:13 +00005908 // handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00005909 if (lex.get()->getType()->isArithmeticType() &&
5910 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005911 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005912 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005913 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005914
Eli Friedmand72d16e2008-05-18 18:08:51 +00005915 // Put any potential pointer into PExp
John Wiegley429bb272011-04-08 18:41:53 +00005916 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005917 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00005918 std::swap(PExp, IExp);
5919
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005920 if (PExp->getType()->isAnyPointerType()) {
Eli Friedmand72d16e2008-05-18 18:08:51 +00005921 if (IExp->getType()->isIntegerType()) {
Chandler Carruth13b21be2011-06-27 08:02:19 +00005922 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
5923 return QualType();
5924
Steve Naroff760e3c42009-07-13 21:20:41 +00005925 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005926
Chris Lattnerb5f15622009-04-24 23:50:08 +00005927 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00005928 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00005929 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5930 << PointeeTy << PExp->getSourceRange();
5931 return QualType();
5932 }
Mike Stump1eb44332009-09-09 15:08:12 +00005933
Eli Friedmanab3a8522009-03-28 01:22:36 +00005934 if (CompLHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00005935 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman04e83572009-08-20 04:21:42 +00005936 if (LHSTy.isNull()) {
John Wiegley429bb272011-04-08 18:41:53 +00005937 LHSTy = lex.get()->getType();
Eli Friedman04e83572009-08-20 04:21:42 +00005938 if (LHSTy->isPromotableIntegerType())
5939 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005940 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00005941 *CompLHSTy = LHSTy;
5942 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00005943 return PExp->getType();
5944 }
5945 }
5946
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005947 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005948}
5949
Chris Lattnereca7be62008-04-07 05:30:13 +00005950// C99 6.5.6
John Wiegley429bb272011-04-08 18:41:53 +00005951QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Richard Trieu67e29332011-08-02 04:35:43 +00005952 SourceLocation Loc,
5953 QualType* CompLHSTy) {
5954 if (lex.get()->getType()->isVectorType() ||
5955 rex.get()->getType()->isVectorType()) {
Eli Friedmanb9b4b782011-06-23 18:10:35 +00005956 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00005957 if (CompLHSTy) *CompLHSTy = compType;
5958 return compType;
5959 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005960
Eli Friedmanab3a8522009-03-28 01:22:36 +00005961 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00005962 if (lex.isInvalid() || rex.isInvalid())
5963 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005964
Chris Lattner6e4ab612007-12-09 21:53:25 +00005965 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005966
Chris Lattner6e4ab612007-12-09 21:53:25 +00005967 // Handle the common case first (both operands are arithmetic).
John Wiegley429bb272011-04-08 18:41:53 +00005968 if (lex.get()->getType()->isArithmeticType() &&
5969 rex.get()->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005970 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005971 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005972 }
Mike Stump1eb44332009-09-09 15:08:12 +00005973
Chris Lattner6e4ab612007-12-09 21:53:25 +00005974 // Either ptr - int or ptr - ptr.
John Wiegley429bb272011-04-08 18:41:53 +00005975 if (lex.get()->getType()->isAnyPointerType()) {
5976 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005977
Chris Lattnerb5f15622009-04-24 23:50:08 +00005978 // Diagnose bad cases where we step over interface counts.
John McCallc12c5bb2010-05-15 11:32:37 +00005979 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattnerb5f15622009-04-24 23:50:08 +00005980 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley429bb272011-04-08 18:41:53 +00005981 << lpointee << lex.get()->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00005982 return QualType();
5983 }
Mike Stump1eb44332009-09-09 15:08:12 +00005984
Chris Lattner6e4ab612007-12-09 21:53:25 +00005985 // The result type of a pointer-int computation is the pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00005986 if (rex.get()->getType()->isIntegerType()) {
Chandler Carruth13b21be2011-06-27 08:02:19 +00005987 if (!checkArithmeticOpPointerOperand(*this, Loc, lex.get()))
5988 return QualType();
Douglas Gregore7450f52009-03-24 19:52:54 +00005989
John Wiegley429bb272011-04-08 18:41:53 +00005990 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
5991 return lex.get()->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00005992 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005993
Chris Lattner6e4ab612007-12-09 21:53:25 +00005994 // Handle pointer-pointer subtractions.
Richard Trieu67e29332011-08-02 04:35:43 +00005995 if (const PointerType *RHSPTy
5996 = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00005997 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005998
Eli Friedman88d936b2009-05-16 13:54:38 +00005999 if (getLangOptions().CPlusPlus) {
6000 // Pointee types must be the same: C++ [expr.add]
6001 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6002 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley429bb272011-04-08 18:41:53 +00006003 << lex.get()->getType() << rex.get()->getType()
6004 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman88d936b2009-05-16 13:54:38 +00006005 return QualType();
6006 }
6007 } else {
6008 // Pointee types must be compatible C99 6.5.6p3
6009 if (!Context.typesAreCompatible(
6010 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6011 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6012 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley429bb272011-04-08 18:41:53 +00006013 << lex.get()->getType() << rex.get()->getType()
6014 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman88d936b2009-05-16 13:54:38 +00006015 return QualType();
6016 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00006017 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006018
Chandler Carruth13b21be2011-06-27 08:02:19 +00006019 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
6020 lex.get(), rex.get()))
6021 return QualType();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006022
John Wiegley429bb272011-04-08 18:41:53 +00006023 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00006024 return Context.getPointerDiffType();
6025 }
6026 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006027
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006028 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006029}
6030
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006031static bool isScopedEnumerationType(QualType T) {
6032 if (const EnumType *ET = dyn_cast<EnumType>(T))
6033 return ET->getDecl()->isScoped();
6034 return false;
6035}
6036
John Wiegley429bb272011-04-08 18:41:53 +00006037static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth21206d52011-02-23 23:34:11 +00006038 SourceLocation Loc, unsigned Opc,
6039 QualType LHSTy) {
6040 llvm::APSInt Right;
6041 // Check right/shifter operand
Richard Trieu67e29332011-08-02 04:35:43 +00006042 if (rex.get()->isValueDependent() ||
6043 !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth21206d52011-02-23 23:34:11 +00006044 return;
6045
6046 if (Right.isNegative()) {
John Wiegley429bb272011-04-08 18:41:53 +00006047 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek082bf7a2011-03-01 18:09:31 +00006048 S.PDiag(diag::warn_shift_negative)
John Wiegley429bb272011-04-08 18:41:53 +00006049 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006050 return;
6051 }
6052 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley429bb272011-04-08 18:41:53 +00006053 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth21206d52011-02-23 23:34:11 +00006054 if (Right.uge(LeftBits)) {
John Wiegley429bb272011-04-08 18:41:53 +00006055 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek425a31e2011-03-01 19:13:22 +00006056 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley429bb272011-04-08 18:41:53 +00006057 << rex.get()->getSourceRange());
Chandler Carruth21206d52011-02-23 23:34:11 +00006058 return;
6059 }
6060 if (Opc != BO_Shl)
6061 return;
6062
6063 // When left shifting an ICE which is signed, we can check for overflow which
6064 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6065 // integers have defined behavior modulo one more than the maximum value
6066 // representable in the result type, so never warn for those.
6067 llvm::APSInt Left;
Richard Trieu67e29332011-08-02 04:35:43 +00006068 if (lex.get()->isValueDependent() ||
6069 !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth21206d52011-02-23 23:34:11 +00006070 LHSTy->hasUnsignedIntegerRepresentation())
6071 return;
6072 llvm::APInt ResultBits =
6073 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6074 if (LeftBits.uge(ResultBits))
6075 return;
6076 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6077 Result = Result.shl(Right);
6078
Ted Kremenekfa821382011-06-15 00:54:52 +00006079 // Print the bit representation of the signed integer as an unsigned
6080 // hexadecimal number.
6081 llvm::SmallString<40> HexResult;
6082 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6083
Chandler Carruth21206d52011-02-23 23:34:11 +00006084 // If we are only missing a sign bit, this is less likely to result in actual
6085 // bugs -- if the result is cast back to an unsigned type, it will have the
6086 // expected value. Thus we place this behind a different warning that can be
6087 // turned off separately if needed.
6088 if (LeftBits == ResultBits - 1) {
Ted Kremenekfa821382011-06-15 00:54:52 +00006089 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6090 << HexResult.str() << LHSTy
John Wiegley429bb272011-04-08 18:41:53 +00006091 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006092 return;
6093 }
6094
6095 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Ted Kremenekfa821382011-06-15 00:54:52 +00006096 << HexResult.str() << Result.getMinSignedBits() << LHSTy
Richard Trieu67e29332011-08-02 04:35:43 +00006097 << Left.getBitWidth() << lex.get()->getSourceRange()
6098 << rex.get()->getSourceRange();
Chandler Carruth21206d52011-02-23 23:34:11 +00006099}
6100
Chris Lattnereca7be62008-04-07 05:30:13 +00006101// C99 6.5.7
Richard Trieu67e29332011-08-02 04:35:43 +00006102QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex,
6103 SourceLocation Loc, unsigned Opc,
6104 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00006105 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley429bb272011-04-08 18:41:53 +00006106 if (!lex.get()->getType()->hasIntegerRepresentation() ||
6107 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006108 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006109
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006110 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6111 // hasIntegerRepresentation() above instead of this.
John Wiegley429bb272011-04-08 18:41:53 +00006112 if (isScopedEnumerationType(lex.get()->getType()) ||
6113 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006114 return InvalidOperands(Loc, lex, rex);
6115 }
6116
Nate Begeman2207d792009-10-25 02:26:48 +00006117 // Vector shifts promote their scalar inputs to vector type.
Richard Trieu67e29332011-08-02 04:35:43 +00006118 if (lex.get()->getType()->isVectorType() ||
6119 rex.get()->getType()->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006120 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Nate Begeman2207d792009-10-25 02:26:48 +00006121
Chris Lattnerca5eede2007-12-12 05:47:28 +00006122 // Shifts don't perform usual arithmetic conversions, they just do integer
6123 // promotions on each operand. C99 6.5.7p3
Eli Friedmanab3a8522009-03-28 01:22:36 +00006124
John McCall1bc80af2010-12-16 19:28:59 +00006125 // For the LHS, do usual unary conversions, but then reset them away
6126 // if this is a compound assignment.
John Wiegley429bb272011-04-08 18:41:53 +00006127 ExprResult old_lex = lex;
6128 lex = UsualUnaryConversions(lex.take());
6129 if (lex.isInvalid())
6130 return QualType();
6131 QualType LHSTy = lex.get()->getType();
John McCall1bc80af2010-12-16 19:28:59 +00006132 if (isCompAssign) lex = old_lex;
6133
6134 // The RHS is simpler.
John Wiegley429bb272011-04-08 18:41:53 +00006135 rex = UsualUnaryConversions(rex.take());
6136 if (rex.isInvalid())
6137 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006138
Ryan Flynnd0439682009-08-07 16:20:20 +00006139 // Sanity-check shift operands
Chandler Carruth21206d52011-02-23 23:34:11 +00006140 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnd0439682009-08-07 16:20:20 +00006141
Chris Lattnerca5eede2007-12-12 05:47:28 +00006142 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00006143 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006144}
6145
Chandler Carruth99919472010-07-10 12:30:03 +00006146static bool IsWithinTemplateSpecialization(Decl *D) {
6147 if (DeclContext *DC = D->getDeclContext()) {
6148 if (isa<ClassTemplateSpecializationDecl>(DC))
6149 return true;
6150 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6151 return FD->isFunctionTemplateSpecialization();
6152 }
6153 return false;
6154}
6155
Douglas Gregor0c6db942009-05-04 06:07:12 +00006156// C99 6.5.8, C++ [expr.rel]
Richard Trieu67e29332011-08-02 04:35:43 +00006157QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex,
6158 SourceLocation Loc, unsigned OpaqueOpc,
6159 bool isRelational) {
John McCall2de56d12010-08-25 11:45:40 +00006160 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregora86b8322009-04-06 18:45:53 +00006161
Chris Lattner02dd4b12009-12-05 05:40:13 +00006162 // Handle vector comparisons separately.
Richard Trieu67e29332011-08-02 04:35:43 +00006163 if (lex.get()->getType()->isVectorType() ||
6164 rex.get()->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006165 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006166
John Wiegley429bb272011-04-08 18:41:53 +00006167 QualType lType = lex.get()->getType();
6168 QualType rType = rex.get()->getType();
Douglas Gregorfadb53b2011-03-12 01:48:56 +00006169
John Wiegley429bb272011-04-08 18:41:53 +00006170 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
6171 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth543cb652011-02-17 08:37:06 +00006172 QualType LHSStrippedType = LHSStripped->getType();
6173 QualType RHSStrippedType = RHSStripped->getType();
6174
Douglas Gregorfadb53b2011-03-12 01:48:56 +00006175
6176
Chandler Carruth543cb652011-02-17 08:37:06 +00006177 // Two different enums will raise a warning when compared.
6178 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
6179 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
6180 if (LHSEnumType->getDecl()->getIdentifier() &&
6181 RHSEnumType->getDecl()->getIdentifier() &&
6182 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
6183 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6184 << LHSStrippedType << RHSStrippedType
John Wiegley429bb272011-04-08 18:41:53 +00006185 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth543cb652011-02-17 08:37:06 +00006186 }
6187 }
6188 }
6189
Douglas Gregor8eee1192010-06-22 22:12:46 +00006190 if (!lType->hasFloatingRepresentation() &&
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006191 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley429bb272011-04-08 18:41:53 +00006192 !lex.get()->getLocStart().isMacroID() &&
6193 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner55660a72009-03-08 19:39:53 +00006194 // For non-floating point types, check for self-comparisons of the form
6195 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6196 // often indicate logic errors in the program.
Chandler Carruth64d092c2010-07-12 06:23:38 +00006197 //
6198 // NOTE: Don't warn about comparison expressions resulting from macro
6199 // expansion. Also don't warn about comparisons which are only self
6200 // comparisons within a template specialization. The warnings should catch
6201 // obvious cases in the definition of the template anyways. The idea is to
6202 // warn when the typed comparison operator will always evaluate to the same
6203 // result.
Chandler Carruth99919472010-07-10 12:30:03 +00006204 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006205 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenekfbcb0eb2010-09-16 00:03:01 +00006206 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth99919472010-07-10 12:30:03 +00006207 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek351ba912011-02-23 01:52:04 +00006208 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006209 << 0 // self-
John McCall2de56d12010-08-25 11:45:40 +00006210 << (Opc == BO_EQ
6211 || Opc == BO_LE
6212 || Opc == BO_GE));
Douglas Gregord64fdd02010-06-08 19:50:34 +00006213 } else if (lType->isArrayType() && rType->isArrayType() &&
6214 !DRL->getDecl()->getType()->isReferenceType() &&
6215 !DRR->getDecl()->getType()->isReferenceType()) {
6216 // what is it always going to eval to?
6217 char always_evals_to;
6218 switch(Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006219 case BO_EQ: // e.g. array1 == array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006220 always_evals_to = 0; // false
6221 break;
John McCall2de56d12010-08-25 11:45:40 +00006222 case BO_NE: // e.g. array1 != array2
Douglas Gregord64fdd02010-06-08 19:50:34 +00006223 always_evals_to = 1; // true
6224 break;
6225 default:
6226 // best we can say is 'a constant'
6227 always_evals_to = 2; // e.g. array1 <= array2
6228 break;
6229 }
Ted Kremenek351ba912011-02-23 01:52:04 +00006230 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregord64fdd02010-06-08 19:50:34 +00006231 << 1 // array
6232 << always_evals_to);
6233 }
6234 }
Chandler Carruth99919472010-07-10 12:30:03 +00006235 }
Mike Stump1eb44332009-09-09 15:08:12 +00006236
Chris Lattner55660a72009-03-08 19:39:53 +00006237 if (isa<CastExpr>(LHSStripped))
6238 LHSStripped = LHSStripped->IgnoreParenCasts();
6239 if (isa<CastExpr>(RHSStripped))
6240 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00006241
Chris Lattner55660a72009-03-08 19:39:53 +00006242 // Warn about comparisons against a string constant (unless the other
6243 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00006244 Expr *literalString = 0;
6245 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00006246 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006247 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006248 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00006249 literalString = lex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006250 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006251 } else if ((isa<StringLiteral>(RHSStripped) ||
6252 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006253 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006254 Expr::NPC_ValueDependentIsNull)) {
John Wiegley429bb272011-04-08 18:41:53 +00006255 literalString = rex.get();
Douglas Gregora86b8322009-04-06 18:45:53 +00006256 literalStringStripped = RHSStripped;
6257 }
6258
6259 if (literalString) {
6260 std::string resultComparison;
6261 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00006262 case BO_LT: resultComparison = ") < 0"; break;
6263 case BO_GT: resultComparison = ") > 0"; break;
6264 case BO_LE: resultComparison = ") <= 0"; break;
6265 case BO_GE: resultComparison = ") >= 0"; break;
6266 case BO_EQ: resultComparison = ") == 0"; break;
6267 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregora86b8322009-04-06 18:45:53 +00006268 default: assert(false && "Invalid comparison operator");
6269 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006270
Ted Kremenek351ba912011-02-23 01:52:04 +00006271 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00006272 PDiag(diag::warn_stringcompare)
6273 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek03a4bee2010-04-09 20:26:53 +00006274 << literalString->getSourceRange());
Douglas Gregora86b8322009-04-06 18:45:53 +00006275 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00006276 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006277
Douglas Gregord64fdd02010-06-08 19:50:34 +00006278 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieu67e29332011-08-02 04:35:43 +00006279 if (lex.get()->getType()->isArithmeticType() &&
6280 rex.get()->getType()->isArithmeticType()) {
Douglas Gregord64fdd02010-06-08 19:50:34 +00006281 UsualArithmeticConversions(lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00006282 if (lex.isInvalid() || rex.isInvalid())
6283 return QualType();
6284 }
Douglas Gregord64fdd02010-06-08 19:50:34 +00006285 else {
John Wiegley429bb272011-04-08 18:41:53 +00006286 lex = UsualUnaryConversions(lex.take());
6287 if (lex.isInvalid())
6288 return QualType();
6289
6290 rex = UsualUnaryConversions(rex.take());
6291 if (rex.isInvalid())
6292 return QualType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006293 }
6294
John Wiegley429bb272011-04-08 18:41:53 +00006295 lType = lex.get()->getType();
6296 rType = rex.get()->getType();
Douglas Gregord64fdd02010-06-08 19:50:34 +00006297
Douglas Gregor447b69e2008-11-19 03:25:36 +00006298 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00006299 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregor447b69e2008-11-19 03:25:36 +00006300
Chris Lattnera5937dd2007-08-26 01:18:55 +00006301 if (isRelational) {
6302 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006303 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006304 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00006305 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006306 if (lType->hasFloatingRepresentation())
John Wiegley429bb272011-04-08 18:41:53 +00006307 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006308
Chris Lattnera5937dd2007-08-26 01:18:55 +00006309 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00006310 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00006311 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006312
John Wiegley429bb272011-04-08 18:41:53 +00006313 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006314 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00006315 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00006316 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006317
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006318 // All of the following pointer-related warnings are GCC extensions, except
6319 // when handling null pointer constants.
Steve Naroff77878cc2007-08-27 04:08:11 +00006320 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00006321 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006322 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00006323 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00006324 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006325
Douglas Gregor0c6db942009-05-04 06:07:12 +00006326 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00006327 if (LCanPointeeTy == RCanPointeeTy)
6328 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006329 if (!isRelational &&
6330 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6331 // Valid unless comparison between non-null pointer and function pointer
6332 // This is a gcc extension compatibility comparison.
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006333 // In a SFINAE context, we treat this as a hard error to maintain
6334 // conformance with the C++ standard.
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006335 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6336 && !LHSIsNull && !RHSIsNull) {
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006337 Diag(Loc,
6338 isSFINAEContext()?
6339 diag::err_typecheck_comparison_of_fptr_to_void
6340 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu67e29332011-08-02 04:35:43 +00006341 << lType << rType << lex.get()->getSourceRange()
6342 << rex.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006343
6344 if (isSFINAEContext())
6345 return QualType();
6346
John Wiegley429bb272011-04-08 18:41:53 +00006347 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00006348 return ResultTy;
6349 }
6350 }
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006351
Douglas Gregor0c6db942009-05-04 06:07:12 +00006352 // C++ [expr.rel]p2:
6353 // [...] Pointer conversions (4.10) and qualification
6354 // conversions (4.4) are performed on pointer operands (or on
6355 // a pointer operand and a null pointer constant) to bring
6356 // them to their composite pointer type. [...]
6357 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00006358 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00006359 // comparisons of pointers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006360 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00006361 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006362 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor0c6db942009-05-04 06:07:12 +00006363 if (T.isNull()) {
6364 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00006365 << lType << rType << lex.get()->getSourceRange()
6366 << rex.get()->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00006367 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006368 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006369 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006370 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006371 << lType << rType << T
John Wiegley429bb272011-04-08 18:41:53 +00006372 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00006373 }
6374
John Wiegley429bb272011-04-08 18:41:53 +00006375 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6376 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00006377 return ResultTy;
6378 }
Eli Friedman3075e762009-08-23 00:27:47 +00006379 // C99 6.5.9p2 and C99 6.5.8p2
6380 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6381 RCanPointeeTy.getUnqualifiedType())) {
6382 // Valid unless a relational comparison of function pointers
6383 if (isRelational && LCanPointeeTy->isFunctionType()) {
6384 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00006385 << lType << rType << lex.get()->getSourceRange()
6386 << rex.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00006387 }
6388 } else if (!isRelational &&
6389 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6390 // Valid unless comparison between non-null pointer and function pointer
6391 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6392 && !LHSIsNull && !RHSIsNull) {
6393 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu67e29332011-08-02 04:35:43 +00006394 << lType << rType << lex.get()->getSourceRange()
6395 << rex.get()->getSourceRange();
Eli Friedman3075e762009-08-23 00:27:47 +00006396 }
6397 } else {
6398 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006399 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00006400 << lType << rType << lex.get()->getSourceRange()
6401 << rex.get()->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006402 }
John McCall34d6f932011-03-11 04:25:25 +00006403 if (LCanPointeeTy != RCanPointeeTy) {
6404 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00006405 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006406 else
John Wiegley429bb272011-04-08 18:41:53 +00006407 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006408 }
Douglas Gregor447b69e2008-11-19 03:25:36 +00006409 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00006410 }
Mike Stump1eb44332009-09-09 15:08:12 +00006411
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006412 if (getLangOptions().CPlusPlus) {
Anders Carlsson0c8209e2010-11-04 03:17:43 +00006413 // Comparison of nullptr_t with itself.
6414 if (lType->isNullPtrType() && rType->isNullPtrType())
6415 return ResultTy;
6416
Mike Stump1eb44332009-09-09 15:08:12 +00006417 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00006418 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00006419 if (RHSIsNull &&
Douglas Gregor17e37c72011-06-01 15:12:24 +00006420 ((lType->isAnyPointerType() || lType->isNullPtrType()) ||
Douglas Gregor16cd4b72011-06-16 18:52:05 +00006421 (!isRelational &&
6422 (lType->isMemberPointerType() || lType->isBlockPointerType())))) {
John Wiegley429bb272011-04-08 18:41:53 +00006423 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregor443c2122010-08-07 13:36:37 +00006424 lType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006425 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006426 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006427 return ResultTy;
6428 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006429 if (LHSIsNull &&
Douglas Gregor17e37c72011-06-01 15:12:24 +00006430 ((rType->isAnyPointerType() || rType->isNullPtrType()) ||
Douglas Gregor16cd4b72011-06-16 18:52:05 +00006431 (!isRelational &&
6432 (rType->isMemberPointerType() || rType->isBlockPointerType())))) {
John Wiegley429bb272011-04-08 18:41:53 +00006433 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregor443c2122010-08-07 13:36:37 +00006434 rType->isMemberPointerType()
John McCall2de56d12010-08-25 11:45:40 +00006435 ? CK_NullToMemberPointer
John McCall404cd162010-11-13 01:35:44 +00006436 : CK_NullToPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006437 return ResultTy;
6438 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00006439
6440 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00006441 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00006442 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6443 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00006444 // In addition, pointers to members can be compared, or a pointer to
6445 // member and a null pointer constant. Pointer to member conversions
6446 // (4.11) and qualification conversions (4.4) are performed to bring
6447 // them to a common type. If one operand is a null pointer constant,
6448 // the common type is the type of the other operand. Otherwise, the
6449 // common type is a pointer to member type similar (4.4) to the type
6450 // of one of the operands, with a cv-qualification signature (4.4)
6451 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00006452 // types.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006453 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00006454 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006455 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor20b3e992009-08-24 17:42:35 +00006456 if (T.isNull()) {
6457 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00006458 << lType << rType << lex.get()->getSourceRange()
6459 << rex.get()->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00006460 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006461 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006462 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00006463 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006464 << lType << rType << T
John Wiegley429bb272011-04-08 18:41:53 +00006465 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00006466 }
Mike Stump1eb44332009-09-09 15:08:12 +00006467
John Wiegley429bb272011-04-08 18:41:53 +00006468 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6469 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00006470 return ResultTy;
6471 }
Douglas Gregor90566c02011-03-01 17:16:20 +00006472
6473 // Handle scoped enumeration types specifically, since they don't promote
6474 // to integers.
John Wiegley429bb272011-04-08 18:41:53 +00006475 if (lex.get()->getType()->isEnumeralType() &&
Richard Trieu67e29332011-08-02 04:35:43 +00006476 Context.hasSameUnqualifiedType(lex.get()->getType(),
6477 rex.get()->getType()))
Douglas Gregor90566c02011-03-01 17:16:20 +00006478 return ResultTy;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00006479 }
Mike Stump1eb44332009-09-09 15:08:12 +00006480
Steve Naroff1c7d0672008-09-04 15:10:53 +00006481 // Handle block pointer types.
Richard Trieu67e29332011-08-02 04:35:43 +00006482 if (!isRelational && lType->isBlockPointerType() &&
6483 rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00006484 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6485 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006486
Steve Naroff1c7d0672008-09-04 15:10:53 +00006487 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00006488 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006489 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieu67e29332011-08-02 04:35:43 +00006490 << lType << rType << lex.get()->getSourceRange()
6491 << rex.get()->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00006492 }
John Wiegley429bb272011-04-08 18:41:53 +00006493 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006494 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006495 }
John Wiegley429bb272011-04-08 18:41:53 +00006496
Steve Naroff59f53942008-09-28 01:11:11 +00006497 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00006498 if (!isRelational
6499 && ((lType->isBlockPointerType() && rType->isPointerType())
6500 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00006501 if (!LHSIsNull && !RHSIsNull) {
John McCall34d6f932011-03-11 04:25:25 +00006502 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006503 ->getPointeeType()->isVoidType())
John McCall34d6f932011-03-11 04:25:25 +00006504 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00006505 ->getPointeeType()->isVoidType())))
6506 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieu67e29332011-08-02 04:35:43 +00006507 << lType << rType << lex.get()->getSourceRange()
6508 << rex.get()->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00006509 }
John McCall34d6f932011-03-11 04:25:25 +00006510 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00006511 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006512 else
John Wiegley429bb272011-04-08 18:41:53 +00006513 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006514 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00006515 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00006516
John McCall34d6f932011-03-11 04:25:25 +00006517 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
6518 const PointerType *LPT = lType->getAs<PointerType>();
6519 const PointerType *RPT = rType->getAs<PointerType>();
6520 if (LPT || RPT) {
6521 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6522 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006523
Steve Naroffa8069f12008-11-17 19:49:16 +00006524 if (!LPtrToVoid && !RPtrToVoid &&
6525 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00006526 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00006527 << lType << rType << lex.get()->getSourceRange()
6528 << rex.get()->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00006529 }
John McCall34d6f932011-03-11 04:25:25 +00006530 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00006531 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006532 else
John Wiegley429bb272011-04-08 18:41:53 +00006533 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006534 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00006535 }
Steve Naroff14108da2009-07-10 23:34:53 +00006536 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00006537 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00006538 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu67e29332011-08-02 04:35:43 +00006539 << lType << rType << lex.get()->getSourceRange()
6540 << rex.get()->getSourceRange();
John McCall34d6f932011-03-11 04:25:25 +00006541 if (LHSIsNull && !RHSIsNull)
John Wiegley429bb272011-04-08 18:41:53 +00006542 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall34d6f932011-03-11 04:25:25 +00006543 else
John Wiegley429bb272011-04-08 18:41:53 +00006544 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006545 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00006546 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00006547 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006548 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6549 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006550 unsigned DiagID = 0;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006551 bool isError = false;
6552 if ((LHSIsNull && lType->isIntegerType()) ||
6553 (RHSIsNull && rType->isIntegerType())) {
6554 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006555 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006556 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006557 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006558 else if (getLangOptions().CPlusPlus) {
6559 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6560 isError = true;
6561 } else
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006562 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00006563
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006564 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00006565 Diag(Loc, DiagID)
Richard Trieu67e29332011-08-02 04:35:43 +00006566 << lType << rType << lex.get()->getSourceRange()
6567 << rex.get()->getSourceRange();
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006568 if (isError)
6569 return QualType();
Chris Lattner6365e3e2009-08-22 18:58:31 +00006570 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006571
6572 if (lType->isIntegerType())
John Wiegley429bb272011-04-08 18:41:53 +00006573 lex = ImpCastExprToType(lex.take(), rType,
John McCall404cd162010-11-13 01:35:44 +00006574 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattner06c0f5b2009-08-23 00:03:44 +00006575 else
John Wiegley429bb272011-04-08 18:41:53 +00006576 rex = ImpCastExprToType(rex.take(), lType,
John McCall404cd162010-11-13 01:35:44 +00006577 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006578 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006579 }
Douglas Gregor6e5122c2010-06-15 21:38:40 +00006580
Steve Naroff39218df2008-09-04 16:56:14 +00006581 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00006582 if (!isRelational && RHSIsNull
6583 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006584 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006585 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006586 }
Mike Stumpaf199f32009-05-07 18:43:07 +00006587 if (!isRelational && LHSIsNull
6588 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006589 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00006590 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00006591 }
Douglas Gregor90566c02011-03-01 17:16:20 +00006592
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006593 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006594}
6595
Nate Begemanbe2341d2008-07-14 18:02:46 +00006596/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00006597/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00006598/// like a scalar comparison, a vector comparison produces a vector of integer
6599/// types.
John Wiegley429bb272011-04-08 18:41:53 +00006600QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006601 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00006602 bool isRelational) {
6603 // Check to make sure we're operating on vectors of the same type and width,
6604 // Allowing one side to be a scalar of element type.
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006605 QualType vType = CheckVectorOperands(lex, rex, Loc, /*isCompAssign*/false);
Nate Begemanbe2341d2008-07-14 18:02:46 +00006606 if (vType.isNull())
6607 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006608
John Wiegley429bb272011-04-08 18:41:53 +00006609 QualType lType = lex.get()->getType();
6610 QualType rType = rex.get()->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006611
Anton Yartsev7870b132011-03-27 15:36:07 +00006612 // If AltiVec, the comparison results in a numeric type, i.e.
6613 // bool for C++, int for C
Anton Yartsev6305f722011-03-28 21:00:05 +00006614 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev7870b132011-03-27 15:36:07 +00006615 return Context.getLogicalOperationType();
6616
Nate Begemanbe2341d2008-07-14 18:02:46 +00006617 // For non-floating point types, check for self-comparisons of the form
6618 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6619 // often indicate logic errors in the program.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006620 if (!lType->hasFloatingRepresentation()) {
John Wiegley429bb272011-04-08 18:41:53 +00006621 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
6622 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006623 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek351ba912011-02-23 01:52:04 +00006624 DiagRuntimeBehavior(Loc, 0,
Douglas Gregord64fdd02010-06-08 19:50:34 +00006625 PDiag(diag::warn_comparison_always)
6626 << 0 // self-
6627 << 2 // "a constant"
6628 );
Nate Begemanbe2341d2008-07-14 18:02:46 +00006629 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006630
Nate Begemanbe2341d2008-07-14 18:02:46 +00006631 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor8eee1192010-06-22 22:12:46 +00006632 if (!isRelational && lType->hasFloatingRepresentation()) {
6633 assert (rType->hasFloatingRepresentation());
John Wiegley429bb272011-04-08 18:41:53 +00006634 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begemanbe2341d2008-07-14 18:02:46 +00006635 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006636
Nate Begemanbe2341d2008-07-14 18:02:46 +00006637 // Return the type for the comparison, which is the same as vector type for
6638 // integer vectors, or an integer type of identical size and number of
6639 // elements for floating point vectors.
Douglas Gregorf6094622010-07-23 15:58:24 +00006640 if (lType->hasIntegerRepresentation())
Nate Begemanbe2341d2008-07-14 18:02:46 +00006641 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006642
John McCall183700f2009-09-21 23:43:11 +00006643 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00006644 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00006645 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00006646 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00006647 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00006648 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6649
Mike Stumpeed9cac2009-02-19 03:04:26 +00006650 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00006651 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00006652 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6653}
6654
Reid Spencer5f016e22007-07-11 17:01:13 +00006655inline QualType Sema::CheckBitwiseOperands(
John Wiegley429bb272011-04-08 18:41:53 +00006656 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
Richard Trieu67e29332011-08-02 04:35:43 +00006657 if (lex.get()->getType()->isVectorType() ||
6658 rex.get()->getType()->isVectorType()) {
John Wiegley429bb272011-04-08 18:41:53 +00006659 if (lex.get()->getType()->hasIntegerRepresentation() &&
6660 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00006661 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Douglas Gregorf6094622010-07-23 15:58:24 +00006662
6663 return InvalidOperands(Loc, lex, rex);
6664 }
Steve Naroff90045e82007-07-13 23:32:42 +00006665
John Wiegley429bb272011-04-08 18:41:53 +00006666 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
Richard Trieu67e29332011-08-02 04:35:43 +00006667 QualType compType = UsualArithmeticConversions(lexResult, rexResult,
6668 isCompAssign);
John Wiegley429bb272011-04-08 18:41:53 +00006669 if (lexResult.isInvalid() || rexResult.isInvalid())
6670 return QualType();
6671 lex = lexResult.take();
6672 rex = rexResult.take();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006673
John Wiegley429bb272011-04-08 18:41:53 +00006674 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6675 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00006676 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006677 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00006678}
6679
6680inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley429bb272011-04-08 18:41:53 +00006681 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner90a8f272010-07-13 19:41:32 +00006682
6683 // Diagnose cases where the user write a logical and/or but probably meant a
6684 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6685 // is a constant.
Richard Trieu67e29332011-08-02 04:35:43 +00006686 if (lex.get()->getType()->isIntegerType() &&
6687 !lex.get()->getType()->isBooleanType() &&
John Wiegley429bb272011-04-08 18:41:53 +00006688 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Richard Trieue5adf592011-07-15 00:00:51 +00006689 // Don't warn in macros or template instantiations.
6690 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattnerb7690b42010-07-24 01:10:11 +00006691 // If the RHS can be constant folded, and if it constant folds to something
6692 // that isn't 0 or 1 (which indicate a potential logical operation that
6693 // happened to fold to true/false) then warn.
Chandler Carruth0683a142011-05-31 05:41:42 +00006694 // Parens on the RHS are ignored.
Chris Lattnerb7690b42010-07-24 01:10:11 +00006695 Expr::EvalResult Result;
Chandler Carruth0683a142011-05-31 05:41:42 +00006696 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6697 if ((getLangOptions().Bool && !rex.get()->getType()->isBooleanType()) ||
6698 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6699 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6700 << rex.get()->getSourceRange()
6701 << (Opc == BO_LAnd ? "&&" : "||")
6702 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattnerb7690b42010-07-24 01:10:11 +00006703 }
6704 }
Chris Lattner90a8f272010-07-13 19:41:32 +00006705
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006706 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00006707 lex = UsualUnaryConversions(lex.take());
6708 if (lex.isInvalid())
6709 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006710
John Wiegley429bb272011-04-08 18:41:53 +00006711 rex = UsualUnaryConversions(rex.take());
6712 if (rex.isInvalid())
6713 return QualType();
6714
Richard Trieu67e29332011-08-02 04:35:43 +00006715 if (!lex.get()->getType()->isScalarType() ||
6716 !rex.get()->getType()->isScalarType())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006717 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006718
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006719 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00006720 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006721
John McCall75f7c0f2010-06-04 00:29:51 +00006722 // The following is safe because we only use this method for
6723 // non-overloadable operands.
6724
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006725 // C++ [expr.log.and]p1
6726 // C++ [expr.log.or]p1
John McCall75f7c0f2010-06-04 00:29:51 +00006727 // The operands are both contextually converted to type bool.
John Wiegley429bb272011-04-08 18:41:53 +00006728 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
6729 if (lexRes.isInvalid())
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006730 return InvalidOperands(Loc, lex, rex);
John Wiegley429bb272011-04-08 18:41:53 +00006731 lex = move(lexRes);
6732
6733 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
6734 if (rexRes.isInvalid())
6735 return InvalidOperands(Loc, lex, rex);
6736 rex = move(rexRes);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006737
Anders Carlssona4c98cd2009-11-23 21:47:44 +00006738 // C++ [expr.log.and]p2
6739 // C++ [expr.log.or]p2
6740 // The result is a bool.
6741 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006742}
6743
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006744/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6745/// is a read-only property; return true if so. A readonly property expression
6746/// depends on various declarations and thus must be treated specially.
6747///
Mike Stump1eb44332009-09-09 15:08:12 +00006748static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006749 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6750 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCall12f78a62010-12-02 01:19:52 +00006751 if (PropExpr->isImplicitProperty()) return false;
6752
6753 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6754 QualType BaseType = PropExpr->isSuperReceiver() ?
6755 PropExpr->getSuperReceiverType() :
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00006756 PropExpr->getBase()->getType();
6757
John McCall12f78a62010-12-02 01:19:52 +00006758 if (const ObjCObjectPointerType *OPT =
6759 BaseType->getAsObjCInterfacePointerType())
6760 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6761 if (S.isPropertyReadonly(PDecl, IFace))
6762 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006763 }
6764 return false;
6765}
6766
Fariborz Jahanian14086762011-03-28 23:47:18 +00006767static bool IsConstProperty(Expr *E, Sema &S) {
6768 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6769 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6770 if (PropExpr->isImplicitProperty()) return false;
6771
6772 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6773 QualType T = PDecl->getType();
6774 if (T->isReferenceType())
Fariborz Jahanian61750f22011-03-30 16:59:30 +00006775 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanian14086762011-03-28 23:47:18 +00006776 CanQualType CT = S.Context.getCanonicalType(T);
6777 return CT.isConstQualified();
6778 }
6779 return false;
6780}
6781
Fariborz Jahanian077f4902011-03-26 19:48:30 +00006782static bool IsReadonlyMessage(Expr *E, Sema &S) {
6783 if (E->getStmtClass() != Expr::MemberExprClass)
6784 return false;
6785 const MemberExpr *ME = cast<MemberExpr>(E);
6786 NamedDecl *Member = ME->getMemberDecl();
6787 if (isa<FieldDecl>(Member)) {
6788 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
6789 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
6790 return false;
6791 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
6792 }
6793 return false;
6794}
6795
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006796/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6797/// emit an error and return true. If so, return false.
6798static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006799 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00006800 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006801 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00006802 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6803 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian14086762011-03-28 23:47:18 +00006804 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
6805 IsLV = Expr::MLV_Valid;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00006806 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
6807 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006808 if (IsLV == Expr::MLV_Valid)
6809 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006810
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006811 unsigned Diag = 0;
6812 bool NeedType = false;
6813 switch (IsLV) { // C99 6.5.16p2
John McCallf85e1932011-06-15 23:02:42 +00006814 case Expr::MLV_ConstQualified:
6815 Diag = diag::err_typecheck_assign_const;
6816
John McCall7acddac2011-06-17 06:42:21 +00006817 // In ARC, use some specialized diagnostics for occasions where we
6818 // infer 'const'. These are always pseudo-strong variables.
John McCallf85e1932011-06-15 23:02:42 +00006819 if (S.getLangOptions().ObjCAutoRefCount) {
6820 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
6821 if (declRef && isa<VarDecl>(declRef->getDecl())) {
6822 VarDecl *var = cast<VarDecl>(declRef->getDecl());
6823
John McCall7acddac2011-06-17 06:42:21 +00006824 // Use the normal diagnostic if it's pseudo-__strong but the
6825 // user actually wrote 'const'.
6826 if (var->isARCPseudoStrong() &&
6827 (!var->getTypeSourceInfo() ||
6828 !var->getTypeSourceInfo()->getType().isConstQualified())) {
6829 // There are two pseudo-strong cases:
6830 // - self
John McCallf85e1932011-06-15 23:02:42 +00006831 ObjCMethodDecl *method = S.getCurMethodDecl();
6832 if (method && var == method->getSelfDecl())
6833 Diag = diag::err_typecheck_arr_assign_self;
John McCall7acddac2011-06-17 06:42:21 +00006834
6835 // - fast enumeration variables
6836 else
John McCallf85e1932011-06-15 23:02:42 +00006837 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCall7acddac2011-06-17 06:42:21 +00006838
John McCallf85e1932011-06-15 23:02:42 +00006839 SourceRange Assign;
6840 if (Loc != OrigLoc)
6841 Assign = SourceRange(OrigLoc, OrigLoc);
6842 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
6843 // We need to preserve the AST regardless, so migration tool
6844 // can do its job.
6845 return false;
6846 }
6847 }
6848 }
6849
6850 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006851 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006852 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6853 NeedType = true;
6854 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006855 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006856 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6857 NeedType = true;
6858 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00006859 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006860 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6861 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00006862 case Expr::MLV_Valid:
6863 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00006864 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00006865 case Expr::MLV_MemberFunction:
6866 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006867 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6868 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006869 case Expr::MLV_IncompleteType:
6870 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00006871 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006872 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00006873 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00006874 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006875 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6876 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00006877 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006878 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6879 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00006880 case Expr::MLV_ReadonlyProperty:
6881 Diag = diag::error_readonly_property_assignment;
6882 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00006883 case Expr::MLV_NoSetterProperty:
6884 Diag = diag::error_nosetter_property_assignment;
6885 break;
Fariborz Jahanian077f4902011-03-26 19:48:30 +00006886 case Expr::MLV_InvalidMessageExpression:
6887 Diag = diag::error_readonly_message_assignment;
6888 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00006889 case Expr::MLV_SubObjCPropertySetting:
6890 Diag = diag::error_no_subobject_property_setting;
6891 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006892 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00006893
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006894 SourceRange Assign;
6895 if (Loc != OrigLoc)
6896 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006897 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00006898 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006899 else
Mike Stump1eb44332009-09-09 15:08:12 +00006900 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006901 return true;
6902}
6903
6904
6905
6906// C99 6.5.16.1
John Wiegley429bb272011-04-08 18:41:53 +00006907QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006908 SourceLocation Loc,
6909 QualType CompoundType) {
6910 // Verify that LHS is a modifiable lvalue, and emit error if not.
6911 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00006912 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006913
6914 QualType LHSType = LHS->getType();
Richard Trieu67e29332011-08-02 04:35:43 +00006915 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
6916 CompoundType;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006917 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006918 if (CompoundType.isNull()) {
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00006919 QualType LHSTy(LHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00006920 // Simple assignment "x = y".
John Wiegley429bb272011-04-08 18:41:53 +00006921 if (LHS->getObjectKind() == OK_ObjCProperty) {
6922 ExprResult LHSResult = Owned(LHS);
6923 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
6924 if (LHSResult.isInvalid())
6925 return QualType();
6926 LHS = LHSResult.take();
6927 }
Fariborz Jahaniane2a901a2010-06-07 22:02:01 +00006928 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00006929 if (RHS.isInvalid())
6930 return QualType();
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00006931 // Special case of NSObject attributes on c-style pointer types.
6932 if (ConvTy == IncompatiblePointer &&
6933 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00006934 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00006935 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00006936 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00006937 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006938
John McCallf89e55a2010-11-18 06:31:45 +00006939 if (ConvTy == Compatible &&
6940 getLangOptions().ObjCNonFragileABI &&
6941 LHSType->isObjCObjectType())
6942 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
6943 << LHSType;
6944
Chris Lattner2c156472008-08-21 18:04:13 +00006945 // If the RHS is a unary plus or minus, check to see if they = and + are
6946 // right next to each other. If so, the user may have typo'd "x =+ 4"
6947 // instead of "x += 4".
John Wiegley429bb272011-04-08 18:41:53 +00006948 Expr *RHSCheck = RHS.get();
Chris Lattner2c156472008-08-21 18:04:13 +00006949 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
6950 RHSCheck = ICE->getSubExpr();
6951 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCall2de56d12010-08-25 11:45:40 +00006952 if ((UO->getOpcode() == UO_Plus ||
6953 UO->getOpcode() == UO_Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006954 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00006955 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00006956 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
6957 // And there is a space or other character before the subexpr of the
6958 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00006959 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
6960 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006961 Diag(Loc, diag::warn_not_compound_assign)
John McCall2de56d12010-08-25 11:45:40 +00006962 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006963 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00006964 }
Chris Lattner2c156472008-08-21 18:04:13 +00006965 }
John McCallf85e1932011-06-15 23:02:42 +00006966
6967 if (ConvTy == Compatible) {
6968 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
6969 checkRetainCycles(LHS, RHS.get());
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006970 else if (getLangOptions().ObjCAutoRefCount)
6971 checkUnsafeExprAssigns(Loc, LHS, RHS.get());
John McCallf85e1932011-06-15 23:02:42 +00006972 }
Chris Lattner2c156472008-08-21 18:04:13 +00006973 } else {
6974 // Compound assignment "x += y"
Douglas Gregorb608b982011-01-28 02:26:04 +00006975 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00006976 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00006977
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006978 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley429bb272011-04-08 18:41:53 +00006979 RHS.get(), AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00006980 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006981
Argyrios Kyrtzidis8a285ae2011-04-26 17:41:22 +00006982 CheckForNullPointerDereference(*this, LHS);
Ted Kremeneka0125d82011-02-16 01:57:07 +00006983 // Check for trivial buffer overflows.
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006984 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006985
Reid Spencer5f016e22007-07-11 17:01:13 +00006986 // C99 6.5.16p3: The type of an assignment expression is the type of the
6987 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00006988 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00006989 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
6990 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006991 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00006992 // operand.
John McCall2bf6f492010-10-12 02:19:57 +00006993 return (getLangOptions().CPlusPlus
6994 ? LHSType : LHSType.getUnqualifiedType());
Reid Spencer5f016e22007-07-11 17:01:13 +00006995}
6996
Chris Lattner29a1cfb2008-11-18 01:30:42 +00006997// C99 6.5.17
John Wiegley429bb272011-04-08 18:41:53 +00006998static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall09431682010-11-18 19:01:18 +00006999 SourceLocation Loc) {
John Wiegley429bb272011-04-08 18:41:53 +00007000 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis25973452010-06-30 10:53:14 +00007001
John McCallfb8721c2011-04-10 19:13:55 +00007002 LHS = S.CheckPlaceholderExpr(LHS.take());
7003 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley429bb272011-04-08 18:41:53 +00007004 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor7ad5d422010-11-09 21:07:58 +00007005 return QualType();
7006
John McCallcf2e5062010-10-12 07:14:40 +00007007 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7008 // operands, but not unary promotions.
7009 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007010
John McCallf6a16482010-12-04 03:47:34 +00007011 // So we treat the LHS as a ignored value, and in C++ we allow the
7012 // containing site to determine what should be done with the RHS.
John Wiegley429bb272011-04-08 18:41:53 +00007013 LHS = S.IgnoredValueConversions(LHS.take());
7014 if (LHS.isInvalid())
7015 return QualType();
John McCallf6a16482010-12-04 03:47:34 +00007016
7017 if (!S.getLangOptions().CPlusPlus) {
John Wiegley429bb272011-04-08 18:41:53 +00007018 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7019 if (RHS.isInvalid())
7020 return QualType();
7021 if (!RHS.get()->getType()->isVoidType())
Richard Trieu67e29332011-08-02 04:35:43 +00007022 S.RequireCompleteType(Loc, RHS.get()->getType(),
7023 diag::err_incomplete_type);
John McCallcf2e5062010-10-12 07:14:40 +00007024 }
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007025
John Wiegley429bb272011-04-08 18:41:53 +00007026 return RHS.get()->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007027}
7028
Steve Naroff49b45262007-07-13 16:58:59 +00007029/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7030/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall09431682010-11-18 19:01:18 +00007031static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7032 ExprValueKind &VK,
7033 SourceLocation OpLoc,
7034 bool isInc, bool isPrefix) {
Sebastian Redl28507842009-02-26 14:39:58 +00007035 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007036 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007037
Chris Lattner3528d352008-11-21 07:05:48 +00007038 QualType ResType = Op->getType();
7039 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007040
John McCall09431682010-11-18 19:01:18 +00007041 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007042 // Decrement of bool is not allowed.
7043 if (!isInc) {
John McCall09431682010-11-18 19:01:18 +00007044 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007045 return QualType();
7046 }
7047 // Increment of bool sets it to true, but is deprecated.
John McCall09431682010-11-18 19:01:18 +00007048 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00007049 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007050 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00007051 } else if (ResType->isAnyPointerType()) {
7052 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00007053
Chris Lattner3528d352008-11-21 07:05:48 +00007054 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruth13b21be2011-06-27 08:02:19 +00007055 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00007056 return QualType();
Chandler Carruth13b21be2011-06-27 08:02:19 +00007057
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007058 // Diagnose bad cases where we step over interface counts.
John McCall09431682010-11-18 19:01:18 +00007059 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7060 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00007061 << PointeeTy << Op->getSourceRange();
7062 return QualType();
7063 }
Eli Friedman5b088a12010-01-03 00:20:48 +00007064 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00007065 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall09431682010-11-18 19:01:18 +00007066 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00007067 << ResType << Op->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00007068 } else if (ResType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007069 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007070 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007071 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7072 isInc, isPrefix);
Anton Yartsev683564a2011-02-07 02:17:30 +00007073 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7074 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner3528d352008-11-21 07:05:48 +00007075 } else {
John McCall09431682010-11-18 19:01:18 +00007076 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00007077 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00007078 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00007079 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007080 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00007081 // Now make sure the operand is a modifiable lvalue.
John McCall09431682010-11-18 19:01:18 +00007082 if (CheckForModifiableLvalue(Op, OpLoc, S))
Reid Spencer5f016e22007-07-11 17:01:13 +00007083 return QualType();
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00007084 // In C++, a prefix increment is the same type as the operand. Otherwise
7085 // (in C or with postfix), the increment is the unqualified type of the
7086 // operand.
John McCall09431682010-11-18 19:01:18 +00007087 if (isPrefix && S.getLangOptions().CPlusPlus) {
7088 VK = VK_LValue;
7089 return ResType;
7090 } else {
7091 VK = VK_RValue;
7092 return ResType.getUnqualifiedType();
7093 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007094}
7095
John Wiegley429bb272011-04-08 18:41:53 +00007096ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCallf6a16482010-12-04 03:47:34 +00007097 assert(E->getValueKind() == VK_LValue &&
7098 E->getObjectKind() == OK_ObjCProperty);
7099 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7100
Douglas Gregor926df6c2011-06-11 01:09:30 +00007101 QualType T = E->getType();
7102 QualType ReceiverType;
7103 if (PRE->isObjectReceiver())
7104 ReceiverType = PRE->getBase()->getType();
7105 else if (PRE->isSuperReceiver())
7106 ReceiverType = PRE->getSuperReceiverType();
7107 else
7108 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
7109
John McCallf6a16482010-12-04 03:47:34 +00007110 ExprValueKind VK = VK_RValue;
7111 if (PRE->isImplicitProperty()) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00007112 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007113 PRE->getImplicitPropertyGetter()) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00007114 T = getMessageSendResultType(ReceiverType, GetterMethod,
7115 PRE->isClassReceiver(),
7116 PRE->isSuperReceiver());
7117 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian99130e52010-12-22 19:46:35 +00007118 }
7119 else {
7120 Diag(PRE->getLocation(), diag::err_getter_not_found)
7121 << PRE->getBase()->getType();
7122 }
John McCallf6a16482010-12-04 03:47:34 +00007123 }
Douglas Gregor926df6c2011-06-11 01:09:30 +00007124
7125 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCallf6a16482010-12-04 03:47:34 +00007126 E, 0, VK);
John McCalldb67e2f2010-12-10 01:49:45 +00007127
7128 ExprResult Result = MaybeBindToTemporary(E);
7129 if (!Result.isInvalid())
7130 E = Result.take();
John Wiegley429bb272011-04-08 18:41:53 +00007131
7132 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00007133}
7134
Richard Trieu67e29332011-08-02 04:35:43 +00007135void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
7136 QualType &LHSTy) {
John Wiegley429bb272011-04-08 18:41:53 +00007137 assert(LHS.get()->getValueKind() == VK_LValue &&
7138 LHS.get()->getObjectKind() == OK_ObjCProperty);
7139 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCallf6a16482010-12-04 03:47:34 +00007140
John McCallf85e1932011-06-15 23:02:42 +00007141 bool Consumed = false;
7142
John Wiegley429bb272011-04-08 18:41:53 +00007143 if (PropRef->isImplicitProperty()) {
John McCallf6a16482010-12-04 03:47:34 +00007144 // If using property-dot syntax notation for assignment, and there is a
7145 // setter, RHS expression is being passed to the setter argument. So,
7146 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley429bb272011-04-08 18:41:53 +00007147 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCallf6a16482010-12-04 03:47:34 +00007148 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7149 LHSTy = (*P)->getType();
John McCallf85e1932011-06-15 23:02:42 +00007150 Consumed = (getLangOptions().ObjCAutoRefCount &&
7151 (*P)->hasAttr<NSConsumedAttr>());
John McCallf6a16482010-12-04 03:47:34 +00007152
7153 // Otherwise, if the getter returns an l-value, just call that.
7154 } else {
John Wiegley429bb272011-04-08 18:41:53 +00007155 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCallf6a16482010-12-04 03:47:34 +00007156 ExprValueKind VK = Expr::getValueKindForType(Result);
7157 if (VK == VK_LValue) {
John Wiegley429bb272011-04-08 18:41:53 +00007158 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7159 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCallf6a16482010-12-04 03:47:34 +00007160 return;
John McCall12f78a62010-12-02 01:19:52 +00007161 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007162 }
John McCallf85e1932011-06-15 23:02:42 +00007163 } else if (getLangOptions().ObjCAutoRefCount) {
7164 const ObjCMethodDecl *setter
7165 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7166 if (setter) {
7167 ObjCMethodDecl::param_iterator P = setter->param_begin();
7168 LHSTy = (*P)->getType();
7169 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7170 }
John McCallf6a16482010-12-04 03:47:34 +00007171 }
7172
John McCallf85e1932011-06-15 23:02:42 +00007173 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7174 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007175 InitializedEntity Entity =
John McCallf85e1932011-06-15 23:02:42 +00007176 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley429bb272011-04-08 18:41:53 +00007177 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCallf85e1932011-06-15 23:02:42 +00007178 if (!ArgE.isInvalid()) {
John Wiegley429bb272011-04-08 18:41:53 +00007179 RHS = ArgE;
John McCallf85e1932011-06-15 23:02:42 +00007180 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7181 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7182 }
Fariborz Jahanianc4e1a682010-09-14 23:02:38 +00007183 }
7184}
7185
7186
Anders Carlsson369dee42008-02-01 07:15:58 +00007187/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00007188/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007189/// where the declaration is needed for type checking. We only need to
7190/// handle cases when the expression references a function designator
7191/// or is an lvalue. Here are some examples:
7192/// - &(x) => x
7193/// - &*****f => f for f a function designator.
7194/// - &s.xx => s
7195/// - &s.zz[1].yy -> s, if zz is an array
7196/// - *(x + 1) -> x, if x is an array
7197/// - &"123"[2] -> 0
7198/// - & __real__ x -> x
John McCall5808ce42011-02-03 08:15:49 +00007199static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00007200 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007201 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007202 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007203 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007204 // If this is an arrow operator, the address is an offset from
7205 // the base's value, so the object the base refers to is
7206 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007207 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00007208 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00007209 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00007210 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00007211 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00007212 // FIXME: This code shouldn't be necessary! We should catch the implicit
7213 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00007214 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7215 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7216 if (ICE->getSubExpr()->getType()->isArrayType())
7217 return getPrimaryDecl(ICE->getSubExpr());
7218 }
7219 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00007220 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007221 case Stmt::UnaryOperatorClass: {
7222 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007223
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007224 switch(UO->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00007225 case UO_Real:
7226 case UO_Imag:
7227 case UO_Extension:
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00007228 return getPrimaryDecl(UO->getSubExpr());
7229 default:
7230 return 0;
7231 }
7232 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007233 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00007234 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00007235 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00007236 // If the result of an implicit cast is an l-value, we care about
7237 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00007238 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00007239 default:
7240 return 0;
7241 }
7242}
7243
7244/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00007245/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00007246/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007247/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00007248/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007249/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00007250/// we allow the '&' but retain the overloaded-function type.
John McCall09431682010-11-18 19:01:18 +00007251static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7252 SourceLocation OpLoc) {
John McCall9c72c602010-08-27 09:08:28 +00007253 if (OrigOp->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007254 return S.Context.DependentTy;
7255 if (OrigOp->getType() == S.Context.OverloadTy)
7256 return S.Context.OverloadTy;
John McCall755d8492011-04-12 00:42:48 +00007257 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7258 return S.Context.UnknownAnyTy;
John McCall864c0412011-04-26 20:42:42 +00007259 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7260 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7261 << OrigOp->getSourceRange();
7262 return QualType();
7263 }
John McCall9c72c602010-08-27 09:08:28 +00007264
John McCall755d8492011-04-12 00:42:48 +00007265 assert(!OrigOp->getType()->isPlaceholderType());
John McCall2cd11fe2010-10-12 02:09:17 +00007266
John McCall9c72c602010-08-27 09:08:28 +00007267 // Make sure to ignore parentheses in subsequent checks
7268 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor9103bb22008-12-17 22:52:20 +00007269
John McCall09431682010-11-18 19:01:18 +00007270 if (S.getLangOptions().C99) {
Steve Naroff08f19672008-01-13 17:10:08 +00007271 // Implement C99-only parts of addressof rules.
7272 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCall2de56d12010-08-25 11:45:40 +00007273 if (uOp->getOpcode() == UO_Deref)
Steve Naroff08f19672008-01-13 17:10:08 +00007274 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7275 // (assuming the deref expression is valid).
7276 return uOp->getSubExpr()->getType();
7277 }
7278 // Technically, there should be a check for array subscript
7279 // expressions here, but the result of one is always an lvalue anyway.
7280 }
John McCall5808ce42011-02-03 08:15:49 +00007281 ValueDecl *dcl = getPrimaryDecl(op);
John McCall7eb0a9e2010-11-24 05:12:34 +00007282 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00007283
Fariborz Jahanian077f4902011-03-26 19:48:30 +00007284 if (lval == Expr::LV_ClassTemporary) {
John McCall09431682010-11-18 19:01:18 +00007285 bool sfinae = S.isSFINAEContext();
7286 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7287 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregore873fb72010-02-16 21:39:57 +00007288 << op->getType() << op->getSourceRange();
John McCall09431682010-11-18 19:01:18 +00007289 if (sfinae)
Douglas Gregore873fb72010-02-16 21:39:57 +00007290 return QualType();
John McCall9c72c602010-08-27 09:08:28 +00007291 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007292 return S.Context.getPointerType(op->getType());
John McCall9c72c602010-08-27 09:08:28 +00007293 } else if (lval == Expr::LV_MemberFunction) {
7294 // If it's an instance method, make a member pointer.
7295 // The expression must have exactly the form &A::foo.
7296
7297 // If the underlying expression isn't a decl ref, give up.
7298 if (!isa<DeclRefExpr>(op)) {
John McCall09431682010-11-18 19:01:18 +00007299 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007300 << OrigOp->getSourceRange();
7301 return QualType();
7302 }
7303 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7304 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7305
7306 // The id-expression was parenthesized.
7307 if (OrigOp != DRE) {
John McCall09431682010-11-18 19:01:18 +00007308 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007309 << OrigOp->getSourceRange();
7310
7311 // The method was named without a qualifier.
7312 } else if (!DRE->getQualifier()) {
John McCall09431682010-11-18 19:01:18 +00007313 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall9c72c602010-08-27 09:08:28 +00007314 << op->getSourceRange();
7315 }
7316
John McCall09431682010-11-18 19:01:18 +00007317 return S.Context.getMemberPointerType(op->getType(),
7318 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00007319 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00007320 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007321 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00007322 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00007323 // FIXME: emit more specific diag...
John McCall09431682010-11-18 19:01:18 +00007324 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00007325 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007326 return QualType();
7327 }
John McCall7eb0a9e2010-11-24 05:12:34 +00007328 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00007329 // The operand cannot be a bit-field
John McCall09431682010-11-18 19:01:18 +00007330 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman23d58ce2009-04-20 08:23:18 +00007331 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00007332 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007333 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00007334 // The operand cannot be an element of a vector
John McCall09431682010-11-18 19:01:18 +00007335 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00007336 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00007337 return QualType();
John McCall7eb0a9e2010-11-24 05:12:34 +00007338 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007339 // cannot take address of a property expression.
John McCall09431682010-11-18 19:01:18 +00007340 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian0337f212009-07-07 18:50:52 +00007341 << "property expression" << op->getSourceRange();
7342 return QualType();
Steve Naroffbcb2b612008-02-29 23:30:25 +00007343 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00007344 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00007345 // with the register storage-class specifier.
7346 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahanian4020f872010-08-24 22:21:48 +00007347 // in C++ it is not error to take address of a register
7348 // variable (c++03 7.1.1P3)
John McCalld931b082010-08-26 03:08:43 +00007349 if (vd->getStorageClass() == SC_Register &&
John McCall09431682010-11-18 19:01:18 +00007350 !S.getLangOptions().CPlusPlus) {
7351 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattnerd3a94e22008-11-20 06:06:08 +00007352 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00007353 return QualType();
7354 }
John McCallba135432009-11-21 08:51:07 +00007355 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall09431682010-11-18 19:01:18 +00007356 return S.Context.OverloadTy;
John McCall5808ce42011-02-03 08:15:49 +00007357 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00007358 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00007359 // Could be a pointer to member, though, if there is an explicit
7360 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00007361 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00007362 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007363 if (Ctx && Ctx->isRecord()) {
John McCall5808ce42011-02-03 08:15:49 +00007364 if (dcl->getType()->isReferenceType()) {
John McCall09431682010-11-18 19:01:18 +00007365 S.Diag(OpLoc,
7366 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCall5808ce42011-02-03 08:15:49 +00007367 << dcl->getDeclName() << dcl->getType();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007368 return QualType();
7369 }
Mike Stump1eb44332009-09-09 15:08:12 +00007370
Argyrios Kyrtzidis0413db42011-01-31 07:04:29 +00007371 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7372 Ctx = Ctx->getParent();
John McCall09431682010-11-18 19:01:18 +00007373 return S.Context.getMemberPointerType(op->getType(),
7374 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00007375 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00007376 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00007377 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00007378 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00007379 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00007380
Eli Friedman441cf102009-05-16 23:27:50 +00007381 if (lval == Expr::LV_IncompleteVoidType) {
7382 // Taking the address of a void variable is technically illegal, but we
7383 // allow it in cases which are otherwise valid.
7384 // Example: "extern void x; void* y = &x;".
John McCall09431682010-11-18 19:01:18 +00007385 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedman441cf102009-05-16 23:27:50 +00007386 }
7387
Reid Spencer5f016e22007-07-11 17:01:13 +00007388 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor8f70ddb2010-07-29 16:05:45 +00007389 if (op->getType()->isObjCObjectType())
John McCall09431682010-11-18 19:01:18 +00007390 return S.Context.getObjCObjectPointerType(op->getType());
7391 return S.Context.getPointerType(op->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +00007392}
7393
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007394/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall09431682010-11-18 19:01:18 +00007395static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7396 SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00007397 if (Op->isTypeDependent())
John McCall09431682010-11-18 19:01:18 +00007398 return S.Context.DependentTy;
Sebastian Redl28507842009-02-26 14:39:58 +00007399
John Wiegley429bb272011-04-08 18:41:53 +00007400 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7401 if (ConvResult.isInvalid())
7402 return QualType();
7403 Op = ConvResult.take();
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007404 QualType OpTy = Op->getType();
7405 QualType Result;
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00007406
7407 if (isa<CXXReinterpretCastExpr>(Op)) {
7408 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7409 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7410 Op->getSourceRange());
7411 }
7412
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007413 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7414 // is an incomplete type or void. It would be possible to warn about
7415 // dereferencing a void pointer, but it's completely well-defined, and such a
7416 // warning is unlikely to catch any mistakes.
7417 if (const PointerType *PT = OpTy->getAs<PointerType>())
7418 Result = PT->getPointeeType();
7419 else if (const ObjCObjectPointerType *OPT =
7420 OpTy->getAs<ObjCObjectPointerType>())
7421 Result = OPT->getPointeeType();
John McCall2cd11fe2010-10-12 02:09:17 +00007422 else {
John McCallfb8721c2011-04-10 19:13:55 +00007423 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall2cd11fe2010-10-12 02:09:17 +00007424 if (PR.isInvalid()) return QualType();
John McCall09431682010-11-18 19:01:18 +00007425 if (PR.take() != Op)
7426 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall2cd11fe2010-10-12 02:09:17 +00007427 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007428
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007429 if (Result.isNull()) {
John McCall09431682010-11-18 19:01:18 +00007430 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007431 << OpTy << Op->getSourceRange();
7432 return QualType();
7433 }
John McCall09431682010-11-18 19:01:18 +00007434
7435 // Dereferences are usually l-values...
7436 VK = VK_LValue;
7437
7438 // ...except that certain expressions are never l-values in C.
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00007439 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall09431682010-11-18 19:01:18 +00007440 VK = VK_RValue;
Chris Lattnerfd79a9d2010-07-05 19:17:26 +00007441
7442 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00007443}
7444
John McCall2de56d12010-08-25 11:45:40 +00007445static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007446 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007447 BinaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007448 switch (Kind) {
7449 default: assert(0 && "Unknown binop!");
John McCall2de56d12010-08-25 11:45:40 +00007450 case tok::periodstar: Opc = BO_PtrMemD; break;
7451 case tok::arrowstar: Opc = BO_PtrMemI; break;
7452 case tok::star: Opc = BO_Mul; break;
7453 case tok::slash: Opc = BO_Div; break;
7454 case tok::percent: Opc = BO_Rem; break;
7455 case tok::plus: Opc = BO_Add; break;
7456 case tok::minus: Opc = BO_Sub; break;
7457 case tok::lessless: Opc = BO_Shl; break;
7458 case tok::greatergreater: Opc = BO_Shr; break;
7459 case tok::lessequal: Opc = BO_LE; break;
7460 case tok::less: Opc = BO_LT; break;
7461 case tok::greaterequal: Opc = BO_GE; break;
7462 case tok::greater: Opc = BO_GT; break;
7463 case tok::exclaimequal: Opc = BO_NE; break;
7464 case tok::equalequal: Opc = BO_EQ; break;
7465 case tok::amp: Opc = BO_And; break;
7466 case tok::caret: Opc = BO_Xor; break;
7467 case tok::pipe: Opc = BO_Or; break;
7468 case tok::ampamp: Opc = BO_LAnd; break;
7469 case tok::pipepipe: Opc = BO_LOr; break;
7470 case tok::equal: Opc = BO_Assign; break;
7471 case tok::starequal: Opc = BO_MulAssign; break;
7472 case tok::slashequal: Opc = BO_DivAssign; break;
7473 case tok::percentequal: Opc = BO_RemAssign; break;
7474 case tok::plusequal: Opc = BO_AddAssign; break;
7475 case tok::minusequal: Opc = BO_SubAssign; break;
7476 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7477 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7478 case tok::ampequal: Opc = BO_AndAssign; break;
7479 case tok::caretequal: Opc = BO_XorAssign; break;
7480 case tok::pipeequal: Opc = BO_OrAssign; break;
7481 case tok::comma: Opc = BO_Comma; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007482 }
7483 return Opc;
7484}
7485
John McCall2de56d12010-08-25 11:45:40 +00007486static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Reid Spencer5f016e22007-07-11 17:01:13 +00007487 tok::TokenKind Kind) {
John McCall2de56d12010-08-25 11:45:40 +00007488 UnaryOperatorKind Opc;
Reid Spencer5f016e22007-07-11 17:01:13 +00007489 switch (Kind) {
7490 default: assert(0 && "Unknown unary op!");
John McCall2de56d12010-08-25 11:45:40 +00007491 case tok::plusplus: Opc = UO_PreInc; break;
7492 case tok::minusminus: Opc = UO_PreDec; break;
7493 case tok::amp: Opc = UO_AddrOf; break;
7494 case tok::star: Opc = UO_Deref; break;
7495 case tok::plus: Opc = UO_Plus; break;
7496 case tok::minus: Opc = UO_Minus; break;
7497 case tok::tilde: Opc = UO_Not; break;
7498 case tok::exclaim: Opc = UO_LNot; break;
7499 case tok::kw___real: Opc = UO_Real; break;
7500 case tok::kw___imag: Opc = UO_Imag; break;
7501 case tok::kw___extension__: Opc = UO_Extension; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00007502 }
7503 return Opc;
7504}
7505
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007506/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7507/// This warning is only emitted for builtin assignment operations. It is also
7508/// suppressed in the event of macro expansions.
7509static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7510 SourceLocation OpLoc) {
7511 if (!S.ActiveTemplateInstantiations.empty())
7512 return;
7513 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7514 return;
7515 lhs = lhs->IgnoreParenImpCasts();
7516 rhs = rhs->IgnoreParenImpCasts();
7517 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7518 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7519 if (!LeftDeclRef || !RightDeclRef ||
7520 LeftDeclRef->getLocation().isMacroID() ||
7521 RightDeclRef->getLocation().isMacroID())
7522 return;
7523 const ValueDecl *LeftDecl =
7524 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7525 const ValueDecl *RightDecl =
7526 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7527 if (LeftDecl != RightDecl)
7528 return;
7529 if (LeftDecl->getType().isVolatileQualified())
7530 return;
7531 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7532 if (RefTy->getPointeeType().isVolatileQualified())
7533 return;
7534
7535 S.Diag(OpLoc, diag::warn_self_assignment)
7536 << LeftDeclRef->getType()
7537 << lhs->getSourceRange() << rhs->getSourceRange();
7538}
7539
Douglas Gregoreaebc752008-11-06 23:29:22 +00007540/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7541/// operator @p Opc at location @c TokLoc. This routine only supports
7542/// built-in operations; ActOnBinOp handles overloaded operators.
John McCall60d7b3a2010-08-24 06:29:42 +00007543ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007544 BinaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00007545 Expr *lhsExpr, Expr *rhsExpr) {
7546 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007547 QualType ResultTy; // Result type of the binary operator.
Eli Friedmanab3a8522009-03-28 01:22:36 +00007548 // The following two variables are used for compound assignment operators
7549 QualType CompLHSTy; // Type of LHS after promotions for computation
7550 QualType CompResultTy; // Type of computation result
John McCallf89e55a2010-11-18 06:31:45 +00007551 ExprValueKind VK = VK_RValue;
7552 ExprObjectKind OK = OK_Ordinary;
Douglas Gregoreaebc752008-11-06 23:29:22 +00007553
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007554 // Check if a 'foo<int>' involved in a binary op, identifies a single
7555 // function unambiguously (i.e. an lvalue ala 13.4)
7556 // But since an assignment can trigger target based overload, exclude it in
7557 // our blind search. i.e:
7558 // template<class T> void f(); template<class T, class U> void f(U);
7559 // f<int> == 0; // resolve f<int> blindly
7560 // void (*p)(int); p = f<int>; // resolve f<int> using target
7561 if (Opc != BO_Assign) {
John McCallfb8721c2011-04-10 19:13:55 +00007562 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00007563 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00007564 lhs = move(resolvedLHS);
John McCall1de4d4e2011-04-07 08:22:57 +00007565
John McCallfb8721c2011-04-10 19:13:55 +00007566 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall1de4d4e2011-04-07 08:22:57 +00007567 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00007568 rhs = move(resolvedRHS);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00007569 }
7570
Eli Friedmaned3b2562011-06-17 20:52:22 +00007571 // The canonical way to check for a GNU null is with isNullPointerConstant,
7572 // but we use a bit of a hack here for speed; this is a relatively
7573 // hot path, and isNullPointerConstant is slow.
7574 bool LeftNull = isa<GNUNullExpr>(lhs.get()->IgnoreParenImpCasts());
7575 bool RightNull = isa<GNUNullExpr>(rhs.get()->IgnoreParenImpCasts());
Richard Trieu3e95ba92011-06-16 21:36:56 +00007576
7577 // Detect when a NULL constant is used improperly in an expression. These
7578 // are mainly cases where the null pointer is used as an integer instead
7579 // of a pointer.
7580 if (LeftNull || RightNull) {
Chandler Carruth1567a8b2011-06-20 07:38:51 +00007581 // Avoid analyzing cases where the result will either be invalid (and
7582 // diagnosed as such) or entirely valid and not something to warn about.
7583 QualType LeftType = lhs.get()->getType();
7584 QualType RightType = rhs.get()->getType();
7585 if (!LeftType->isBlockPointerType() && !LeftType->isMemberPointerType() &&
7586 !LeftType->isFunctionType() &&
7587 !RightType->isBlockPointerType() &&
7588 !RightType->isMemberPointerType() &&
7589 !RightType->isFunctionType()) {
7590 if (Opc == BO_Mul || Opc == BO_Div || Opc == BO_Rem || Opc == BO_Add ||
7591 Opc == BO_Sub || Opc == BO_Shl || Opc == BO_Shr || Opc == BO_And ||
7592 Opc == BO_Xor || Opc == BO_Or || Opc == BO_MulAssign ||
7593 Opc == BO_DivAssign || Opc == BO_AddAssign || Opc == BO_SubAssign ||
7594 Opc == BO_RemAssign || Opc == BO_ShlAssign || Opc == BO_ShrAssign ||
7595 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign) {
7596 // These are the operations that would not make sense with a null pointer
Richard Trieu67e29332011-08-02 04:35:43 +00007597 // pointer no matter what the other expression is.
Chandler Carruth2af68e42011-06-19 09:05:14 +00007598 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
Chandler Carruth1567a8b2011-06-20 07:38:51 +00007599 << (LeftNull ? lhs.get()->getSourceRange() : SourceRange())
7600 << (RightNull ? rhs.get()->getSourceRange() : SourceRange());
7601 } else if (Opc == BO_LE || Opc == BO_LT || Opc == BO_GE || Opc == BO_GT ||
7602 Opc == BO_EQ || Opc == BO_NE) {
7603 // These are the operations that would not make sense with a null pointer
7604 // if the other expression the other expression is not a pointer.
7605 if (LeftNull != RightNull &&
7606 !LeftType->isAnyPointerType() &&
7607 !LeftType->canDecayToPointerType() &&
7608 !RightType->isAnyPointerType() &&
7609 !RightType->canDecayToPointerType()) {
7610 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
7611 << (LeftNull ? lhs.get()->getSourceRange()
7612 : rhs.get()->getSourceRange());
7613 }
Richard Trieu3e95ba92011-06-16 21:36:56 +00007614 }
7615 }
7616 }
7617
Douglas Gregoreaebc752008-11-06 23:29:22 +00007618 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007619 case BO_Assign:
John Wiegley429bb272011-04-08 18:41:53 +00007620 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCallf6a16482010-12-04 03:47:34 +00007621 if (getLangOptions().CPlusPlus &&
John Wiegley429bb272011-04-08 18:41:53 +00007622 lhs.get()->getObjectKind() != OK_ObjCProperty) {
7623 VK = lhs.get()->getValueKind();
7624 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007625 }
Chandler Carruth9f7a6ee2011-01-04 06:52:15 +00007626 if (!ResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00007627 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007628 break;
John McCall2de56d12010-08-25 11:45:40 +00007629 case BO_PtrMemD:
7630 case BO_PtrMemI:
John McCallf89e55a2010-11-18 06:31:45 +00007631 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007632 Opc == BO_PtrMemI);
Sebastian Redl22460502009-02-07 00:15:38 +00007633 break;
John McCall2de56d12010-08-25 11:45:40 +00007634 case BO_Mul:
7635 case BO_Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00007636 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCall2de56d12010-08-25 11:45:40 +00007637 Opc == BO_Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007638 break;
John McCall2de56d12010-08-25 11:45:40 +00007639 case BO_Rem:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007640 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7641 break;
John McCall2de56d12010-08-25 11:45:40 +00007642 case BO_Add:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007643 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7644 break;
John McCall2de56d12010-08-25 11:45:40 +00007645 case BO_Sub:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007646 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7647 break;
John McCall2de56d12010-08-25 11:45:40 +00007648 case BO_Shl:
7649 case BO_Shr:
Chandler Carruth21206d52011-02-23 23:34:11 +00007650 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007651 break;
John McCall2de56d12010-08-25 11:45:40 +00007652 case BO_LE:
7653 case BO_LT:
7654 case BO_GE:
7655 case BO_GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00007656 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007657 break;
John McCall2de56d12010-08-25 11:45:40 +00007658 case BO_EQ:
7659 case BO_NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00007660 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007661 break;
John McCall2de56d12010-08-25 11:45:40 +00007662 case BO_And:
7663 case BO_Xor:
7664 case BO_Or:
Douglas Gregoreaebc752008-11-06 23:29:22 +00007665 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7666 break;
John McCall2de56d12010-08-25 11:45:40 +00007667 case BO_LAnd:
7668 case BO_LOr:
Chris Lattner90a8f272010-07-13 19:41:32 +00007669 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007670 break;
John McCall2de56d12010-08-25 11:45:40 +00007671 case BO_MulAssign:
7672 case BO_DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00007673 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCallf89e55a2010-11-18 06:31:45 +00007674 Opc == BO_DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007675 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00007676 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7677 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007678 break;
John McCall2de56d12010-08-25 11:45:40 +00007679 case BO_RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007680 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7681 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00007682 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7683 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007684 break;
John McCall2de56d12010-08-25 11:45:40 +00007685 case BO_AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007686 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00007687 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7688 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007689 break;
John McCall2de56d12010-08-25 11:45:40 +00007690 case BO_SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007691 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley429bb272011-04-08 18:41:53 +00007692 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7693 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007694 break;
John McCall2de56d12010-08-25 11:45:40 +00007695 case BO_ShlAssign:
7696 case BO_ShrAssign:
Chandler Carruth21206d52011-02-23 23:34:11 +00007697 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedmanab3a8522009-03-28 01:22:36 +00007698 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00007699 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7700 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007701 break;
John McCall2de56d12010-08-25 11:45:40 +00007702 case BO_AndAssign:
7703 case BO_XorAssign:
7704 case BO_OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00007705 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7706 CompLHSTy = CompResultTy;
John Wiegley429bb272011-04-08 18:41:53 +00007707 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7708 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00007709 break;
John McCall2de56d12010-08-25 11:45:40 +00007710 case BO_Comma:
John McCall09431682010-11-18 19:01:18 +00007711 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00007712 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
7713 VK = rhs.get()->getValueKind();
7714 OK = rhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007715 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00007716 break;
7717 }
John Wiegley429bb272011-04-08 18:41:53 +00007718 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00007719 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00007720 if (CompResultTy.isNull())
John Wiegley429bb272011-04-08 18:41:53 +00007721 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
7722 ResultTy, VK, OK, OpLoc));
Richard Trieu67e29332011-08-02 04:35:43 +00007723 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() !=
7724 OK_ObjCProperty) {
John McCallf89e55a2010-11-18 06:31:45 +00007725 VK = VK_LValue;
John Wiegley429bb272011-04-08 18:41:53 +00007726 OK = lhs.get()->getObjectKind();
John McCallf89e55a2010-11-18 06:31:45 +00007727 }
John Wiegley429bb272011-04-08 18:41:53 +00007728 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
7729 ResultTy, VK, OK, CompLHSTy,
John McCallf89e55a2010-11-18 06:31:45 +00007730 CompResultTy, OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00007731}
7732
Sebastian Redlaee3c932009-10-27 12:10:02 +00007733/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7734/// operators are mixed in a way that suggests that the programmer forgot that
7735/// comparison operators have higher precedence. The most typical example of
7736/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCall2de56d12010-08-25 11:45:40 +00007737static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007738 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00007739 typedef BinaryOperator BinOp;
7740 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7741 rhsopc = static_cast<BinOp::Opcode>(-1);
7742 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007743 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00007744 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007745 rhsopc = BO->getOpcode();
7746
7747 // Subs are not binary operators.
7748 if (lhsopc == -1 && rhsopc == -1)
7749 return;
7750
7751 // Bitwise operations are sometimes used as eager logical ops.
7752 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00007753 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7754 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007755 return;
7756
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007757 if (BinOp::isComparisonOp(lhsopc)) {
7758 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7759 << SourceRange(lhs->getLocStart(), OpLoc)
7760 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc);
Sebastian Redl6b169ac2009-10-26 17:01:32 +00007761 SuggestParentheses(Self, OpLoc,
Douglas Gregor55b38842010-04-14 16:09:52 +00007762 Self.PDiag(diag::note_precedence_bitwise_silence)
7763 << BinOp::getOpcodeStr(lhsopc),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007764 lhs->getSourceRange());
7765 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00007766 Self.PDiag(diag::note_precedence_bitwise_first)
7767 << BinOp::getOpcodeStr(Opc),
7768 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007769 } else if (BinOp::isComparisonOp(rhsopc)) {
7770 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7771 << SourceRange(OpLoc, rhs->getLocEnd())
7772 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc);
Sebastian Redl6b169ac2009-10-26 17:01:32 +00007773 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00007774 Self.PDiag(diag::note_precedence_bitwise_silence)
7775 << BinOp::getOpcodeStr(rhsopc),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007776 rhs->getSourceRange());
7777 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007778 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00007779 << BinOp::getOpcodeStr(Opc),
Douglas Gregorb27c7a12011-06-22 18:41:08 +00007780 SourceRange(lhs->getLocStart(),
7781 cast<BinOp>(rhs)->getLHS()->getLocStart()));
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007782 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007783}
7784
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00007785/// \brief It accepts a '&' expr that is inside a '|' one.
7786/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7787/// in parentheses.
7788static void
7789EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7790 BinaryOperator *Bop) {
7791 assert(Bop->getOpcode() == BO_And);
7792 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7793 << Bop->getSourceRange() << OpLoc;
7794 SuggestParentheses(Self, Bop->getOperatorLoc(),
7795 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7796 Bop->getSourceRange());
7797}
7798
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007799/// \brief It accepts a '&&' expr that is inside a '||' one.
7800/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7801/// in parentheses.
7802static void
7803EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00007804 BinaryOperator *Bop) {
7805 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007806 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7807 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisa61aedc2011-04-22 19:16:27 +00007808 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007809 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthf0b60d62011-06-16 01:05:14 +00007810 Bop->getSourceRange());
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007811}
7812
7813/// \brief Returns true if the given expression can be evaluated as a constant
7814/// 'true'.
7815static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7816 bool Res;
7817 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7818}
7819
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007820/// \brief Returns true if the given expression can be evaluated as a constant
7821/// 'false'.
7822static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7823 bool Res;
7824 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7825}
7826
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007827/// \brief Look for '&&' in the left hand of a '||' expr.
7828static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007829 Expr *OrLHS, Expr *OrRHS) {
7830 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007831 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007832 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7833 if (EvaluatesAsFalse(S, OrRHS))
7834 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007835 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7836 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7837 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7838 } else if (Bop->getOpcode() == BO_LOr) {
7839 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7840 // If it's "a || b && 1 || c" we didn't warn earlier for
7841 // "a || b && 1", but warn now.
7842 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7843 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7844 }
7845 }
7846 }
7847}
7848
7849/// \brief Look for '&&' in the right hand of a '||' expr.
7850static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007851 Expr *OrLHS, Expr *OrRHS) {
7852 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007853 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007854 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7855 if (EvaluatesAsFalse(S, OrLHS))
7856 return;
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007857 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7858 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7859 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007860 }
7861 }
7862}
7863
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00007864/// \brief Look for '&' in the left or right hand of a '|' expr.
7865static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7866 Expr *OrArg) {
7867 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7868 if (Bop->getOpcode() == BO_And)
7869 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7870 }
7871}
7872
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007873/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007874/// precedence.
John McCall2de56d12010-08-25 11:45:40 +00007875static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007876 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007877 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redlaee3c932009-10-27 12:10:02 +00007878 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidis33f46e22011-06-20 18:41:26 +00007879 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7880
7881 // Diagnose "arg1 & arg2 | arg3"
7882 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7883 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, lhs);
7884 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, rhs);
7885 }
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007886
Argyrios Kyrtzidis567bb712010-11-17 18:26:36 +00007887 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7888 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisd92ccaa2010-11-17 18:54:22 +00007889 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis47d512c2010-11-17 19:18:19 +00007890 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7891 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisbee77f72010-11-16 21:00:12 +00007892 }
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007893}
7894
Reid Spencer5f016e22007-07-11 17:01:13 +00007895// Binary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00007896ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCall2de56d12010-08-25 11:45:40 +00007897 tok::TokenKind Kind,
7898 Expr *lhs, Expr *rhs) {
7899 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Narofff69936d2007-09-16 03:34:24 +00007900 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
7901 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00007902
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00007903 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7904 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
7905
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007906 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
7907}
7908
John McCall60d7b3a2010-08-24 06:29:42 +00007909ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007910 BinaryOperatorKind Opc,
7911 Expr *lhs, Expr *rhs) {
John McCall01b2e4e2010-12-06 05:26:58 +00007912 if (getLangOptions().CPlusPlus) {
7913 bool UseBuiltinOperator;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007914
John McCall01b2e4e2010-12-06 05:26:58 +00007915 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
7916 UseBuiltinOperator = false;
7917 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
7918 UseBuiltinOperator = true;
7919 } else {
7920 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
7921 !rhs->getType()->isOverloadableType();
7922 }
7923
7924 if (!UseBuiltinOperator) {
7925 // Find all of the overloaded operators visible from this
7926 // point. We perform both an operator-name lookup from the local
7927 // scope and an argument-dependent lookup based on the types of
7928 // the arguments.
7929 UnresolvedSet<16> Functions;
7930 OverloadedOperatorKind OverOp
7931 = BinaryOperator::getOverloadedOperator(Opc);
7932 if (S && OverOp != OO_None)
7933 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
7934 Functions);
7935
7936 // Build the (potentially-overloaded, potentially-dependent)
7937 // binary operation.
7938 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
7939 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00007940 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007941
Douglas Gregoreaebc752008-11-06 23:29:22 +00007942 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007943 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00007944}
7945
John McCall60d7b3a2010-08-24 06:29:42 +00007946ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidisb1fa3dc2011-01-05 20:09:36 +00007947 UnaryOperatorKind Opc,
John Wiegley429bb272011-04-08 18:41:53 +00007948 Expr *InputExpr) {
7949 ExprResult Input = Owned(InputExpr);
John McCallf89e55a2010-11-18 06:31:45 +00007950 ExprValueKind VK = VK_RValue;
7951 ExprObjectKind OK = OK_Ordinary;
Reid Spencer5f016e22007-07-11 17:01:13 +00007952 QualType resultType;
7953 switch (Opc) {
John McCall2de56d12010-08-25 11:45:40 +00007954 case UO_PreInc:
7955 case UO_PreDec:
7956 case UO_PostInc:
7957 case UO_PostDec:
John Wiegley429bb272011-04-08 18:41:53 +00007958 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00007959 Opc == UO_PreInc ||
7960 Opc == UO_PostInc,
7961 Opc == UO_PreInc ||
7962 Opc == UO_PreDec);
Reid Spencer5f016e22007-07-11 17:01:13 +00007963 break;
John McCall2de56d12010-08-25 11:45:40 +00007964 case UO_AddrOf:
John Wiegley429bb272011-04-08 18:41:53 +00007965 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00007966 break;
John McCall1de4d4e2011-04-07 08:22:57 +00007967 case UO_Deref: {
John McCallfb8721c2011-04-10 19:13:55 +00007968 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall1de4d4e2011-04-07 08:22:57 +00007969 if (!resolved.isUsable()) return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00007970 Input = move(resolved);
7971 Input = DefaultFunctionArrayLvalueConversion(Input.take());
7972 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00007973 break;
John McCall1de4d4e2011-04-07 08:22:57 +00007974 }
John McCall2de56d12010-08-25 11:45:40 +00007975 case UO_Plus:
7976 case UO_Minus:
John Wiegley429bb272011-04-08 18:41:53 +00007977 Input = UsualUnaryConversions(Input.take());
7978 if (Input.isInvalid()) return ExprError();
7979 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00007980 if (resultType->isDependentType())
7981 break;
Douglas Gregor00619622010-06-22 23:41:02 +00007982 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
7983 resultType->isVectorType())
Douglas Gregor74253732008-11-19 15:42:04 +00007984 break;
7985 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
7986 resultType->isEnumeralType())
7987 break;
7988 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCall2de56d12010-08-25 11:45:40 +00007989 Opc == UO_Plus &&
Douglas Gregor74253732008-11-19 15:42:04 +00007990 resultType->isPointerType())
7991 break;
John McCall2cd11fe2010-10-12 02:09:17 +00007992 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00007993 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00007994 if (Input.isInvalid()) return ExprError();
7995 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00007996 }
Douglas Gregor74253732008-11-19 15:42:04 +00007997
Sebastian Redl0eb23302009-01-19 00:08:26 +00007998 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00007999 << resultType << Input.get()->getSourceRange());
8000
John McCall2de56d12010-08-25 11:45:40 +00008001 case UO_Not: // bitwise complement
John Wiegley429bb272011-04-08 18:41:53 +00008002 Input = UsualUnaryConversions(Input.take());
8003 if (Input.isInvalid()) return ExprError();
8004 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008005 if (resultType->isDependentType())
8006 break;
Chris Lattner02a65142008-07-25 23:52:49 +00008007 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8008 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8009 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00008010 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley429bb272011-04-08 18:41:53 +00008011 << resultType << Input.get()->getSourceRange();
John McCall2cd11fe2010-10-12 02:09:17 +00008012 else if (resultType->hasIntegerRepresentation())
8013 break;
8014 else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008015 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008016 if (Input.isInvalid()) return ExprError();
8017 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008018 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008019 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008020 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008021 }
Reid Spencer5f016e22007-07-11 17:01:13 +00008022 break;
John Wiegley429bb272011-04-08 18:41:53 +00008023
John McCall2de56d12010-08-25 11:45:40 +00008024 case UO_LNot: // logical negation
Reid Spencer5f016e22007-07-11 17:01:13 +00008025 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley429bb272011-04-08 18:41:53 +00008026 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8027 if (Input.isInvalid()) return ExprError();
8028 resultType = Input.get()->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008029 if (resultType->isDependentType())
8030 break;
Abramo Bagnara737d5442011-04-07 09:26:19 +00008031 if (resultType->isScalarType()) {
8032 // C99 6.5.3.3p1: ok, fallthrough;
8033 if (Context.getLangOptions().CPlusPlus) {
8034 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8035 // operand contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00008036 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8037 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara737d5442011-04-07 09:26:19 +00008038 }
John McCall2cd11fe2010-10-12 02:09:17 +00008039 } else if (resultType->isPlaceholderType()) {
John McCallfb8721c2011-04-10 19:13:55 +00008040 Input = CheckPlaceholderExpr(Input.take());
John Wiegley429bb272011-04-08 18:41:53 +00008041 if (Input.isInvalid()) return ExprError();
8042 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall2cd11fe2010-10-12 02:09:17 +00008043 } else {
Sebastian Redl0eb23302009-01-19 00:08:26 +00008044 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley429bb272011-04-08 18:41:53 +00008045 << resultType << Input.get()->getSourceRange());
John McCall2cd11fe2010-10-12 02:09:17 +00008046 }
Douglas Gregorea844f32010-09-20 17:13:33 +00008047
Reid Spencer5f016e22007-07-11 17:01:13 +00008048 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00008049 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis16f744b2011-02-18 20:55:15 +00008050 resultType = Context.getLogicalOperationType();
Reid Spencer5f016e22007-07-11 17:01:13 +00008051 break;
John McCall2de56d12010-08-25 11:45:40 +00008052 case UO_Real:
8053 case UO_Imag:
John McCall09431682010-11-18 19:01:18 +00008054 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCallf89e55a2010-11-18 06:31:45 +00008055 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley429bb272011-04-08 18:41:53 +00008056 if (Input.isInvalid()) return ExprError();
8057 if (Input.get()->getValueKind() != VK_RValue &&
8058 Input.get()->getObjectKind() == OK_Ordinary)
8059 VK = Input.get()->getValueKind();
Chris Lattnerdbb36972007-08-24 21:16:53 +00008060 break;
John McCall2de56d12010-08-25 11:45:40 +00008061 case UO_Extension:
John Wiegley429bb272011-04-08 18:41:53 +00008062 resultType = Input.get()->getType();
8063 VK = Input.get()->getValueKind();
8064 OK = Input.get()->getObjectKind();
Reid Spencer5f016e22007-07-11 17:01:13 +00008065 break;
8066 }
John Wiegley429bb272011-04-08 18:41:53 +00008067 if (resultType.isNull() || Input.isInvalid())
Sebastian Redl0eb23302009-01-19 00:08:26 +00008068 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008069
John Wiegley429bb272011-04-08 18:41:53 +00008070 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCallf89e55a2010-11-18 06:31:45 +00008071 VK, OK, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00008072}
8073
John McCall60d7b3a2010-08-24 06:29:42 +00008074ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall2de56d12010-08-25 11:45:40 +00008075 UnaryOperatorKind Opc,
8076 Expr *Input) {
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00008077 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman957c0942010-09-05 23:15:52 +00008078 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008079 // Find all of the overloaded operators visible from this
8080 // point. We perform both an operator-name lookup from the local
8081 // scope and an argument-dependent lookup based on the types of
8082 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00008083 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008084 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00008085 if (S && OverOp != OO_None)
8086 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8087 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008088
John McCall9ae2f072010-08-23 23:25:46 +00008089 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008090 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008091
John McCall9ae2f072010-08-23 23:25:46 +00008092 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008093}
8094
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008095// Unary Operators. 'Tok' is the token for the operator.
John McCall60d7b3a2010-08-24 06:29:42 +00008096ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallf4c73712011-01-19 06:33:43 +00008097 tok::TokenKind Op, Expr *Input) {
John McCall9ae2f072010-08-23 23:25:46 +00008098 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00008099}
8100
Steve Naroff1b273c42007-09-16 14:56:35 +00008101/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008102ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattner57ad3782011-02-17 20:34:02 +00008103 LabelDecl *TheDecl) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008104 TheDecl->setUsed();
Reid Spencer5f016e22007-07-11 17:01:13 +00008105 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerad8dcf42011-02-17 07:39:24 +00008106 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008107 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00008108}
8109
John McCallf85e1932011-06-15 23:02:42 +00008110/// Given the last statement in a statement-expression, check whether
8111/// the result is a producing expression (like a call to an
8112/// ns_returns_retained function) and, if so, rebuild it to hoist the
8113/// release out of the full-expression. Otherwise, return null.
8114/// Cannot fail.
8115static Expr *maybeRebuildARCConsumingStmt(Stmt *s) {
8116 // Should always be wrapped with one of these.
8117 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(s);
8118 if (!cleanups) return 0;
8119
8120 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
8121 if (!cast || cast->getCastKind() != CK_ObjCConsumeObject)
8122 return 0;
8123
8124 // Splice out the cast. This shouldn't modify any interesting
8125 // features of the statement.
8126 Expr *producer = cast->getSubExpr();
8127 assert(producer->getType() == cast->getType());
8128 assert(producer->getValueKind() == cast->getValueKind());
8129 cleanups->setSubExpr(producer);
8130 return cleanups;
8131}
8132
John McCall60d7b3a2010-08-24 06:29:42 +00008133ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008134Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008135 SourceLocation RPLoc) { // "({..})"
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008136 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8137 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8138
Douglas Gregordd8f5692010-03-10 04:54:39 +00008139 bool isFileScope
8140 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00008141 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00008142 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00008143
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008144 // FIXME: there are a variety of strange constraints to enforce here, for
8145 // example, it is not possible to goto into a stmt expression apparently.
8146 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00008147
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008148 // If there are sub stmts in the compound stmt, take the type of the last one
8149 // as the type of the stmtexpr.
8150 QualType Ty = Context.VoidTy;
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008151 bool StmtExprMayBindToTemp = false;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008152 if (!Compound->body_empty()) {
8153 Stmt *LastStmt = Compound->body_back();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008154 LabelStmt *LastLabelStmt = 0;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008155 // If LastStmt is a label, skip down through into the body.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008156 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8157 LastLabelStmt = Label;
Chris Lattner611b2ec2008-07-26 19:51:01 +00008158 LastStmt = Label->getSubStmt();
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008159 }
John McCallf85e1932011-06-15 23:02:42 +00008160
John Wiegley429bb272011-04-08 18:41:53 +00008161 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCallf6a16482010-12-04 03:47:34 +00008162 // Do function/array conversion on the last expression, but not
8163 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley429bb272011-04-08 18:41:53 +00008164 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8165 if (LastExpr.isInvalid())
8166 return ExprError();
8167 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCallf6a16482010-12-04 03:47:34 +00008168
John Wiegley429bb272011-04-08 18:41:53 +00008169 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCallf85e1932011-06-15 23:02:42 +00008170 // In ARC, if the final expression ends in a consume, splice
8171 // the consume out and bind it later. In the alternate case
8172 // (when dealing with a retainable type), the result
8173 // initialization will create a produce. In both cases the
8174 // result will be +1, and we'll need to balance that out with
8175 // a bind.
8176 if (Expr *rebuiltLastStmt
8177 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8178 LastExpr = rebuiltLastStmt;
8179 } else {
8180 LastExpr = PerformCopyInitialization(
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008181 InitializedEntity::InitializeResult(LPLoc,
8182 Ty,
8183 false),
8184 SourceLocation(),
John McCallf85e1932011-06-15 23:02:42 +00008185 LastExpr);
8186 }
8187
John Wiegley429bb272011-04-08 18:41:53 +00008188 if (LastExpr.isInvalid())
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008189 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008190 if (LastExpr.get() != 0) {
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008191 if (!LastLabelStmt)
John Wiegley429bb272011-04-08 18:41:53 +00008192 Compound->setLastStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008193 else
John Wiegley429bb272011-04-08 18:41:53 +00008194 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008195 StmtExprMayBindToTemp = true;
8196 }
8197 }
8198 }
Chris Lattner611b2ec2008-07-26 19:51:01 +00008199 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008200
Eli Friedmanb1d796d2009-03-23 00:24:07 +00008201 // FIXME: Check that expression type is complete/non-abstract; statement
8202 // expressions are not lvalues.
Fariborz Jahaniane946fc82010-10-25 23:27:26 +00008203 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8204 if (StmtExprMayBindToTemp)
8205 return MaybeBindToTemporary(ResStmtExpr);
8206 return Owned(ResStmtExpr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +00008207}
Steve Naroffd34e9152007-08-01 22:05:33 +00008208
John McCall60d7b3a2010-08-24 06:29:42 +00008209ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008210 TypeSourceInfo *TInfo,
8211 OffsetOfComponent *CompPtr,
8212 unsigned NumComponents,
8213 SourceLocation RParenLoc) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008214 QualType ArgTy = TInfo->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00008215 bool Dependent = ArgTy->isDependentType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008216 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008217
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008218 // We must have at least one component that refers to the type, and the first
8219 // one is known to be a field designator. Verify that the ArgTy represents
8220 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00008221 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008222 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8223 << ArgTy << TypeRange);
8224
8225 // Type must be complete per C99 7.17p3 because a declaring a variable
8226 // with an incomplete type would be ill-formed.
8227 if (!Dependent
8228 && RequireCompleteType(BuiltinLoc, ArgTy,
8229 PDiag(diag::err_offsetof_incomplete_type)
8230 << TypeRange))
8231 return ExprError();
8232
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008233 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8234 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00008235 // FIXME: This diagnostic isn't actually visible because the location is in
8236 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00008237 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00008238 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8239 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008240
8241 bool DidWarnAboutNonPOD = false;
8242 QualType CurrentType = ArgTy;
8243 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008244 SmallVector<OffsetOfNode, 4> Comps;
8245 SmallVector<Expr*, 4> Exprs;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008246 for (unsigned i = 0; i != NumComponents; ++i) {
8247 const OffsetOfComponent &OC = CompPtr[i];
8248 if (OC.isBrackets) {
8249 // Offset of an array sub-field. TODO: Should we allow vector elements?
8250 if (!CurrentType->isDependentType()) {
8251 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8252 if(!AT)
8253 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8254 << CurrentType);
8255 CurrentType = AT->getElementType();
8256 } else
8257 CurrentType = Context.DependentTy;
8258
8259 // The expression must be an integral expression.
8260 // FIXME: An integral constant expression?
8261 Expr *Idx = static_cast<Expr*>(OC.U.E);
8262 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8263 !Idx->getType()->isIntegerType())
8264 return ExprError(Diag(Idx->getLocStart(),
8265 diag::err_typecheck_subscript_not_integer)
8266 << Idx->getSourceRange());
8267
8268 // Record this array index.
8269 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8270 Exprs.push_back(Idx);
8271 continue;
8272 }
8273
8274 // Offset of a field.
8275 if (CurrentType->isDependentType()) {
8276 // We have the offset of a field, but we can't look into the dependent
8277 // type. Just record the identifier of the field.
8278 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8279 CurrentType = Context.DependentTy;
8280 continue;
8281 }
8282
8283 // We need to have a complete type to look into.
8284 if (RequireCompleteType(OC.LocStart, CurrentType,
8285 diag::err_offsetof_incomplete_type))
8286 return ExprError();
8287
8288 // Look for the designated field.
8289 const RecordType *RC = CurrentType->getAs<RecordType>();
8290 if (!RC)
8291 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8292 << CurrentType);
8293 RecordDecl *RD = RC->getDecl();
8294
8295 // C++ [lib.support.types]p5:
8296 // The macro offsetof accepts a restricted set of type arguments in this
8297 // International Standard. type shall be a POD structure or a POD union
8298 // (clause 9).
8299 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8300 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek762696f2011-02-23 01:51:43 +00008301 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008302 PDiag(diag::warn_offsetof_non_pod_type)
8303 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8304 << CurrentType))
8305 DidWarnAboutNonPOD = true;
8306 }
8307
8308 // Look for the field.
8309 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8310 LookupQualifiedName(R, RD);
8311 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet87c2e122010-11-21 06:08:52 +00008312 IndirectFieldDecl *IndirectMemberDecl = 0;
8313 if (!MemberDecl) {
Benjamin Kramerd9811462010-11-21 14:11:41 +00008314 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet87c2e122010-11-21 06:08:52 +00008315 MemberDecl = IndirectMemberDecl->getAnonField();
8316 }
8317
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008318 if (!MemberDecl)
8319 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8320 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8321 OC.LocEnd));
8322
Douglas Gregor9d5d60f2010-04-28 22:36:06 +00008323 // C99 7.17p3:
8324 // (If the specified member is a bit-field, the behavior is undefined.)
8325 //
8326 // We diagnose this as an error.
8327 if (MemberDecl->getBitWidth()) {
8328 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8329 << MemberDecl->getDeclName()
8330 << SourceRange(BuiltinLoc, RParenLoc);
8331 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8332 return ExprError();
8333 }
Eli Friedman19410a72010-08-05 10:11:36 +00008334
8335 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet87c2e122010-11-21 06:08:52 +00008336 if (IndirectMemberDecl)
8337 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman19410a72010-08-05 10:11:36 +00008338
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008339 // If the member was found in a base class, introduce OffsetOfNodes for
8340 // the base class indirections.
8341 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8342 /*DetectVirtual=*/false);
Eli Friedman19410a72010-08-05 10:11:36 +00008343 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00008344 CXXBasePath &Path = Paths.front();
8345 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8346 B != BEnd; ++B)
8347 Comps.push_back(OffsetOfNode(B->Base));
8348 }
Eli Friedman19410a72010-08-05 10:11:36 +00008349
Francois Pichet87c2e122010-11-21 06:08:52 +00008350 if (IndirectMemberDecl) {
8351 for (IndirectFieldDecl::chain_iterator FI =
8352 IndirectMemberDecl->chain_begin(),
8353 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8354 assert(isa<FieldDecl>(*FI));
8355 Comps.push_back(OffsetOfNode(OC.LocStart,
8356 cast<FieldDecl>(*FI), OC.LocEnd));
8357 }
8358 } else
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008359 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet87c2e122010-11-21 06:08:52 +00008360
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008361 CurrentType = MemberDecl->getType().getNonReferenceType();
8362 }
8363
8364 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8365 TInfo, Comps.data(), Comps.size(),
8366 Exprs.data(), Exprs.size(), RParenLoc));
8367}
Mike Stumpeed9cac2009-02-19 03:04:26 +00008368
John McCall60d7b3a2010-08-24 06:29:42 +00008369ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall2cd11fe2010-10-12 02:09:17 +00008370 SourceLocation BuiltinLoc,
8371 SourceLocation TypeLoc,
8372 ParsedType argty,
8373 OffsetOfComponent *CompPtr,
8374 unsigned NumComponents,
8375 SourceLocation RPLoc) {
8376
Douglas Gregor8ecdb652010-04-28 22:16:22 +00008377 TypeSourceInfo *ArgTInfo;
8378 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8379 if (ArgTy.isNull())
8380 return ExprError();
8381
Eli Friedman5a15dc12010-08-05 10:15:45 +00008382 if (!ArgTInfo)
8383 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8384
8385 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8386 RPLoc);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00008387}
8388
8389
John McCall60d7b3a2010-08-24 06:29:42 +00008390ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall2cd11fe2010-10-12 02:09:17 +00008391 Expr *CondExpr,
8392 Expr *LHSExpr, Expr *RHSExpr,
8393 SourceLocation RPLoc) {
Steve Naroffd04fdd52007-08-03 21:21:27 +00008394 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8395
John McCallf89e55a2010-11-18 06:31:45 +00008396 ExprValueKind VK = VK_RValue;
8397 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl28507842009-02-26 14:39:58 +00008398 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00008399 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00008400 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00008401 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00008402 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00008403 } else {
8404 // The conditional expression is required to be a constant expression.
8405 llvm::APSInt condEval(32);
8406 SourceLocation ExpLoc;
8407 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00008408 return ExprError(Diag(ExpLoc,
8409 diag::err_typecheck_choose_expr_requires_constant)
8410 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00008411
Sebastian Redl28507842009-02-26 14:39:58 +00008412 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCallf89e55a2010-11-18 06:31:45 +00008413 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8414
8415 resType = ActiveExpr->getType();
8416 ValueDependent = ActiveExpr->isValueDependent();
8417 VK = ActiveExpr->getValueKind();
8418 OK = ActiveExpr->getObjectKind();
Sebastian Redl28507842009-02-26 14:39:58 +00008419 }
8420
Sebastian Redlf53597f2009-03-15 17:47:39 +00008421 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCallf89e55a2010-11-18 06:31:45 +00008422 resType, VK, OK, RPLoc,
Douglas Gregorce940492009-09-25 04:25:58 +00008423 resType->isDependentType(),
8424 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00008425}
8426
Steve Naroff4eb206b2008-09-03 18:15:37 +00008427//===----------------------------------------------------------------------===//
8428// Clang Extensions.
8429//===----------------------------------------------------------------------===//
8430
8431/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00008432void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008433 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8434 PushBlockScope(BlockScope, Block);
8435 CurContext->addDecl(Block);
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008436 if (BlockScope)
8437 PushDeclContext(BlockScope, Block);
8438 else
8439 CurContext = Block;
Steve Naroff090276f2008-10-10 01:28:17 +00008440}
8441
Mike Stump98eb8a72009-02-04 22:31:32 +00008442void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00008443 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall711c52b2011-01-05 12:14:39 +00008444 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008445 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008446
John McCallbf1a0282010-06-04 23:28:52 +00008447 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCallbf1a0282010-06-04 23:28:52 +00008448 QualType T = Sig->getType();
Mike Stump98eb8a72009-02-04 22:31:32 +00008449
John McCall711c52b2011-01-05 12:14:39 +00008450 // GetTypeForDeclarator always produces a function type for a block
8451 // literal signature. Furthermore, it is always a FunctionProtoType
8452 // unless the function was written with a typedef.
8453 assert(T->isFunctionType() &&
8454 "GetTypeForDeclarator made a non-function block signature");
8455
8456 // Look for an explicit signature in that function type.
8457 FunctionProtoTypeLoc ExplicitSignature;
8458
8459 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8460 if (isa<FunctionProtoTypeLoc>(tmp)) {
8461 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8462
8463 // Check whether that explicit signature was synthesized by
8464 // GetTypeForDeclarator. If so, don't save that as part of the
8465 // written signature.
Abramo Bagnara796aa442011-03-12 11:17:06 +00008466 if (ExplicitSignature.getLocalRangeBegin() ==
8467 ExplicitSignature.getLocalRangeEnd()) {
John McCall711c52b2011-01-05 12:14:39 +00008468 // This would be much cheaper if we stored TypeLocs instead of
8469 // TypeSourceInfos.
8470 TypeLoc Result = ExplicitSignature.getResultLoc();
8471 unsigned Size = Result.getFullDataSize();
8472 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8473 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8474
8475 ExplicitSignature = FunctionProtoTypeLoc();
8476 }
John McCall82dc0092010-06-04 11:21:44 +00008477 }
Mike Stump1eb44332009-09-09 15:08:12 +00008478
John McCall711c52b2011-01-05 12:14:39 +00008479 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8480 CurBlock->FunctionType = T;
8481
8482 const FunctionType *Fn = T->getAs<FunctionType>();
8483 QualType RetTy = Fn->getResultType();
8484 bool isVariadic =
8485 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8486
John McCallc71a4912010-06-04 19:02:56 +00008487 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregora873dfc2010-02-03 00:27:59 +00008488
John McCall82dc0092010-06-04 11:21:44 +00008489 // Don't allow returning a objc interface by value.
8490 if (RetTy->isObjCObjectType()) {
8491 Diag(ParamInfo.getSourceRange().getBegin(),
8492 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8493 return;
8494 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008495
John McCall82dc0092010-06-04 11:21:44 +00008496 // Context.DependentTy is used as a placeholder for a missing block
John McCallc71a4912010-06-04 19:02:56 +00008497 // return type. TODO: what should we do with declarators like:
8498 // ^ * { ... }
8499 // If the answer is "apply template argument deduction"....
John McCall82dc0092010-06-04 11:21:44 +00008500 if (RetTy != Context.DependentTy)
8501 CurBlock->ReturnType = RetTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008502
John McCall82dc0092010-06-04 11:21:44 +00008503 // Push block parameters from the declarator if we had them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008504 SmallVector<ParmVarDecl*, 8> Params;
John McCall711c52b2011-01-05 12:14:39 +00008505 if (ExplicitSignature) {
8506 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8507 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008508 if (Param->getIdentifier() == 0 &&
8509 !Param->isImplicit() &&
8510 !Param->isInvalidDecl() &&
8511 !getLangOptions().CPlusPlus)
8512 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCallc71a4912010-06-04 19:02:56 +00008513 Params.push_back(Param);
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00008514 }
John McCall82dc0092010-06-04 11:21:44 +00008515
8516 // Fake up parameter variables if we have a typedef, like
8517 // ^ fntype { ... }
8518 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8519 for (FunctionProtoType::arg_type_iterator
8520 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8521 ParmVarDecl *Param =
8522 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8523 ParamInfo.getSourceRange().getBegin(),
8524 *I);
John McCallc71a4912010-06-04 19:02:56 +00008525 Params.push_back(Param);
John McCall82dc0092010-06-04 11:21:44 +00008526 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008527 }
John McCall82dc0092010-06-04 11:21:44 +00008528
John McCallc71a4912010-06-04 19:02:56 +00008529 // Set the parameters on the block decl.
Douglas Gregor82aa7132010-11-01 18:37:59 +00008530 if (!Params.empty()) {
John McCallc71a4912010-06-04 19:02:56 +00008531 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregor82aa7132010-11-01 18:37:59 +00008532 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8533 CurBlock->TheDecl->param_end(),
8534 /*CheckParameterNames=*/false);
8535 }
8536
John McCall82dc0092010-06-04 11:21:44 +00008537 // Finally we can process decl attributes.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00008538 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00008539
John McCallc71a4912010-06-04 19:02:56 +00008540 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCall82dc0092010-06-04 11:21:44 +00008541 Diag(ParamInfo.getAttributes()->getLoc(),
8542 diag::warn_attribute_sentinel_not_variadic) << 1;
8543 // FIXME: remove the attribute.
8544 }
8545
8546 // Put the parameter variables in scope. We can bail out immediately
8547 // if we don't have any.
John McCallc71a4912010-06-04 19:02:56 +00008548 if (Params.empty())
John McCall82dc0092010-06-04 11:21:44 +00008549 return;
8550
Steve Naroff090276f2008-10-10 01:28:17 +00008551 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00008552 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8553 (*AI)->setOwningFunction(CurBlock->TheDecl);
8554
Steve Naroff090276f2008-10-10 01:28:17 +00008555 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00008556 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00008557 CheckShadow(CurBlock->TheScope, *AI);
John McCall053f4bd2010-03-22 09:20:08 +00008558
Steve Naroff090276f2008-10-10 01:28:17 +00008559 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00008560 }
John McCall7a9813c2010-01-22 00:28:27 +00008561 }
Steve Naroff4eb206b2008-09-03 18:15:37 +00008562}
8563
8564/// ActOnBlockError - If there is an error parsing a block, this callback
8565/// is invoked to pop the information about the block from the action impl.
8566void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00008567 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00008568 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008569 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008570}
8571
8572/// ActOnBlockStmtExpr - This is called when the body of a block statement
8573/// literal was successfully completed. ^(int x){...}
John McCall60d7b3a2010-08-24 06:29:42 +00008574ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattnere476bdc2011-02-17 23:58:47 +00008575 Stmt *Body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00008576 // If blocks are disabled, emit an error.
8577 if (!LangOpts.Blocks)
8578 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00008579
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008580 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahaniana729da22010-07-09 18:44:02 +00008581
Steve Naroff090276f2008-10-10 01:28:17 +00008582 PopDeclContext();
8583
Steve Naroff4eb206b2008-09-03 18:15:37 +00008584 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00008585 if (!BSI->ReturnType.isNull())
8586 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00008587
Mike Stump56925862009-07-28 22:04:01 +00008588 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00008589 QualType BlockTy;
John McCallc71a4912010-06-04 19:02:56 +00008590
John McCall469a1eb2011-02-02 13:00:07 +00008591 // Set the captured variables on the block.
John McCall6b5a61b2011-02-07 10:33:21 +00008592 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8593 BSI->CapturesCXXThis);
John McCall469a1eb2011-02-02 13:00:07 +00008594
John McCallc71a4912010-06-04 19:02:56 +00008595 // If the user wrote a function type in some form, try to use that.
8596 if (!BSI->FunctionType.isNull()) {
8597 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8598
8599 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8600 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8601
8602 // Turn protoless block types into nullary block types.
8603 if (isa<FunctionNoProtoType>(FTy)) {
John McCalle23cf432010-12-14 08:05:40 +00008604 FunctionProtoType::ExtProtoInfo EPI;
8605 EPI.ExtInfo = Ext;
8606 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008607
8608 // Otherwise, if we don't need to change anything about the function type,
8609 // preserve its sugar structure.
8610 } else if (FTy->getResultType() == RetTy &&
8611 (!NoReturn || FTy->getNoReturnAttr())) {
8612 BlockTy = BSI->FunctionType;
8613
8614 // Otherwise, make the minimal modifications to the function type.
8615 } else {
8616 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalle23cf432010-12-14 08:05:40 +00008617 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8618 EPI.TypeQuals = 0; // FIXME: silently?
8619 EPI.ExtInfo = Ext;
John McCallc71a4912010-06-04 19:02:56 +00008620 BlockTy = Context.getFunctionType(RetTy,
8621 FPT->arg_type_begin(),
8622 FPT->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00008623 EPI);
John McCallc71a4912010-06-04 19:02:56 +00008624 }
8625
8626 // If we don't have a function type, just build one from nothing.
8627 } else {
John McCalle23cf432010-12-14 08:05:40 +00008628 FunctionProtoType::ExtProtoInfo EPI;
John McCallf85e1932011-06-15 23:02:42 +00008629 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00008630 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCallc71a4912010-06-04 19:02:56 +00008631 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008632
John McCallc71a4912010-06-04 19:02:56 +00008633 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8634 BSI->TheDecl->param_end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00008635 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008636
Chris Lattner17a78302009-04-19 05:28:12 +00008637 // If needed, diagnose invalid gotos and switches in the block.
John McCallf85e1932011-06-15 23:02:42 +00008638 if (getCurFunction()->NeedsScopeChecking() &&
8639 !hasAnyUnrecoverableErrorsInThisFunction())
John McCall9ae2f072010-08-23 23:25:46 +00008640 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump1eb44332009-09-09 15:08:12 +00008641
Chris Lattnere476bdc2011-02-17 23:58:47 +00008642 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008643
Fariborz Jahanian4e7c7f22011-07-11 18:04:54 +00008644 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8645 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8646 const VarDecl *variable = ci->getVariable();
8647 QualType T = variable->getType();
8648 QualType::DestructionKind destructKind = T.isDestructedType();
8649 if (destructKind != QualType::DK_none)
8650 getCurFunction()->setHasBranchProtectedScope();
8651 }
8652
Benjamin Kramerd2486192011-07-12 14:11:05 +00008653 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8654 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8655 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8656
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00008657 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00008658}
8659
John McCall60d7b3a2010-08-24 06:29:42 +00008660ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallb3d87482010-08-24 05:47:05 +00008661 Expr *expr, ParsedType type,
Sebastian Redlf53597f2009-03-15 17:47:39 +00008662 SourceLocation RPLoc) {
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008663 TypeSourceInfo *TInfo;
Jeffrey Yasskindec09842011-01-18 02:00:16 +00008664 GetTypeFromParser(type, &TInfo);
John McCall9ae2f072010-08-23 23:25:46 +00008665 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008666}
8667
John McCall60d7b3a2010-08-24 06:29:42 +00008668ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCallf89e55a2010-11-18 06:31:45 +00008669 Expr *E, TypeSourceInfo *TInfo,
8670 SourceLocation RPLoc) {
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008671 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00008672
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008673 // Get the va_list type
8674 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008675 if (VaListType->isArrayType()) {
8676 // Deal with implicit array decay; for example, on x86-64,
8677 // va_list is an array, but it's supposed to decay to
8678 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008679 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00008680 // Make sure the input expression also decays appropriately.
John Wiegley429bb272011-04-08 18:41:53 +00008681 ExprResult Result = UsualUnaryConversions(E);
8682 if (Result.isInvalid())
8683 return ExprError();
8684 E = Result.take();
Eli Friedman5c091ba2009-05-16 12:46:54 +00008685 } else {
8686 // Otherwise, the va_list argument must be an l-value because
8687 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00008688 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00008689 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00008690 return ExprError();
8691 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00008692
Douglas Gregordd027302009-05-19 23:10:31 +00008693 if (!E->isTypeDependent() &&
8694 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00008695 return ExprError(Diag(E->getLocStart(),
8696 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00008697 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00008698 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008699
David Majnemer0adde122011-06-14 05:17:32 +00008700 if (!TInfo->getType()->isDependentType()) {
8701 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8702 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8703 << TInfo->getTypeLoc().getSourceRange()))
8704 return ExprError();
David Majnemerdb11b012011-06-13 06:37:03 +00008705
David Majnemer0adde122011-06-14 05:17:32 +00008706 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8707 TInfo->getType(),
8708 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8709 << TInfo->getTypeLoc().getSourceRange()))
8710 return ExprError();
8711
Douglas Gregor4eb75222011-07-30 06:45:27 +00008712 if (!TInfo->getType().isPODType(Context)) {
David Majnemer0adde122011-06-14 05:17:32 +00008713 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor4eb75222011-07-30 06:45:27 +00008714 TInfo->getType()->isObjCLifetimeType()
8715 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8716 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemer0adde122011-06-14 05:17:32 +00008717 << TInfo->getType()
8718 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor4eb75222011-07-30 06:45:27 +00008719 }
Eli Friedman46d37c12011-07-11 21:45:59 +00008720
8721 // Check for va_arg where arguments of the given type will be promoted
8722 // (i.e. this va_arg is guaranteed to have undefined behavior).
8723 QualType PromoteType;
8724 if (TInfo->getType()->isPromotableIntegerType()) {
8725 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8726 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8727 PromoteType = QualType();
8728 }
8729 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8730 PromoteType = Context.DoubleTy;
8731 if (!PromoteType.isNull())
8732 Diag(TInfo->getTypeLoc().getBeginLoc(),
8733 diag::warn_second_parameter_to_va_arg_never_compatible)
8734 << TInfo->getType()
8735 << PromoteType
8736 << TInfo->getTypeLoc().getSourceRange();
David Majnemer0adde122011-06-14 05:17:32 +00008737 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008738
Abramo Bagnara2cad9002010-08-10 10:06:15 +00008739 QualType T = TInfo->getType().getNonLValueExprType(Context);
8740 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00008741}
8742
John McCall60d7b3a2010-08-24 06:29:42 +00008743ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008744 // The type of __null will be int or long, depending on the size of
8745 // pointers on the target.
8746 QualType Ty;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008747 unsigned pw = Context.Target.getPointerWidth(0);
8748 if (pw == Context.Target.getIntWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008749 Ty = Context.IntTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008750 else if (pw == Context.Target.getLongWidth())
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008751 Ty = Context.LongTy;
NAKAMURA Takumi6e5658d2011-01-19 00:11:41 +00008752 else if (pw == Context.Target.getLongLongWidth())
8753 Ty = Context.LongLongTy;
8754 else {
8755 assert(!"I don't know size of pointer!");
8756 Ty = Context.IntTy;
8757 }
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008758
Sebastian Redlf53597f2009-03-15 17:47:39 +00008759 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00008760}
8761
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008762static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregor849b2432010-03-31 17:46:05 +00008763 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008764 if (!SemaRef.getLangOptions().ObjC1)
8765 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008766
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008767 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8768 if (!PT)
8769 return;
8770
8771 // Check if the destination is of type 'id'.
8772 if (!PT->isObjCIdType()) {
8773 // Check if the destination is the 'NSString' interface.
8774 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8775 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8776 return;
8777 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008778
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008779 // Strip off any parens and casts.
8780 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregor5cee1192011-07-27 05:40:30 +00008781 if (!SL || !SL->isAscii())
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008782 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008783
Douglas Gregor849b2432010-03-31 17:46:05 +00008784 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00008785}
8786
Chris Lattner5cf216b2008-01-04 18:04:52 +00008787bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8788 SourceLocation Loc,
8789 QualType DstType, QualType SrcType,
Douglas Gregora41a8c52010-04-22 00:20:18 +00008790 Expr *SrcExpr, AssignmentAction Action,
8791 bool *Complained) {
8792 if (Complained)
8793 *Complained = false;
8794
Chris Lattner5cf216b2008-01-04 18:04:52 +00008795 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor926df6c2011-06-11 01:09:30 +00008796 bool CheckInferredResultType = false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008797 bool isInvalid = false;
8798 unsigned DiagKind;
Douglas Gregor849b2432010-03-31 17:46:05 +00008799 FixItHint Hint;
Anna Zaks67221552011-07-28 19:51:27 +00008800 ConversionFixItGenerator ConvHints;
8801 bool MayHaveConvFixit = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008802
Chris Lattner5cf216b2008-01-04 18:04:52 +00008803 switch (ConvTy) {
8804 default: assert(0 && "Unknown conversion type");
8805 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008806 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00008807 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks67221552011-07-28 19:51:27 +00008808 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8809 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008810 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008811 case IntToPointer:
8812 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks67221552011-07-28 19:51:27 +00008813 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8814 MayHaveConvFixit = true;
Chris Lattnerb7b61152008-01-04 18:22:42 +00008815 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008816 case IncompatiblePointer:
Douglas Gregor849b2432010-03-31 17:46:05 +00008817 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00008818 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor926df6c2011-06-11 01:09:30 +00008819 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
8820 SrcType->isObjCObjectPointerType();
Anna Zaks67221552011-07-28 19:51:27 +00008821 if (Hint.isNull() && !CheckInferredResultType) {
8822 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8823 }
8824 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008825 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00008826 case IncompatiblePointerSign:
8827 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8828 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008829 case FunctionVoidPointer:
8830 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8831 break;
John McCall86c05f32011-02-01 00:10:29 +00008832 case IncompatiblePointerDiscardsQualifiers: {
John McCall40249e72011-02-01 23:28:01 +00008833 // Perform array-to-pointer decay if necessary.
8834 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8835
John McCall86c05f32011-02-01 00:10:29 +00008836 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8837 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8838 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8839 DiagKind = diag::err_typecheck_incompatible_address_space;
8840 break;
John McCallf85e1932011-06-15 23:02:42 +00008841
8842
8843 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008844 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCallf85e1932011-06-15 23:02:42 +00008845 break;
John McCall86c05f32011-02-01 00:10:29 +00008846 }
8847
8848 llvm_unreachable("unknown error case for discarding qualifiers!");
8849 // fallthrough
8850 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00008851 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00008852 // If the qualifiers lost were because we were applying the
8853 // (deprecated) C++ conversion from a string literal to a char*
8854 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8855 // Ideally, this check would be performed in
John McCalle4be87e2011-01-31 23:13:11 +00008856 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregor77a52232008-09-12 00:47:35 +00008857 // bit of refactoring (so that the second argument is an
8858 // expression, rather than a type), which should be done as part
John McCalle4be87e2011-01-31 23:13:11 +00008859 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregor77a52232008-09-12 00:47:35 +00008860 // C++ semantics.
8861 if (getLangOptions().CPlusPlus &&
8862 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8863 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008864 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8865 break;
Sean Huntc9132b62009-11-08 07:46:34 +00008866 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00008867 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00008868 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00008869 case IntToBlockPointer:
8870 DiagKind = diag::err_int_to_block_pointer;
8871 break;
8872 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00008873 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00008874 break;
Steve Naroff39579072008-10-14 22:18:38 +00008875 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00008876 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00008877 // it can give a more specific diagnostic.
8878 DiagKind = diag::warn_incompatible_qualified_id;
8879 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00008880 case IncompatibleVectors:
8881 DiagKind = diag::warn_incompatible_vectors;
8882 break;
Fariborz Jahanian04e5a252011-07-07 18:55:47 +00008883 case IncompatibleObjCWeakRef:
8884 DiagKind = diag::err_arc_weak_unavailable_assign;
8885 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008886 case Incompatible:
8887 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks67221552011-07-28 19:51:27 +00008888 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8889 MayHaveConvFixit = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008890 isInvalid = true;
8891 break;
8892 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008893
Douglas Gregord4eea832010-04-09 00:35:39 +00008894 QualType FirstType, SecondType;
8895 switch (Action) {
8896 case AA_Assigning:
8897 case AA_Initializing:
8898 // The destination type comes first.
8899 FirstType = DstType;
8900 SecondType = SrcType;
8901 break;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008902
Douglas Gregord4eea832010-04-09 00:35:39 +00008903 case AA_Returning:
8904 case AA_Passing:
8905 case AA_Converting:
8906 case AA_Sending:
8907 case AA_Casting:
8908 // The source type comes first.
8909 FirstType = SrcType;
8910 SecondType = DstType;
8911 break;
8912 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00008913
Anna Zaks67221552011-07-28 19:51:27 +00008914 PartialDiagnostic FDiag = PDiag(DiagKind);
8915 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
8916
8917 // If we can fix the conversion, suggest the FixIts.
8918 assert(ConvHints.isNull() || Hint.isNull());
8919 if (!ConvHints.isNull()) {
8920 for (llvm::SmallVector<FixItHint, 1>::iterator
8921 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
8922 HI != HE; ++HI)
8923 FDiag << *HI;
8924 } else {
8925 FDiag << Hint;
8926 }
8927 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
8928
8929 Diag(Loc, FDiag);
8930
Douglas Gregor926df6c2011-06-11 01:09:30 +00008931 if (CheckInferredResultType)
8932 EmitRelatedResultTypeNote(SrcExpr);
8933
Douglas Gregora41a8c52010-04-22 00:20:18 +00008934 if (Complained)
8935 *Complained = true;
Chris Lattner5cf216b2008-01-04 18:04:52 +00008936 return isInvalid;
8937}
Anders Carlssone21555e2008-11-30 19:50:32 +00008938
Chris Lattner3bf68932009-04-25 21:59:05 +00008939bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00008940 llvm::APSInt ICEResult;
8941 if (E->isIntegerConstantExpr(ICEResult, Context)) {
8942 if (Result)
8943 *Result = ICEResult;
8944 return false;
8945 }
8946
Anders Carlssone21555e2008-11-30 19:50:32 +00008947 Expr::EvalResult EvalResult;
8948
Mike Stumpeed9cac2009-02-19 03:04:26 +00008949 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00008950 EvalResult.HasSideEffects) {
8951 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
8952
8953 if (EvalResult.Diag) {
8954 // We only show the note if it's not the usual "invalid subexpression"
8955 // or if it's actually in a subexpression.
8956 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
8957 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
8958 Diag(EvalResult.DiagLoc, EvalResult.Diag);
8959 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00008960
Anders Carlssone21555e2008-11-30 19:50:32 +00008961 return true;
8962 }
8963
Eli Friedman3b5ccca2009-04-25 22:26:58 +00008964 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
8965 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00008966
Eli Friedman3b5ccca2009-04-25 22:26:58 +00008967 if (EvalResult.Diag &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00008968 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
8969 != Diagnostic::Ignored)
Eli Friedman3b5ccca2009-04-25 22:26:58 +00008970 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00008971
Anders Carlssone21555e2008-11-30 19:50:32 +00008972 if (Result)
8973 *Result = EvalResult.Val.getInt();
8974 return false;
8975}
Douglas Gregore0762c92009-06-19 23:52:42 +00008976
Douglas Gregor2afce722009-11-26 00:44:06 +00008977void
Mike Stump1eb44332009-09-09 15:08:12 +00008978Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00008979 ExprEvalContexts.push_back(
John McCallf85e1932011-06-15 23:02:42 +00008980 ExpressionEvaluationContextRecord(NewContext,
8981 ExprTemporaries.size(),
8982 ExprNeedsCleanups));
8983 ExprNeedsCleanups = false;
Douglas Gregorac7610d2009-06-22 20:57:11 +00008984}
8985
Richard Trieu67e29332011-08-02 04:35:43 +00008986void Sema::PopExpressionEvaluationContext() {
Douglas Gregor2afce722009-11-26 00:44:06 +00008987 // Pop the current expression evaluation context off the stack.
8988 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
8989 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00008990
Douglas Gregor06d33692009-12-12 07:57:52 +00008991 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
8992 if (Rec.PotentiallyReferenced) {
8993 // Mark any remaining declarations in the current position of the stack
8994 // as "referenced". If they were not meant to be referenced, semantic
8995 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00008996 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00008997 I = Rec.PotentiallyReferenced->begin(),
8998 IEnd = Rec.PotentiallyReferenced->end();
8999 I != IEnd; ++I)
9000 MarkDeclarationReferenced(I->first, I->second);
9001 }
9002
9003 if (Rec.PotentiallyDiagnosed) {
9004 // Emit any pending diagnostics.
9005 for (PotentiallyEmittedDiagnostics::iterator
9006 I = Rec.PotentiallyDiagnosed->begin(),
9007 IEnd = Rec.PotentiallyDiagnosed->end();
9008 I != IEnd; ++I)
9009 Diag(I->first, I->second);
9010 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009011 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009012
9013 // When are coming out of an unevaluated context, clear out any
9014 // temporaries that we may have created as part of the evaluation of
9015 // the expression in that context: they aren't relevant because they
9016 // will never be constructed.
John McCallf85e1932011-06-15 23:02:42 +00009017 if (Rec.Context == Unevaluated) {
Douglas Gregor2afce722009-11-26 00:44:06 +00009018 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9019 ExprTemporaries.end());
John McCallf85e1932011-06-15 23:02:42 +00009020 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9021
9022 // Otherwise, merge the contexts together.
9023 } else {
9024 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9025 }
Douglas Gregor2afce722009-11-26 00:44:06 +00009026
9027 // Destroy the popped expression evaluation record.
9028 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00009029}
Douglas Gregore0762c92009-06-19 23:52:42 +00009030
John McCallf85e1932011-06-15 23:02:42 +00009031void Sema::DiscardCleanupsInEvaluationContext() {
9032 ExprTemporaries.erase(
9033 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
9034 ExprTemporaries.end());
9035 ExprNeedsCleanups = false;
9036}
9037
Douglas Gregore0762c92009-06-19 23:52:42 +00009038/// \brief Note that the given declaration was referenced in the source code.
9039///
9040/// This routine should be invoke whenever a given declaration is referenced
9041/// in the source code, and where that reference occurred. If this declaration
9042/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9043/// C99 6.9p3), then the declaration will be marked as used.
9044///
9045/// \param Loc the location where the declaration was referenced.
9046///
9047/// \param D the declaration that has been referenced by the source code.
9048void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9049 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00009050
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +00009051 D->setReferenced();
9052
Douglas Gregorc070cc62010-06-17 23:14:26 +00009053 if (D->isUsed(false))
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009054 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009055
Richard Trieu67e29332011-08-02 04:35:43 +00009056 // Mark a parameter or variable declaration "used", regardless of whether
9057 // we're in a template or not. The reason for this is that unevaluated
9058 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9059 // (-Wunused-variables and -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009060 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009061 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson2127ecc2010-10-22 23:37:08 +00009062 D->setUsed();
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009063 return;
9064 }
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009065
Douglas Gregorfc2ca562010-04-07 20:29:57 +00009066 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9067 return;
Sean Hunt1e3f5ba2010-04-28 23:02:27 +00009068
Douglas Gregore0762c92009-06-19 23:52:42 +00009069 // Do not mark anything as "used" within a dependent context; wait for
9070 // an instantiation.
9071 if (CurContext->isDependentContext())
9072 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009073
Douglas Gregor2afce722009-11-26 00:44:06 +00009074 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00009075 case Unevaluated:
9076 // We are in an expression that is not potentially evaluated; do nothing.
9077 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009078
Douglas Gregorac7610d2009-06-22 20:57:11 +00009079 case PotentiallyEvaluated:
9080 // We are in a potentially-evaluated expression, so this declaration is
9081 // "used"; handle this below.
9082 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009083
Douglas Gregorac7610d2009-06-22 20:57:11 +00009084 case PotentiallyPotentiallyEvaluated:
9085 // We are in an expression that may be potentially evaluated; queue this
9086 // declaration reference until we know whether the expression is
9087 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00009088 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00009089 return;
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009090
9091 case PotentiallyEvaluatedIfUsed:
9092 // Referenced declarations will only be used if the construct in the
9093 // containing expression is used.
9094 return;
Douglas Gregorac7610d2009-06-22 20:57:11 +00009095 }
Mike Stump1eb44332009-09-09 15:08:12 +00009096
Douglas Gregore0762c92009-06-19 23:52:42 +00009097 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00009098 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Sean Hunt1e238652011-05-12 03:51:51 +00009099 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor()) {
9100 if (Constructor->isTrivial())
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00009101 return;
9102 if (!Constructor->isUsed(false))
9103 DefineImplicitDefaultConstructor(Loc, Constructor);
Sean Hunt509f0482011-05-14 18:20:50 +00009104 } else if (Constructor->isDefaulted() &&
Sean Hunt49634cf2011-05-13 06:10:58 +00009105 Constructor->isCopyConstructor()) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009106 if (!Constructor->isUsed(false))
Sean Hunt49634cf2011-05-13 06:10:58 +00009107 DefineImplicitCopyConstructor(Loc, Constructor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009108 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009109
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009110 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009111 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00009112 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009113 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009114 if (Destructor->isVirtual())
9115 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009116 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Sean Hunt2b188082011-05-14 05:23:28 +00009117 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009118 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00009119 if (!MethodDecl->isUsed(false))
Douglas Gregor39957dc2010-05-01 15:04:51 +00009120 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009121 } else if (MethodDecl->isVirtual())
9122 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009123 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00009124 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall15e310a2011-02-19 02:53:41 +00009125 // Recursive functions should be marked when used from another function.
9126 if (CurContext == Function) return;
9127
Mike Stump1eb44332009-09-09 15:08:12 +00009128 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00009129 // class templates.
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00009130 if (Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009131 bool AlreadyInstantiated = false;
9132 if (FunctionTemplateSpecializationInfo *SpecInfo
9133 = Function->getTemplateSpecializationInfo()) {
9134 if (SpecInfo->getPointOfInstantiation().isInvalid())
9135 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009136 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009137 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009138 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009139 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009140 = Function->getMemberSpecializationInfo()) {
9141 if (MSInfo->getPointOfInstantiation().isInvalid())
9142 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009143 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00009144 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009145 AlreadyInstantiated = true;
9146 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009147
Douglas Gregor60406be2010-01-16 22:29:39 +00009148 if (!AlreadyInstantiated) {
9149 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9150 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9151 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9152 Loc));
9153 else
Chandler Carruth62c78d52010-08-25 08:44:16 +00009154 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor60406be2010-01-16 22:29:39 +00009155 }
John McCall15e310a2011-02-19 02:53:41 +00009156 } else {
9157 // Walk redefinitions, as some of them may be instantiable.
Gabor Greif40181c42010-08-28 00:16:06 +00009158 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9159 e(Function->redecls_end()); i != e; ++i) {
Gabor Greifbe9ebe32010-08-28 01:58:12 +00009160 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greif40181c42010-08-28 00:16:06 +00009161 MarkDeclarationReferenced(Loc, *i);
9162 }
John McCall15e310a2011-02-19 02:53:41 +00009163 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009164
John McCall15e310a2011-02-19 02:53:41 +00009165 // Keep track of used but undefined functions.
9166 if (!Function->isPure() && !Function->hasBody() &&
9167 Function->getLinkage() != ExternalLinkage) {
9168 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9169 if (old.isInvalid()) old = Loc;
9170 }
Argyrios Kyrtzidis58b52592010-08-25 10:34:54 +00009171
John McCall15e310a2011-02-19 02:53:41 +00009172 Function->setUsed(true);
Douglas Gregore0762c92009-06-19 23:52:42 +00009173 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00009174 }
Mike Stump1eb44332009-09-09 15:08:12 +00009175
Douglas Gregore0762c92009-06-19 23:52:42 +00009176 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00009177 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00009178 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009179 Var->getInstantiatedFromStaticDataMember()) {
9180 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9181 assert(MSInfo && "Missing member specialization information?");
9182 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9183 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9184 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redlf79a7192011-04-29 08:19:30 +00009185 // This is a modification of an existing AST node. Notify listeners.
9186 if (ASTMutationListener *L = getASTMutationListener())
9187 L->StaticDataMemberInstantiated(Var);
Chandler Carruth62c78d52010-08-25 08:44:16 +00009188 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00009189 }
9190 }
Mike Stump1eb44332009-09-09 15:08:12 +00009191
John McCall77efc682011-02-21 19:25:48 +00009192 // Keep track of used but undefined variables. We make a hole in
9193 // the warning for static const data members with in-line
9194 // initializers.
John McCall15e310a2011-02-19 02:53:41 +00009195 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall77efc682011-02-21 19:25:48 +00009196 && Var->getLinkage() != ExternalLinkage
9197 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall15e310a2011-02-19 02:53:41 +00009198 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9199 if (old.isInvalid()) old = Loc;
9200 }
Douglas Gregor7caa6822009-07-24 20:34:43 +00009201
Douglas Gregore0762c92009-06-19 23:52:42 +00009202 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00009203 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00009204 }
Douglas Gregore0762c92009-06-19 23:52:42 +00009205}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009206
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009207namespace {
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009208 // Mark all of the declarations referenced
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009209 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009210 // of when we're entering
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009211 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9212 Sema &S;
9213 SourceLocation Loc;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009214
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009215 public:
9216 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009217
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009218 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009219
9220 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9221 bool TraverseRecordType(RecordType *T);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009222 };
9223}
9224
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009225bool MarkReferencedDecls::TraverseTemplateArgument(
9226 const TemplateArgument &Arg) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009227 if (Arg.getKind() == TemplateArgument::Declaration) {
9228 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9229 }
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009230
9231 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009232}
9233
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009234bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009235 if (ClassTemplateSpecializationDecl *Spec
9236 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9237 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor910f8002010-11-07 23:05:16 +00009238 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009239 }
9240
Chandler Carruthe3e210c2010-06-10 10:31:57 +00009241 return true;
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009242}
9243
9244void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9245 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthdfc35e32010-06-09 08:17:30 +00009246 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregorb4eeaff2010-05-07 23:12:07 +00009247}
9248
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009249namespace {
9250 /// \brief Helper class that marks all of the declarations referenced by
9251 /// potentially-evaluated subexpressions as "referenced".
9252 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9253 Sema &S;
9254
9255 public:
9256 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9257
9258 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9259
9260 void VisitDeclRefExpr(DeclRefExpr *E) {
9261 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9262 }
9263
9264 void VisitMemberExpr(MemberExpr *E) {
9265 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009266 Inherited::VisitMemberExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009267 }
9268
9269 void VisitCXXNewExpr(CXXNewExpr *E) {
9270 if (E->getConstructor())
9271 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9272 if (E->getOperatorNew())
9273 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9274 if (E->getOperatorDelete())
9275 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009276 Inherited::VisitCXXNewExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009277 }
9278
9279 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9280 if (E->getOperatorDelete())
9281 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor5833b0b2010-09-14 22:55:20 +00009282 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9283 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9284 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9285 S.MarkDeclarationReferenced(E->getLocStart(),
9286 S.LookupDestructor(Record));
9287 }
9288
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009289 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009290 }
9291
9292 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9293 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor4fcf5b22010-09-11 23:32:50 +00009294 Inherited::VisitCXXConstructExpr(E);
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009295 }
9296
9297 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9298 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9299 }
Douglas Gregor102ff972010-10-19 17:17:35 +00009300
9301 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9302 Visit(E->getExpr());
9303 }
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009304 };
9305}
9306
9307/// \brief Mark any declarations that appear within this expression or any
9308/// potentially-evaluated subexpressions as "referenced".
9309void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9310 EvaluatedExprMarker(*this).Visit(E);
9311}
9312
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009313/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9314/// of the program being compiled.
9315///
9316/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009317/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009318/// possibility that the code will actually be executable. Code in sizeof()
9319/// expressions, code used only during overload resolution, etc., are not
9320/// potentially evaluated. This routine will suppress such diagnostics or,
9321/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009322/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009323/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009324///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009325/// This routine should be used for all diagnostics that describe the run-time
9326/// behavior of a program, such as passing a non-POD value through an ellipsis.
9327/// Failure to do so will likely result in spurious diagnostics or failures
9328/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek762696f2011-02-23 01:51:43 +00009329bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009330 const PartialDiagnostic &PD) {
John McCallf85e1932011-06-15 23:02:42 +00009331 switch (ExprEvalContexts.back().Context) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009332 case Unevaluated:
9333 // The argument will never be evaluated, so don't complain.
9334 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009335
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009336 case PotentiallyEvaluated:
Douglas Gregorbe0f7bd2010-09-11 20:24:53 +00009337 case PotentiallyEvaluatedIfUsed:
Ted Kremenek351ba912011-02-23 01:52:04 +00009338 if (stmt && getCurFunctionOrMethodDecl()) {
9339 FunctionScopes.back()->PossiblyUnreachableDiags.
9340 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9341 }
9342 else
9343 Diag(Loc, PD);
9344
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009345 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009346
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00009347 case PotentiallyPotentiallyEvaluated:
9348 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9349 break;
9350 }
9351
9352 return false;
9353}
9354
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009355bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9356 CallExpr *CE, FunctionDecl *FD) {
9357 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9358 return false;
9359
9360 PartialDiagnostic Note =
9361 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9362 << FD->getDeclName() : PDiag();
9363 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009364
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009365 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009366 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009367 PDiag(diag::err_call_function_incomplete_return)
9368 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00009369 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +00009370 << CE->getSourceRange(),
9371 std::make_pair(NoteLoc, Note)))
9372 return true;
9373
9374 return false;
9375}
9376
Douglas Gregor92c3a042011-01-19 16:50:08 +00009377// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCall5a881bb2009-10-12 21:59:07 +00009378// will prevent this condition from triggering, which is what we want.
9379void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9380 SourceLocation Loc;
9381
John McCalla52ef082009-11-11 02:41:58 +00009382 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor92c3a042011-01-19 16:50:08 +00009383 bool IsOrAssign = false;
John McCalla52ef082009-11-11 02:41:58 +00009384
John McCall5a881bb2009-10-12 21:59:07 +00009385 if (isa<BinaryOperator>(E)) {
9386 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +00009387 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCall5a881bb2009-10-12 21:59:07 +00009388 return;
9389
Douglas Gregor92c3a042011-01-19 16:50:08 +00009390 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9391
John McCallc8d8ac52009-11-12 00:06:05 +00009392 // Greylist some idioms by putting them into a warning subcategory.
9393 if (ObjCMessageExpr *ME
9394 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9395 Selector Sel = ME->getSelector();
9396
John McCallc8d8ac52009-11-12 00:06:05 +00009397 // self = [<foo> init...]
Douglas Gregor813d8342011-02-18 22:29:55 +00009398 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallc8d8ac52009-11-12 00:06:05 +00009399 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9400
9401 // <foo> = [<bar> nextObject]
Douglas Gregor813d8342011-02-18 22:29:55 +00009402 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallc8d8ac52009-11-12 00:06:05 +00009403 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9404 }
John McCalla52ef082009-11-11 02:41:58 +00009405
John McCall5a881bb2009-10-12 21:59:07 +00009406 Loc = Op->getOperatorLoc();
9407 } else if (isa<CXXOperatorCallExpr>(E)) {
9408 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor92c3a042011-01-19 16:50:08 +00009409 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCall5a881bb2009-10-12 21:59:07 +00009410 return;
9411
Douglas Gregor92c3a042011-01-19 16:50:08 +00009412 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCall5a881bb2009-10-12 21:59:07 +00009413 Loc = Op->getOperatorLoc();
9414 } else {
9415 // Not an assignment.
9416 return;
9417 }
9418
Douglas Gregor55b38842010-04-14 16:09:52 +00009419 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor92c3a042011-01-19 16:50:08 +00009420
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009421 SourceLocation Open = E->getSourceRange().getBegin();
9422 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9423 Diag(Loc, diag::note_condition_assign_silence)
9424 << FixItHint::CreateInsertion(Open, "(")
9425 << FixItHint::CreateInsertion(Close, ")");
9426
Douglas Gregor92c3a042011-01-19 16:50:08 +00009427 if (IsOrAssign)
9428 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9429 << FixItHint::CreateReplacement(Loc, "!=");
9430 else
9431 Diag(Loc, diag::note_condition_assign_to_comparison)
9432 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +00009433}
9434
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009435/// \brief Redundant parentheses over an equality comparison can indicate
9436/// that the user intended an assignment used as condition.
9437void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009438 // Don't warn if the parens came from a macro.
9439 SourceLocation parenLoc = parenE->getLocStart();
9440 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9441 return;
Argyrios Kyrtzidis170a6a22011-03-28 23:52:04 +00009442 // Don't warn for dependent expressions.
9443 if (parenE->isTypeDependent())
9444 return;
Argyrios Kyrtzidiscf1620a2011-02-01 22:23:56 +00009445
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009446 Expr *E = parenE->IgnoreParens();
9447
9448 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis70f23302011-02-01 19:32:59 +00009449 if (opE->getOpcode() == BO_EQ &&
9450 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9451 == Expr::MLV_Valid) {
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009452 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenek006ae382011-02-01 22:36:09 +00009453
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009454 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekf7275cd2011-02-02 02:20:30 +00009455 Diag(Loc, diag::note_equality_comparison_silence)
9456 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9457 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidisabdd3b32011-04-25 23:01:29 +00009458 Diag(Loc, diag::note_equality_comparison_to_assign)
9459 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009460 }
9461}
9462
John Wiegley429bb272011-04-08 18:41:53 +00009463ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCall5a881bb2009-10-12 21:59:07 +00009464 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis0e2dc3a2011-02-01 18:24:22 +00009465 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9466 DiagnoseEqualityWithExtraParens(parenE);
John McCall5a881bb2009-10-12 21:59:07 +00009467
John McCall864c0412011-04-26 20:42:42 +00009468 ExprResult result = CheckPlaceholderExpr(E);
9469 if (result.isInvalid()) return ExprError();
9470 E = result.take();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00009471
John McCall864c0412011-04-26 20:42:42 +00009472 if (!E->isTypeDependent()) {
John McCallf6a16482010-12-04 03:47:34 +00009473 if (getLangOptions().CPlusPlus)
9474 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9475
John Wiegley429bb272011-04-08 18:41:53 +00009476 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9477 if (ERes.isInvalid())
9478 return ExprError();
9479 E = ERes.take();
John McCallabc56c72010-12-04 06:09:13 +00009480
9481 QualType T = E->getType();
John Wiegley429bb272011-04-08 18:41:53 +00009482 if (!T->isScalarType()) { // C99 6.8.4.1p1
9483 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9484 << T << E->getSourceRange();
9485 return ExprError();
9486 }
John McCall5a881bb2009-10-12 21:59:07 +00009487 }
9488
John Wiegley429bb272011-04-08 18:41:53 +00009489 return Owned(E);
John McCall5a881bb2009-10-12 21:59:07 +00009490}
Douglas Gregor586596f2010-05-06 17:25:47 +00009491
John McCall60d7b3a2010-08-24 06:29:42 +00009492ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9493 Expr *Sub) {
Douglas Gregoreecf38f2010-05-06 21:39:56 +00009494 if (!Sub)
Douglas Gregor586596f2010-05-06 17:25:47 +00009495 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009496
9497 return CheckBooleanCondition(Sub, Loc);
Douglas Gregor586596f2010-05-06 17:25:47 +00009498}
John McCall2a984ca2010-10-12 00:20:44 +00009499
John McCall1de4d4e2011-04-07 08:22:57 +00009500namespace {
John McCall755d8492011-04-12 00:42:48 +00009501 /// A visitor for rebuilding a call to an __unknown_any expression
9502 /// to have an appropriate type.
9503 struct RebuildUnknownAnyFunction
9504 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9505
9506 Sema &S;
9507
9508 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9509
9510 ExprResult VisitStmt(Stmt *S) {
9511 llvm_unreachable("unexpected statement!");
9512 return ExprError();
9513 }
9514
9515 ExprResult VisitExpr(Expr *expr) {
9516 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
9517 << expr->getSourceRange();
9518 return ExprError();
9519 }
9520
9521 /// Rebuild an expression which simply semantically wraps another
9522 /// expression which it shares the type and value kind of.
9523 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9524 ExprResult subResult = Visit(expr->getSubExpr());
9525 if (subResult.isInvalid()) return ExprError();
9526
9527 Expr *subExpr = subResult.take();
9528 expr->setSubExpr(subExpr);
9529 expr->setType(subExpr->getType());
9530 expr->setValueKind(subExpr->getValueKind());
9531 assert(expr->getObjectKind() == OK_Ordinary);
9532 return expr;
9533 }
9534
9535 ExprResult VisitParenExpr(ParenExpr *paren) {
9536 return rebuildSugarExpr(paren);
9537 }
9538
9539 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9540 return rebuildSugarExpr(op);
9541 }
9542
9543 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9544 ExprResult subResult = Visit(op->getSubExpr());
9545 if (subResult.isInvalid()) return ExprError();
9546
9547 Expr *subExpr = subResult.take();
9548 op->setSubExpr(subExpr);
9549 op->setType(S.Context.getPointerType(subExpr->getType()));
9550 assert(op->getValueKind() == VK_RValue);
9551 assert(op->getObjectKind() == OK_Ordinary);
9552 return op;
9553 }
9554
9555 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
9556 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
9557
9558 expr->setType(decl->getType());
9559
9560 assert(expr->getValueKind() == VK_RValue);
9561 if (S.getLangOptions().CPlusPlus &&
9562 !(isa<CXXMethodDecl>(decl) &&
9563 cast<CXXMethodDecl>(decl)->isInstance()))
9564 expr->setValueKind(VK_LValue);
9565
9566 return expr;
9567 }
9568
9569 ExprResult VisitMemberExpr(MemberExpr *mem) {
9570 return resolveDecl(mem, mem->getMemberDecl());
9571 }
9572
9573 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
9574 return resolveDecl(ref, ref->getDecl());
9575 }
9576 };
9577}
9578
9579/// Given a function expression of unknown-any type, try to rebuild it
9580/// to have a function type.
9581static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
9582 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
9583 if (result.isInvalid()) return ExprError();
9584 return S.DefaultFunctionArrayConversion(result.take());
9585}
9586
9587namespace {
John McCall379b5152011-04-11 07:02:50 +00009588 /// A visitor for rebuilding an expression of type __unknown_anytype
9589 /// into one which resolves the type directly on the referring
9590 /// expression. Strict preservation of the original source
9591 /// structure is not a goal.
John McCall1de4d4e2011-04-07 08:22:57 +00009592 struct RebuildUnknownAnyExpr
John McCalla5fc4722011-04-09 22:50:59 +00009593 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall1de4d4e2011-04-07 08:22:57 +00009594
9595 Sema &S;
9596
9597 /// The current destination type.
9598 QualType DestType;
9599
9600 RebuildUnknownAnyExpr(Sema &S, QualType castType)
9601 : S(S), DestType(castType) {}
9602
John McCalla5fc4722011-04-09 22:50:59 +00009603 ExprResult VisitStmt(Stmt *S) {
John McCall379b5152011-04-11 07:02:50 +00009604 llvm_unreachable("unexpected statement!");
John McCalla5fc4722011-04-09 22:50:59 +00009605 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009606 }
9607
John McCall379b5152011-04-11 07:02:50 +00009608 ExprResult VisitExpr(Expr *expr) {
9609 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9610 << expr->getSourceRange();
9611 return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009612 }
9613
John McCall379b5152011-04-11 07:02:50 +00009614 ExprResult VisitCallExpr(CallExpr *call);
9615 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
9616
John McCalla5fc4722011-04-09 22:50:59 +00009617 /// Rebuild an expression which simply semantically wraps another
9618 /// expression which it shares the type and value kind of.
9619 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9620 ExprResult subResult = Visit(expr->getSubExpr());
John McCall755d8492011-04-12 00:42:48 +00009621 if (subResult.isInvalid()) return ExprError();
John McCalla5fc4722011-04-09 22:50:59 +00009622 Expr *subExpr = subResult.take();
9623 expr->setSubExpr(subExpr);
9624 expr->setType(subExpr->getType());
9625 expr->setValueKind(subExpr->getValueKind());
9626 assert(expr->getObjectKind() == OK_Ordinary);
9627 return expr;
9628 }
John McCall1de4d4e2011-04-07 08:22:57 +00009629
John McCalla5fc4722011-04-09 22:50:59 +00009630 ExprResult VisitParenExpr(ParenExpr *paren) {
9631 return rebuildSugarExpr(paren);
9632 }
9633
9634 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9635 return rebuildSugarExpr(op);
9636 }
9637
John McCall755d8492011-04-12 00:42:48 +00009638 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9639 const PointerType *ptr = DestType->getAs<PointerType>();
9640 if (!ptr) {
9641 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
9642 << op->getSourceRange();
9643 return ExprError();
9644 }
9645 assert(op->getValueKind() == VK_RValue);
9646 assert(op->getObjectKind() == OK_Ordinary);
9647 op->setType(DestType);
9648
9649 // Build the sub-expression as if it were an object of the pointee type.
9650 DestType = ptr->getPointeeType();
9651 ExprResult subResult = Visit(op->getSubExpr());
9652 if (subResult.isInvalid()) return ExprError();
9653 op->setSubExpr(subResult.take());
9654 return op;
9655 }
9656
John McCall379b5152011-04-11 07:02:50 +00009657 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCalla5fc4722011-04-09 22:50:59 +00009658
John McCall755d8492011-04-12 00:42:48 +00009659 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCalla5fc4722011-04-09 22:50:59 +00009660
John McCall755d8492011-04-12 00:42:48 +00009661 ExprResult VisitMemberExpr(MemberExpr *mem) {
9662 return resolveDecl(mem, mem->getMemberDecl());
9663 }
John McCalla5fc4722011-04-09 22:50:59 +00009664
9665 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall379b5152011-04-11 07:02:50 +00009666 return resolveDecl(ref, ref->getDecl());
John McCall1de4d4e2011-04-07 08:22:57 +00009667 }
9668 };
9669}
9670
John McCall379b5152011-04-11 07:02:50 +00009671/// Rebuilds a call expression which yielded __unknown_anytype.
9672ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
9673 Expr *callee = call->getCallee();
9674
9675 enum FnKind {
John McCallf5307512011-04-27 00:36:17 +00009676 FK_MemberFunction,
John McCall379b5152011-04-11 07:02:50 +00009677 FK_FunctionPointer,
9678 FK_BlockPointer
9679 };
9680
9681 FnKind kind;
9682 QualType type = callee->getType();
John McCallf5307512011-04-27 00:36:17 +00009683 if (type == S.Context.BoundMemberTy) {
9684 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
9685 kind = FK_MemberFunction;
9686 type = Expr::findBoundMemberType(callee);
John McCall379b5152011-04-11 07:02:50 +00009687 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
9688 type = ptr->getPointeeType();
9689 kind = FK_FunctionPointer;
9690 } else {
9691 type = type->castAs<BlockPointerType>()->getPointeeType();
9692 kind = FK_BlockPointer;
9693 }
9694 const FunctionType *fnType = type->castAs<FunctionType>();
9695
9696 // Verify that this is a legal result type of a function.
9697 if (DestType->isArrayType() || DestType->isFunctionType()) {
9698 unsigned diagID = diag::err_func_returning_array_function;
9699 if (kind == FK_BlockPointer)
9700 diagID = diag::err_block_returning_array_function;
9701
9702 S.Diag(call->getExprLoc(), diagID)
9703 << DestType->isFunctionType() << DestType;
9704 return ExprError();
9705 }
9706
9707 // Otherwise, go ahead and set DestType as the call's result.
9708 call->setType(DestType.getNonLValueExprType(S.Context));
9709 call->setValueKind(Expr::getValueKindForType(DestType));
9710 assert(call->getObjectKind() == OK_Ordinary);
9711
9712 // Rebuild the function type, replacing the result type with DestType.
9713 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
9714 DestType = S.Context.getFunctionType(DestType,
9715 proto->arg_type_begin(),
9716 proto->getNumArgs(),
9717 proto->getExtProtoInfo());
9718 else
9719 DestType = S.Context.getFunctionNoProtoType(DestType,
9720 fnType->getExtInfo());
9721
9722 // Rebuild the appropriate pointer-to-function type.
9723 switch (kind) {
John McCallf5307512011-04-27 00:36:17 +00009724 case FK_MemberFunction:
John McCall379b5152011-04-11 07:02:50 +00009725 // Nothing to do.
9726 break;
9727
9728 case FK_FunctionPointer:
9729 DestType = S.Context.getPointerType(DestType);
9730 break;
9731
9732 case FK_BlockPointer:
9733 DestType = S.Context.getBlockPointerType(DestType);
9734 break;
9735 }
9736
9737 // Finally, we can recurse.
9738 ExprResult calleeResult = Visit(callee);
9739 if (!calleeResult.isUsable()) return ExprError();
9740 call->setCallee(calleeResult.take());
9741
9742 // Bind a temporary if necessary.
9743 return S.MaybeBindToTemporary(call);
9744}
9745
9746ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall755d8492011-04-12 00:42:48 +00009747 // Verify that this is a legal result type of a call.
9748 if (DestType->isArrayType() || DestType->isFunctionType()) {
9749 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
9750 << DestType->isFunctionType() << DestType;
9751 return ExprError();
John McCall379b5152011-04-11 07:02:50 +00009752 }
9753
John McCall48218c62011-07-13 17:56:40 +00009754 // Rewrite the method result type if available.
9755 if (ObjCMethodDecl *method = msg->getMethodDecl()) {
9756 assert(method->getResultType() == S.Context.UnknownAnyTy);
9757 method->setResultType(DestType);
9758 }
John McCall755d8492011-04-12 00:42:48 +00009759
John McCall379b5152011-04-11 07:02:50 +00009760 // Change the type of the message.
John McCall755d8492011-04-12 00:42:48 +00009761 msg->setType(DestType.getNonReferenceType());
9762 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall379b5152011-04-11 07:02:50 +00009763
John McCall755d8492011-04-12 00:42:48 +00009764 return S.MaybeBindToTemporary(msg);
John McCall379b5152011-04-11 07:02:50 +00009765}
9766
9767ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall755d8492011-04-12 00:42:48 +00009768 // The only case we should ever see here is a function-to-pointer decay.
John McCall379b5152011-04-11 07:02:50 +00009769 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall379b5152011-04-11 07:02:50 +00009770 assert(ice->getValueKind() == VK_RValue);
9771 assert(ice->getObjectKind() == OK_Ordinary);
9772
John McCall755d8492011-04-12 00:42:48 +00009773 ice->setType(DestType);
9774
John McCall379b5152011-04-11 07:02:50 +00009775 // Rebuild the sub-expression as the pointee (function) type.
9776 DestType = DestType->castAs<PointerType>()->getPointeeType();
9777
9778 ExprResult result = Visit(ice->getSubExpr());
9779 if (!result.isUsable()) return ExprError();
9780
9781 ice->setSubExpr(result.take());
9782 return S.Owned(ice);
9783}
9784
John McCall755d8492011-04-12 00:42:48 +00009785ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall379b5152011-04-11 07:02:50 +00009786 ExprValueKind valueKind = VK_LValue;
John McCall379b5152011-04-11 07:02:50 +00009787 QualType type = DestType;
9788
9789 // We know how to make this work for certain kinds of decls:
9790
9791 // - functions
John McCall755d8492011-04-12 00:42:48 +00009792 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCall379b5152011-04-11 07:02:50 +00009793 // This is true because FunctionDecls must always have function
9794 // type, so we can't be resolving the entire thing at once.
9795 assert(type->isFunctionType());
9796
John McCallf5307512011-04-27 00:36:17 +00009797 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
9798 if (method->isInstance()) {
9799 valueKind = VK_RValue;
9800 type = S.Context.BoundMemberTy;
9801 }
9802
John McCall379b5152011-04-11 07:02:50 +00009803 // Function references aren't l-values in C.
9804 if (!S.getLangOptions().CPlusPlus)
9805 valueKind = VK_RValue;
9806
9807 // - variables
9808 } else if (isa<VarDecl>(decl)) {
John McCall755d8492011-04-12 00:42:48 +00009809 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
9810 type = refTy->getPointeeType();
John McCall379b5152011-04-11 07:02:50 +00009811 } else if (type->isFunctionType()) {
John McCall755d8492011-04-12 00:42:48 +00009812 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
9813 << decl << expr->getSourceRange();
9814 return ExprError();
John McCall379b5152011-04-11 07:02:50 +00009815 }
9816
9817 // - nothing else
9818 } else {
9819 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
9820 << decl << expr->getSourceRange();
9821 return ExprError();
9822 }
9823
John McCall755d8492011-04-12 00:42:48 +00009824 decl->setType(DestType);
9825 expr->setType(type);
9826 expr->setValueKind(valueKind);
9827 return S.Owned(expr);
John McCall379b5152011-04-11 07:02:50 +00009828}
9829
John McCall1de4d4e2011-04-07 08:22:57 +00009830/// Check a cast of an unknown-any type. We intentionally only
9831/// trigger this for C-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00009832ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
9833 Expr *castExpr, CastKind &castKind,
9834 ExprValueKind &VK, CXXCastPath &path) {
John McCall1de4d4e2011-04-07 08:22:57 +00009835 // Rewrite the casted expression from scratch.
John McCalla5fc4722011-04-09 22:50:59 +00009836 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
9837 if (!result.isUsable()) return ExprError();
John McCall1de4d4e2011-04-07 08:22:57 +00009838
John McCalla5fc4722011-04-09 22:50:59 +00009839 castExpr = result.take();
9840 VK = castExpr->getValueKind();
9841 castKind = CK_NoOp;
9842
9843 return castExpr;
John McCall1de4d4e2011-04-07 08:22:57 +00009844}
9845
9846static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
9847 Expr *orig = e;
John McCall379b5152011-04-11 07:02:50 +00009848 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall1de4d4e2011-04-07 08:22:57 +00009849 while (true) {
9850 e = e->IgnoreParenImpCasts();
John McCall379b5152011-04-11 07:02:50 +00009851 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall1de4d4e2011-04-07 08:22:57 +00009852 e = call->getCallee();
John McCall379b5152011-04-11 07:02:50 +00009853 diagID = diag::err_uncasted_call_of_unknown_any;
9854 } else {
John McCall1de4d4e2011-04-07 08:22:57 +00009855 break;
John McCall379b5152011-04-11 07:02:50 +00009856 }
John McCall1de4d4e2011-04-07 08:22:57 +00009857 }
9858
John McCall379b5152011-04-11 07:02:50 +00009859 SourceLocation loc;
9860 NamedDecl *d;
9861 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9862 loc = ref->getLocation();
9863 d = ref->getDecl();
9864 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
9865 loc = mem->getMemberLoc();
9866 d = mem->getMemberDecl();
9867 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
9868 diagID = diag::err_uncasted_call_of_unknown_any;
9869 loc = msg->getSelectorLoc();
9870 d = msg->getMethodDecl();
9871 assert(d && "unknown method returning __unknown_any?");
9872 } else {
9873 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9874 << e->getSourceRange();
9875 return ExprError();
9876 }
9877
9878 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall1de4d4e2011-04-07 08:22:57 +00009879
9880 // Never recoverable.
9881 return ExprError();
9882}
9883
John McCall2a984ca2010-10-12 00:20:44 +00009884/// Check for operands with placeholder types and complain if found.
9885/// Returns true if there was an error and no recovery was possible.
John McCallfb8721c2011-04-10 19:13:55 +00009886ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall1de4d4e2011-04-07 08:22:57 +00009887 // Placeholder types are always *exactly* the appropriate builtin type.
9888 QualType type = E->getType();
John McCall2a984ca2010-10-12 00:20:44 +00009889
John McCall1de4d4e2011-04-07 08:22:57 +00009890 // Overloaded expressions.
9891 if (type == Context.OverloadTy)
9892 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregordb2eae62011-03-16 19:16:25 +00009893 E->getSourceRange(),
John McCall1de4d4e2011-04-07 08:22:57 +00009894 QualType(),
9895 diag::err_ovl_unresolvable);
9896
John McCall864c0412011-04-26 20:42:42 +00009897 // Bound member functions.
9898 if (type == Context.BoundMemberTy) {
9899 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9900 << E->getSourceRange();
9901 return ExprError();
9902 }
9903
John McCall1de4d4e2011-04-07 08:22:57 +00009904 // Expressions of unknown type.
9905 if (type == Context.UnknownAnyTy)
9906 return diagnoseUnknownAnyExpr(*this, E);
9907
9908 assert(!type->isPlaceholderType());
9909 return Owned(E);
John McCall2a984ca2010-10-12 00:20:44 +00009910}
Richard Trieubb9b80c2011-04-21 21:44:26 +00009911
9912bool Sema::CheckCaseExpression(Expr *expr) {
9913 if (expr->isTypeDependent())
9914 return true;
9915 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
9916 return expr->getType()->isIntegralOrEnumerationType();
9917 return false;
9918}