blob: bc7d0bdfe50bf457de89222fdfdd16fea4fc4365 [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/AnalysisBasedWarnings.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000018#include "clang/AST/ASTContext.h"
Sebastian Redl2ac2c722011-04-29 08:19:30 +000019#include "clang/AST/ASTMutationListener.h"
Douglas Gregord1702062010-04-29 00:18:15 +000020#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000022#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000023#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000024#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000025#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000027#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000028#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000029#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000030#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000031#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000032#include "clang/Lex/LiteralSupport.h"
33#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000034#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Designator.h"
36#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000037#include "clang/Sema/ScopeInfo.h"
John McCall8b0666c2010-08-20 18:27:03 +000038#include "clang/Sema/ParsedTemplate.h"
Anna Zaks3b402712011-07-28 19:51:27 +000039#include "clang/Sema/SemaFixItUtils.h"
John McCallde6836a2010-08-24 07:21:54 +000040#include "clang/Sema/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000043
David Chisnall9f57c292009-08-17 16:35:33 +000044
Douglas Gregor171c45a2009-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 Jahanian7d6e11a2010-12-21 00:44:01 +000054/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattnerb7df3c62009-10-25 22:31:57 +000055/// decls.
56///
Douglas Gregor171c45a2009-02-18 21:56:37 +000057/// \returns true if there was an error (this declaration cannot be
58/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000059///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000060bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahaniandbbdd2f2011-04-23 17:27:19 +000061 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor5bb5e4a2010-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 Lattner0e62c1c2011-07-23 10:55:15 +000065 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000066 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
67 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000068 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-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 Gregor20b2ebd2011-03-23 00:50:03 +000073 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-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 Smith30482bc2011-02-20 03:19:35 +000080 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-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 Smith30482bc2011-02-20 03:19:35 +000085 }
86
Douglas Gregor171c45a2009-02-18 21:56:37 +000087 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000088 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000089 if (FD->isDeleted()) {
90 Diag(Loc, diag::err_deleted_function_use);
John McCall31168b02011-06-15 23:02:42 +000091 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
Douglas Gregor171c45a2009-02-18 21:56:37 +000092 return true;
93 }
Douglas Gregorde681d42009-02-24 04:26:15 +000094 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000095
Douglas Gregor20b2ebd2011-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 Kyrtzidisc30661f2011-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 Gregor20b2ebd2011-03-23 00:50:03 +0000121 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000122 break;
123 }
124
Anders Carlsson73067a02010-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 Gregor171c45a2009-02-18 21:56:37 +0000129 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000130}
131
Douglas Gregor20b2ebd2011-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 Jahanian027b8862009-05-13 18:09:35 +0000149/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +0000150/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-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 Stump11289f42009-09-09 15:08:12 +0000154 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000155 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000156 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000157 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000158
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000159 int sentinelPos = attr->getSentinel();
160 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +0000161
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000162 unsigned int i = 0;
Fariborz Jahanian4a528032009-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 Stump12b8ce12009-08-04 21:02:39 +0000176 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-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 Stump12b8ce12009-08-04 21:02:39 +0000186 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000187 // block or function pointer call.
188 QualType Ty = V->getType();
189 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000190 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000191 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
192 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-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 Stump12b8ce12009-08-04 21:02:39 +0000206 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000207 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000208 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000209 return;
210
211 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000212 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000213 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-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 Jahanian4a528032009-05-14 18:00:00 +0000223 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000224 return;
225 }
226 while (i < NumArgs-1) {
227 ++i;
228 ++sentinel;
229 }
230 Expr *sentinelExpr = Args[sentinel];
John McCall7ddbcf42010-05-06 23:53:00 +0000231 if (!sentinelExpr) return;
232 if (sentinelExpr->isTypeDependent()) return;
233 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000234
235 // nullptr_t is always treated as null.
236 if (sentinelExpr->getType()->isNullPtrType()) return;
237
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000238 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-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 Gregor5ff4e982011-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 McCall7ddbcf42010-05-06 23:53:00 +0000262 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000263}
264
Douglas Gregor87f95b02009-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 Lattner513165e2008-07-25 21:10:04 +0000270//===----------------------------------------------------------------------===//
271// Standard Promotions and Conversions
272//===----------------------------------------------------------------------===//
273
Chris Lattner513165e2008-07-25 21:10:04 +0000274/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000275ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattner513165e2008-07-25 21:10:04 +0000276 QualType Ty = E->getType();
277 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
278
Chris Lattner513165e2008-07-25 21:10:04 +0000279 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000280 E = ImpCastExprToType(E, Context.getPointerType(Ty),
281 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-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 Kyrtzidis9321c742008-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 McCall086a4642010-11-24 05:12:34 +0000294 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000295 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
296 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000297 }
John Wiegley01296292011-04-08 18:41:53 +0000298 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000299}
300
Argyrios Kyrtzidisa9b630e2011-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 Wiegley01296292011-04-08 18:41:53 +0000320ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCallf3735e02010-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 Wiegley01296292011-04-08 18:41:53 +0000324 if (!E->isGLValue()) return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000325 QualType T = E->getType();
326 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000327
John McCall27584242010-12-06 20:48:59 +0000328 // Create a load out of an ObjCProperty l-value, if necessary.
329 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +0000330 ExprResult Res = ConvertPropertyForRValue(E);
331 if (Res.isInvalid())
332 return Owned(E);
333 E = Res.take();
John McCall27584242010-12-06 20:48:59 +0000334 if (!E->isGLValue())
John Wiegley01296292011-04-08 18:41:53 +0000335 return Owned(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000336 }
John McCall27584242010-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 Wiegley01296292011-04-08 18:41:53 +0000344 return Owned(E);
John McCall27584242010-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 Wiegley01296292011-04-08 18:41:53 +0000352 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000353
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000354 CheckForNullPointerDereference(*this, E);
355
John McCall27584242010-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 Kremenekdf26df72011-03-01 18:41:00 +0000368 CheckArrayAccess(E);
Ted Kremenek64699be2011-02-16 01:57:07 +0000369
John Wiegley01296292011-04-08 18:41:53 +0000370 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
371 E, 0, VK_RValue));
John McCall27584242010-12-06 20:48:59 +0000372}
373
John Wiegley01296292011-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 Gregorb92a1562010-02-03 00:27:59 +0000382}
383
384
Chris Lattner513165e2008-07-25 21:10:04 +0000385/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000386/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000387/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-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 Wiegley01296292011-04-08 18:41:53 +0000390ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000391 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000392 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
393 if (Res.isInvalid())
394 return Owned(E);
395 E = Res.take();
John McCallf3735e02010-12-01 04:43:34 +0000396
397 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000398 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-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 Wiegley01296292011-04-08 18:41:53 +0000419 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
420 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000421 }
422 if (Ty->isPromotableIntegerType()) {
423 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000424 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
425 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000426 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000427 }
John Wiegley01296292011-04-08 18:41:53 +0000428 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000429}
430
Chris Lattner2ce500f2008-07-25 22:25:12 +0000431/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000432/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000433/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000434ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
435 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000436 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000437
John Wiegley01296292011-04-08 18:41:53 +0000438 ExprResult Res = UsualUnaryConversions(E);
439 if (Res.isInvalid())
440 return Owned(E);
441 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000442
Chris Lattner2ce500f2008-07-25 22:25:12 +0000443 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000444 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000445 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
446
447 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000448}
449
Chris Lattnera8a7d0f2009-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 Wiegley01296292011-04-08 18:41:53 +0000452/// interfaces passed by value.
453ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000454 FunctionDecl *FDecl) {
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000455 ExprResult ExprRes = CheckPlaceholderExpr(E);
456 if (ExprRes.isInvalid())
457 return ExprError();
458
459 ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000460 if (ExprRes.isInvalid())
461 return ExprError();
462 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000463
Chris Lattnerbb53efb2010-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 Wiegley01296292011-04-08 18:41:53 +0000468 return Owned(E);
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000469
Douglas Gregor347e0f22011-05-21 19:26:31 +0000470 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000471 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-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 Wiegley01296292011-04-08 18:41:53 +0000475 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000476
John McCall31168b02011-06-15 23:02:42 +0000477 if (!E->getType().isPODType(Context)) {
Douglas Gregor253cadf2011-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 McCall31168b02011-06-15 23:02:42 +0000492
493 if (!TrivialEnough &&
494 getLangOptions().ObjCAutoRefCount &&
495 E->getType()->isObjCLifetimeType())
496 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000497
498 if (TrivialEnough) {
499 // Nothing to diagnose. This is okay.
500 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000501 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor253cadf2011-05-21 16:27:21 +0000502 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-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 Gregor253cadf2011-05-21 16:27:21 +0000525 }
526
John Wiegley01296292011-04-08 18:41:53 +0000527 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000528}
529
Chris Lattner513165e2008-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 Stump11289f42009-09-09 15:08:12 +0000532/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-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 Trieucfc491d2011-08-02 04:35:43 +0000536QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr,
537 ExprResult &rhsExpr,
Chris Lattner513165e2008-07-25 21:10:04 +0000538 bool isCompAssign) {
John Wiegley01296292011-04-08 18:41:53 +0000539 if (!isCompAssign) {
540 lhsExpr = UsualUnaryConversions(lhsExpr.take());
541 if (lhsExpr.isInvalid())
542 return QualType();
543 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000544
John Wiegley01296292011-04-08 18:41:53 +0000545 rhsExpr = UsualUnaryConversions(rhsExpr.take());
546 if (rhsExpr.isInvalid())
547 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000548
Mike Stump11289f42009-09-09 15:08:12 +0000549 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000550 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000551 QualType lhs =
John Wiegley01296292011-04-08 18:41:53 +0000552 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000553 QualType rhs =
John Wiegley01296292011-04-08 18:41:53 +0000554 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-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 McCalld005ac92010-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 Wiegley01296292011-04-08 18:41:53 +0000569 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000570 if (!LHSBitfieldPromoteTy.isNull())
571 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000572 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000573 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000574
John McCalld005ac92010-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 McCallc5e62b42010-11-13 09:02:35 +0000587 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
588 if (rhs->isIntegerType()) {
589 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000590 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
Richard Trieucfc491d2011-08-02 04:35:43 +0000591 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
592 CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000593 } else {
594 assert(rhs->isComplexIntegerType());
Richard Trieucfc491d2011-08-02 04:35:43 +0000595 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
596 CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000597 }
John McCalld005ac92010-11-13 08:17:45 +0000598 return lhs;
599 }
600
John McCallc5e62b42010-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 Trieucfc491d2011-08-02 04:35:43 +0000606 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp,
607 CK_IntegralToFloating);
608 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
609 CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000610 } else {
611 assert(lhs->isComplexIntegerType());
Richard Trieucfc491d2011-08-02 04:35:43 +0000612 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
613 CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000614 }
615 }
John McCalld005ac92010-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 Trieucfc491d2011-08-02 04:35:43 +0000635 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
636 CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000637 return lhs;
638
639 } else if (order < 0) {
640 // _Complex float -> _Complex double
641 if (!isCompAssign)
Richard Trieucfc491d2011-08-02 04:35:43 +0000642 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
643 CK_FloatingComplexCast);
John McCalld005ac92010-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 McCallc5e62b42010-11-13 09:02:35 +0000654 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000655 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
Richard Trieucfc491d2011-08-02 04:35:43 +0000656 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
657 CK_FloatingRealToComplex);
John McCalld005ac92010-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 Trieucfc491d2011-08-02 04:35:43 +0000665 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
666 CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000667
668 // _Complex float -> _Complex double
669 if (!isCompAssign && order < 0)
Richard Trieucfc491d2011-08-02 04:35:43 +0000670 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
671 CK_FloatingComplexCast);
John McCalld005ac92010-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 McCallc5e62b42010-11-13 09:02:35 +0000682 if (!isCompAssign) {
Argyrios Kyrtzidise84389b2011-01-18 18:49:33 +0000683 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000684 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
Richard Trieucfc491d2011-08-02 04:35:43 +0000685 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
686 CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000687 }
John McCalld005ac92010-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 Trieucfc491d2011-08-02 04:35:43 +0000696 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
697 CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000698
699 // _Complex float -> _Complex double
700 if (order > 0)
Richard Trieucfc491d2011-08-02 04:35:43 +0000701 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
702 CK_FloatingComplexCast);
John McCalld005ac92010-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 Wiegley01296292011-04-08 18:41:53 +0000716 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000717 return lhs;
718 }
719
720 assert(order < 0 && "illegal float comparison");
721 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000722 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCalld005ac92010-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 Wiegley01296292011-04-08 18:41:53 +0000730 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCalld005ac92010-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 Trieucfc491d2011-08-02 04:35:43 +0000739 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
740 CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000741
742 // float -> _Complex float
743 if (!isCompAssign)
Richard Trieucfc491d2011-08-02 04:35:43 +0000744 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
745 CK_FloatingRealToComplex);
John McCalld005ac92010-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 Wiegley01296292011-04-08 18:41:53 +0000754 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCalld005ac92010-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 Trieucfc491d2011-08-02 04:35:43 +0000764 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
765 CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000766
767 // float -> _Complex float
Richard Trieucfc491d2011-08-02 04:35:43 +0000768 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
769 CK_FloatingRealToComplex);
John McCalld005ac92010-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 Wiegley01296292011-04-08 18:41:53 +0000785 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000786 return lhs;
787 }
788
789 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000790 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000791 return rhs;
792 } else if (lhsComplexInt) {
793 // int -> _Complex int
John Wiegley01296292011-04-08 18:41:53 +0000794 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000795 return lhs;
796 } else if (rhsComplexInt) {
797 // int -> _Complex int
798 if (!isCompAssign)
Richard Trieucfc491d2011-08-02 04:35:43 +0000799 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
800 CK_IntegralRealToComplex);
John McCalld005ac92010-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 Wiegley01296292011-04-08 18:41:53 +0000812 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000813 return lhs;
814 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000815 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-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 Wiegley01296292011-04-08 18:41:53 +0000821 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000822 return lhs;
823 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000824 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-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 Wiegley01296292011-04-08 18:41:53 +0000831 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000832 return lhs;
833 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000834 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-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 Wiegley01296292011-04-08 18:41:53 +0000843 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000844 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000845 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000846 return result;
847 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000848}
849
Chris Lattner513165e2008-07-25 21:10:04 +0000850//===----------------------------------------------------------------------===//
851// Semantic Analysis for various Expression Types
852//===----------------------------------------------------------------------===//
853
854
Peter Collingbourne91147592011-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 Kramer34623762011-04-15 11:21:57 +0000879 delete [] Types;
Peter Collingbourne91147592011-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 Lattner0e62c1c2011-07-23 10:55:15 +0000955 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-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 Lattner0e62c1c2011-07-23 10:55:15 +0000975 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-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 Naroff83895f72007-09-16 03:34:24 +00001012/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +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 Redlffbcf962009-01-18 18:53:16 +00001017///
John McCalldadc5752010-08-24 06:29:42 +00001018ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +00001019Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001020 assert(NumStringToks && "Must have at least one string!");
1021
Chris Lattner8a24e582009-01-16 18:51:42 +00001022 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001023 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001024 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001025
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001026 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001027 for (unsigned i = 0; i != NumStringToks; ++i)
1028 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001029
Chris Lattner36fc8792008-02-11 00:02:17 +00001030 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001031 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001032 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001033 else if (Literal.isUTF16())
1034 StrTy = Context.Char16Ty;
1035 else if (Literal.isUTF32())
1036 StrTy = Context.Char32Ty;
Anders Carlsson6b06e182011-04-06 18:42:48 +00001037 else if (Literal.Pascal)
1038 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001039
Douglas Gregorfb65e592011-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 Gregoraa1e21d2008-09-12 00:47:35 +00001050 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +00001051 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001052 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001053
Chris Lattner36fc8792008-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 Lattnerd42c29f2009-02-26 23:01:51 +00001058 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001059 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001060
Chris Lattner5b183d82006-11-10 05:03:26 +00001061 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +00001062 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001063 Kind, Literal.Pascal, StrTy,
Alexis Hunt3b791862010-08-30 17:47:05 +00001064 &StringTokLocs[0],
1065 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +00001066}
1067
John McCallc63de662011-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 McCall351762c2011-02-07 10:33:21 +00001075 /// A by-ref capture is required.
1076 CR_CaptureByRef,
1077
John McCallc63de662011-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 Lattner2a9d9892008-10-20 05:16:36 +00001083///
John McCallc63de662011-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 McCall351762c2011-02-07 10:33:21 +00001087diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-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 Stump11289f42009-09-09 15:08:12 +00001093
John McCallc63de662011-02-02 13:00:07 +00001094 case Sema::PotentiallyEvaluated:
1095 case Sema::PotentiallyEvaluatedIfUsed:
1096 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +00001097
John McCallc63de662011-02-02 13:00:07 +00001098 case Sema::PotentiallyPotentiallyEvaluated:
1099 // FIXME: delay these!
1100 break;
Chris Lattner497d7b02009-04-21 22:26:47 +00001101 }
Mike Stump11289f42009-09-09 15:08:12 +00001102
John McCallc63de662011-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 McCall92d627e2011-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 McCallc63de662011-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 Stump11289f42009-09-09 15:08:12 +00001134}
1135
John McCall351762c2011-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 McCallc63de662011-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 McCall351762c2011-02-07 10:33:21 +00001160static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001161 ValueDecl *value) {
1162 // Only variables ever require capture.
1163 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +00001164 if (!var) return CR_NoCapture;
John McCallc63de662011-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 McCallc63de662011-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 McCall351762c2011-02-07 10:33:21 +00001181 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-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 McCall351762c2011-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 McCallc63de662011-02-02 13:00:07 +00001192
1193 functionScopesIndex--;
1194 DC = cast<BlockDecl>(DC)->getDeclContext();
1195 } while (var->getDeclContext() != DC);
1196
John McCall351762c2011-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 McCalla85af562011-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 McCall351762c2011-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 McCallc63de662011-02-02 13:00:07 +00001299}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001300
John McCalldadc5752010-08-24 06:29:42 +00001301ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001302Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001303 SourceLocation Loc,
1304 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001305 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001306 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001307}
1308
John McCallf4cd4f92011-02-09 01:13:10 +00001309/// BuildDeclRefExpr - Build an expression that references a
1310/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001311ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001312Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001313 const DeclarationNameInfo &NameInfo,
1314 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001315 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001316
John McCall086a4642010-11-24 05:12:34 +00001317 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001318 SS? SS->getWithLocInContext(Context)
1319 : NestedNameSpecifierLoc(),
John McCall086a4642010-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 Gregorc7acfdf2009-01-06 05:10:23 +00001327}
1328
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001329/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-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 Trieucfc491d2011-08-02 04:35:43 +00001338void
1339Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1340 TemplateArgumentListInfo &Buffer,
1341 DeclarationNameInfo &NameInfo,
1342 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-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 Gregor5476205b2011-06-23 00:49:38 +00001347 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001348 Id.TemplateId->getTemplateArgs(),
1349 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001350 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001351 TemplateArgsPtr.release();
1352
John McCall3e56fd42010-08-23 07:28:44 +00001353 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001354 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001355 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001356 TemplateArgs = &Buffer;
1357 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001358 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001359 TemplateArgs = 0;
1360 }
1361}
1362
John McCalld681c392009-12-16 08:11:27 +00001363/// Diagnose an empty lookup.
1364///
1365/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001366bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001367 CorrectTypoContext CTC,
1368 TemplateArgumentListInfo *ExplicitTemplateArgs,
1369 Expr **Args, unsigned NumArgs) {
John McCalld681c392009-12-16 08:11:27 +00001370 DeclarationName Name = R.getLookupName();
1371
John McCalld681c392009-12-16 08:11:27 +00001372 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001373 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001374 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1375 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001376 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001377 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001378 diagnostic_suggest = diag::err_undeclared_use_suggest;
1379 }
John McCalld681c392009-12-16 08:11:27 +00001380
Douglas Gregor598b08f2009-12-31 05:20:13 +00001381 // If the original lookup was an unqualified lookup, fake an
1382 // unqualified lookup. This is useful when (for example) the
1383 // original lookup would not have found something because it was a
1384 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001385 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001386 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001387 if (isa<CXXRecordDecl>(DC)) {
1388 LookupQualifiedName(R, DC);
1389
1390 if (!R.empty()) {
1391 // Don't give errors about ambiguities in this lookup.
1392 R.suppressDiagnostics();
1393
1394 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1395 bool isInstance = CurMethod &&
1396 CurMethod->isInstance() &&
1397 DC == CurMethod->getParent();
1398
1399 // Give a code modification hint to insert 'this->'.
1400 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1401 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001402 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001403 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1404 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001405 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001406 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001407 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001408 Diag(R.getNameLoc(), diagnostic) << Name
1409 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1410 QualType DepThisType = DepMethod->getThisType(Context);
1411 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1412 R.getNameLoc(), DepThisType, false);
1413 TemplateArgumentListInfo TList;
1414 if (ULE->hasExplicitTemplateArgs())
1415 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001416
Douglas Gregore16af532011-02-28 18:50:33 +00001417 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001418 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001419 CXXDependentScopeMemberExpr *DepExpr =
1420 CXXDependentScopeMemberExpr::Create(
1421 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001422 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyfe712382010-08-20 20:54:15 +00001423 R.getLookupNameInfo(), &TList);
1424 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001425 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001426 // FIXME: we should be able to handle this case too. It is correct
1427 // to add this-> here. This is a workaround for PR7947.
1428 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001429 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001430 } else {
John McCalld681c392009-12-16 08:11:27 +00001431 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001432 }
John McCalld681c392009-12-16 08:11:27 +00001433
1434 // Do we really want to note all of these?
1435 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1436 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1437
1438 // Tell the callee to try to recover.
1439 return false;
1440 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001441
1442 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001443 }
1444 }
1445
Douglas Gregor598b08f2009-12-31 05:20:13 +00001446 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001447 TypoCorrection Corrected;
1448 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1449 S, &SS, NULL, false, CTC))) {
1450 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1451 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1452 R.setLookupName(Corrected.getCorrection());
1453
Hans Wennborg38198de2011-07-12 08:45:31 +00001454 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001455 if (Corrected.isOverloaded()) {
1456 OverloadCandidateSet OCS(R.getNameLoc());
1457 OverloadCandidateSet::iterator Best;
1458 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1459 CDEnd = Corrected.end();
1460 CD != CDEnd; ++CD) {
1461 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001462 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001463 Args, NumArgs, OCS);
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001464 else if (FunctionTemplateDecl *FTD =
1465 dyn_cast<FunctionTemplateDecl>(*CD))
1466 AddTemplateOverloadCandidate(
1467 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1468 Args, NumArgs, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001469 }
1470 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1471 case OR_Success:
1472 ND = Best->Function;
1473 break;
1474 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001475 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001476 }
1477 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001478 R.addDecl(ND);
1479 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001480 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001481 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1482 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001483 else
1484 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001485 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001486 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001487 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1488 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001489 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001490 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001491
1492 // Tell the callee to try to recover.
1493 return false;
1494 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001495
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001496 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001497 // FIXME: If we ended up with a typo for a type name or
1498 // Objective-C class name, we're in trouble because the parser
1499 // is in the wrong place to recover. Suggest the typo
1500 // correction, but don't make it a fix-it since we're not going
1501 // to recover well anyway.
1502 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001503 Diag(R.getNameLoc(), diagnostic_suggest)
1504 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001505 else
1506 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001507 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001508 << SS.getRange();
1509
1510 // Don't try to recover; it won't work.
1511 return true;
1512 }
1513 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001514 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001515 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001516 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001517 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001518 else
Douglas Gregor25363982010-01-01 00:15:04 +00001519 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001520 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001521 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001522 return true;
1523 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001524 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001525 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001526
1527 // Emit a special diagnostic for failed member lookups.
1528 // FIXME: computing the declaration context might fail here (?)
1529 if (!SS.isEmpty()) {
1530 Diag(R.getNameLoc(), diag::err_no_member)
1531 << Name << computeDeclContext(SS, false)
1532 << SS.getRange();
1533 return true;
1534 }
1535
John McCalld681c392009-12-16 08:11:27 +00001536 // Give up, we can't recover.
1537 Diag(R.getNameLoc(), diagnostic) << Name;
1538 return true;
1539}
1540
Douglas Gregor05fcf842010-11-02 20:36:02 +00001541ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1542 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001543 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1544 if (!IDecl)
1545 return 0;
1546 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1547 if (!ClassImpDecl)
1548 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001549 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001550 if (!property)
1551 return 0;
1552 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001553 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1554 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001555 return 0;
1556 return property;
1557}
1558
Douglas Gregor05fcf842010-11-02 20:36:02 +00001559bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1560 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1561 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1562 if (!IDecl)
1563 return false;
1564 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1565 if (!ClassImpDecl)
1566 return false;
1567 if (ObjCPropertyImplDecl *PIDecl
1568 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1569 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1570 PIDecl->getPropertyIvarDecl())
1571 return false;
1572
1573 return true;
1574}
1575
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001576ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1577 IdentifierInfo *II,
1578 SourceLocation NameLoc) {
1579 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001580 bool LookForIvars;
1581 if (Lookup.empty())
1582 LookForIvars = true;
1583 else if (CurMeth->isClassMethod())
1584 LookForIvars = false;
1585 else
1586 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001587 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1588 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001589 if (!LookForIvars)
1590 return 0;
1591
Fariborz Jahanian18722982010-07-17 00:59:30 +00001592 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1593 if (!IDecl)
1594 return 0;
1595 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001596 if (!ClassImpDecl)
1597 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001598 bool DynamicImplSeen = false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001599 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian18722982010-07-17 00:59:30 +00001600 if (!property)
1601 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001602 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001603 DynamicImplSeen =
1604 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001605 // property implementation has a designated ivar. No need to assume a new
1606 // one.
1607 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1608 return 0;
1609 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001610 if (!DynamicImplSeen) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001611 QualType PropType = Context.getCanonicalType(property->getType());
1612 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001613 NameLoc, NameLoc,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001614 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001615 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001616 (Expr *)0, true);
1617 ClassImpDecl->addDecl(Ivar);
1618 IDecl->makeDeclVisibleInContext(Ivar, false);
1619 property->setPropertyIvarDecl(Ivar);
1620 return Ivar;
1621 }
1622 return 0;
1623}
1624
John McCalldadc5752010-08-24 06:29:42 +00001625ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001626 CXXScopeSpec &SS,
1627 UnqualifiedId &Id,
1628 bool HasTrailingLParen,
1629 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001630 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1631 "cannot be direct & operand and have a trailing lparen");
1632
1633 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001634 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001635
John McCall10eae182009-11-30 22:42:35 +00001636 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001637
1638 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001639 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001640 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001641 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001642
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001643 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001644 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001645 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001646
John McCalle66edc12009-11-24 19:00:30 +00001647 // C++ [temp.dep.expr]p3:
1648 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001649 // -- an identifier that was declared with a dependent type,
1650 // (note: handled after lookup)
1651 // -- a template-id that is dependent,
1652 // (note: handled in BuildTemplateIdExpr)
1653 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001654 // -- a nested-name-specifier that contains a class-name that
1655 // names a dependent type.
1656 // Determine whether this is a member of an unknown specialization;
1657 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001658 bool DependentID = false;
1659 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1660 Name.getCXXNameType()->isDependentType()) {
1661 DependentID = true;
1662 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001663 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001664 if (RequireCompleteDeclContext(SS, DC))
1665 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001666 } else {
1667 DependentID = true;
1668 }
1669 }
1670
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001671 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001672 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001673 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001674
Fariborz Jahanian86151342010-07-22 23:33:21 +00001675 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001676 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001677 LookupResult R(*this, NameInfo,
1678 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1679 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001680 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001681 // Lookup the template name again to correctly establish the context in
1682 // which it was found. This is really unfortunate as we already did the
1683 // lookup to determine that it was a template name in the first place. If
1684 // this becomes a performance hit, we can work harder to preserve those
1685 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001686 bool MemberOfUnknownSpecialization;
1687 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1688 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001689
1690 if (MemberOfUnknownSpecialization ||
1691 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1692 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1693 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001694 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001695 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001696 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001697
Douglas Gregora5226932011-02-04 13:35:07 +00001698 // If the result might be in a dependent base class, this is a dependent
1699 // id-expression.
1700 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1701 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1702 TemplateArgs);
1703
John McCalle66edc12009-11-24 19:00:30 +00001704 // If this reference is in an Objective-C method, then we need to do
1705 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001706 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001707 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001708 if (E.isInvalid())
1709 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001710
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001711 if (Expr *Ex = E.takeAs<Expr>())
1712 return Owned(Ex);
1713
1714 // Synthesize ivars lazily.
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001715 if (getLangOptions().ObjCDefaultSynthProperties &&
1716 getLangOptions().ObjCNonFragileABI2) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001717 if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001718 if (const ObjCPropertyDecl *Property =
1719 canSynthesizeProvisionalIvar(II)) {
1720 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1721 Diag(Property->getLocation(), diag::note_property_declare);
1722 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001723 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1724 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001725 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001726 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001727 // for further use, this must be set to false if in class method.
1728 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001729 }
Chris Lattner59a25942008-03-31 00:36:02 +00001730 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001731
John McCalle66edc12009-11-24 19:00:30 +00001732 if (R.isAmbiguous())
1733 return ExprError();
1734
Douglas Gregor171c45a2009-02-18 21:56:37 +00001735 // Determine whether this name might be a candidate for
1736 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001737 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001738
John McCalle66edc12009-11-24 19:00:30 +00001739 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001740 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001741 // in C90, extension in C99, forbidden in C++).
1742 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1743 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1744 if (D) R.addDecl(D);
1745 }
1746
1747 // If this name wasn't predeclared and if this is not a function
1748 // call, diagnose the problem.
1749 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001750 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001751 return ExprError();
1752
1753 assert(!R.empty() &&
1754 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001755
1756 // If we found an Objective-C instance variable, let
1757 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001758 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001759 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1760 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001761 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001762 assert(E.isInvalid() || E.get());
1763 return move(E);
1764 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001765 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001766 }
Mike Stump11289f42009-09-09 15:08:12 +00001767
John McCalle66edc12009-11-24 19:00:30 +00001768 // This is guaranteed from this point on.
1769 assert(!R.empty() || ADL);
1770
John McCall2d74de92009-12-01 22:10:20 +00001771 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001772 // C++ [class.mfct.non-static]p3:
1773 // When an id-expression that is not part of a class member access
1774 // syntax and not used to form a pointer to member is used in the
1775 // body of a non-static member function of class X, if name lookup
1776 // resolves the name in the id-expression to a non-static non-type
1777 // member of some class C, the id-expression is transformed into a
1778 // class member access expression using (*this) as the
1779 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001780 //
1781 // But we don't actually need to do this for '&' operands if R
1782 // resolved to a function or overloaded function set, because the
1783 // expression is ill-formed if it actually works out to be a
1784 // non-static member function:
1785 //
1786 // C++ [expr.ref]p4:
1787 // Otherwise, if E1.E2 refers to a non-static member function. . .
1788 // [t]he expression can be used only as the left-hand operand of a
1789 // member function call.
1790 //
1791 // There are other safeguards against such uses, but it's important
1792 // to get this right here so that we don't end up making a
1793 // spuriously dependent expression if we're inside a dependent
1794 // instance method.
John McCall57500772009-12-16 12:17:52 +00001795 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001796 bool MightBeImplicitMember;
1797 if (!isAddressOfOperand)
1798 MightBeImplicitMember = true;
1799 else if (!SS.isEmpty())
1800 MightBeImplicitMember = false;
1801 else if (R.isOverloadedResult())
1802 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001803 else if (R.isUnresolvableResult())
1804 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001805 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001806 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1807 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001808
1809 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001810 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001811 }
1812
John McCalle66edc12009-11-24 19:00:30 +00001813 if (TemplateArgs)
1814 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001815
John McCalle66edc12009-11-24 19:00:30 +00001816 return BuildDeclarationNameExpr(SS, R, ADL);
1817}
1818
John McCall10eae182009-11-30 22:42:35 +00001819/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1820/// declaration name, generally during template instantiation.
1821/// There's a large number of things which don't need to be done along
1822/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001823ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001824Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001825 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001826 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001827 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001828 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001829
John McCall0b66eb32010-05-01 00:40:08 +00001830 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001831 return ExprError();
1832
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001833 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001834 LookupQualifiedName(R, DC);
1835
1836 if (R.isAmbiguous())
1837 return ExprError();
1838
1839 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001840 Diag(NameInfo.getLoc(), diag::err_no_member)
1841 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001842 return ExprError();
1843 }
1844
1845 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1846}
1847
1848/// LookupInObjCMethod - The parser has read a name in, and Sema has
1849/// detected that we're currently inside an ObjC method. Perform some
1850/// additional lookup.
1851///
1852/// Ideally, most of this would be done by lookup, but there's
1853/// actually quite a lot of extra work involved.
1854///
1855/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001856ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001857Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001858 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001859 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001860 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001861
John McCalle66edc12009-11-24 19:00:30 +00001862 // There are two cases to handle here. 1) scoped lookup could have failed,
1863 // in which case we should look for an ivar. 2) scoped lookup could have
1864 // found a decl, but that decl is outside the current instance method (i.e.
1865 // a global variable). In these two cases, we do a lookup for an ivar with
1866 // this name, if the lookup sucedes, we replace it our current decl.
1867
1868 // If we're in a class method, we don't normally want to look for
1869 // ivars. But if we don't find anything else, and there's an
1870 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001871 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001872
1873 bool LookForIvars;
1874 if (Lookup.empty())
1875 LookForIvars = true;
1876 else if (IsClassMethod)
1877 LookForIvars = false;
1878 else
1879 LookForIvars = (Lookup.isSingleResult() &&
1880 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001881 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001882 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001883 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001884 ObjCInterfaceDecl *ClassDeclared;
1885 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1886 // Diagnose using an ivar in a class method.
1887 if (IsClassMethod)
1888 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1889 << IV->getDeclName());
1890
1891 // If we're referencing an invalid decl, just return this as a silent
1892 // error node. The error diagnostic was already emitted on the decl.
1893 if (IV->isInvalidDecl())
1894 return ExprError();
1895
1896 // Check if referencing a field with __attribute__((deprecated)).
1897 if (DiagnoseUseOfDecl(IV, Loc))
1898 return ExprError();
1899
1900 // Diagnose the use of an ivar outside of the declaring class.
1901 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1902 ClassDeclared != IFace)
1903 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1904
1905 // FIXME: This should use a new expr for a direct reference, don't
1906 // turn this into Self->ivar, just return a BareIVarExpr or something.
1907 IdentifierInfo &II = Context.Idents.get("self");
1908 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001909 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001910 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001911 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001912 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001913 SelfName, false, false);
1914 if (SelfExpr.isInvalid())
1915 return ExprError();
1916
John Wiegley01296292011-04-08 18:41:53 +00001917 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1918 if (SelfExpr.isInvalid())
1919 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001920
John McCalle66edc12009-11-24 19:00:30 +00001921 MarkDeclarationReferenced(Loc, IV);
1922 return Owned(new (Context)
1923 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001924 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001925 }
Chris Lattner87313662010-04-12 05:10:17 +00001926 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001927 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001928 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001929 ObjCInterfaceDecl *ClassDeclared;
1930 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1931 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1932 IFace == ClassDeclared)
1933 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1934 }
1935 }
1936
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001937 if (Lookup.empty() && II && AllowBuiltinCreation) {
1938 // FIXME. Consolidate this with similar code in LookupName.
1939 if (unsigned BuiltinID = II->getBuiltinID()) {
1940 if (!(getLangOptions().CPlusPlus &&
1941 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1942 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1943 S, Lookup.isForRedeclaration(),
1944 Lookup.getNameLoc());
1945 if (D) Lookup.addDecl(D);
1946 }
1947 }
1948 }
John McCalle66edc12009-11-24 19:00:30 +00001949 // Sentinel value saying that we didn't do anything special.
1950 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001951}
John McCalld14a8642009-11-21 08:51:07 +00001952
John McCall16df1e52010-03-30 21:47:33 +00001953/// \brief Cast a base object to a member's actual type.
1954///
1955/// Logically this happens in three phases:
1956///
1957/// * First we cast from the base type to the naming class.
1958/// The naming class is the class into which we were looking
1959/// when we found the member; it's the qualifier type if a
1960/// qualifier was provided, and otherwise it's the base type.
1961///
1962/// * Next we cast from the naming class to the declaring class.
1963/// If the member we found was brought into a class's scope by
1964/// a using declaration, this is that class; otherwise it's
1965/// the class declaring the member.
1966///
1967/// * Finally we cast from the declaring class to the "true"
1968/// declaring class of the member. This conversion does not
1969/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001970ExprResult
1971Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001972 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001973 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001974 NamedDecl *Member) {
1975 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1976 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001977 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001978
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001979 QualType DestRecordType;
1980 QualType DestType;
1981 QualType FromRecordType;
1982 QualType FromType = From->getType();
1983 bool PointerConversions = false;
1984 if (isa<FieldDecl>(Member)) {
1985 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001986
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001987 if (FromType->getAs<PointerType>()) {
1988 DestType = Context.getPointerType(DestRecordType);
1989 FromRecordType = FromType->getPointeeType();
1990 PointerConversions = true;
1991 } else {
1992 DestType = DestRecordType;
1993 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001994 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001995 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1996 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00001997 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001998
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001999 DestType = Method->getThisType(Context);
2000 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002001
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002002 if (FromType->getAs<PointerType>()) {
2003 FromRecordType = FromType->getPointeeType();
2004 PointerConversions = true;
2005 } else {
2006 FromRecordType = FromType;
2007 DestType = DestRecordType;
2008 }
2009 } else {
2010 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00002011 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002012 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002013
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002014 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002015 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002016
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002017 // If the unqualified types are the same, no conversion is necessary.
2018 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002019 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002020
John McCall16df1e52010-03-30 21:47:33 +00002021 SourceRange FromRange = From->getSourceRange();
2022 SourceLocation FromLoc = FromRange.getBegin();
2023
John McCall2536c6d2010-08-25 10:28:54 +00002024 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002025
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002026 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002027 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002028 // class name.
2029 //
2030 // If the member was a qualified name and the qualified referred to a
2031 // specific base subobject type, we'll cast to that intermediate type
2032 // first and then to the object in which the member is declared. That allows
2033 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2034 //
2035 // class Base { public: int x; };
2036 // class Derived1 : public Base { };
2037 // class Derived2 : public Base { };
2038 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2039 //
2040 // void VeryDerived::f() {
2041 // x = 17; // error: ambiguous base subobjects
2042 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2043 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002044 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002045 QualType QType = QualType(Qualifier->getAsType(), 0);
2046 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2047 assert(QType->isRecordType() && "lookup done with non-record type");
2048
2049 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2050
2051 // In C++98, the qualifier type doesn't actually have to be a base
2052 // type of the object type, in which case we just ignore it.
2053 // Otherwise build the appropriate casts.
2054 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002055 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002056 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002057 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002058 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002059
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002060 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002061 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002062 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2063 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002064
2065 FromType = QType;
2066 FromRecordType = QRecordType;
2067
2068 // If the qualifier type was the same as the destination type,
2069 // we're done.
2070 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002071 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002072 }
2073 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002074
John McCall16df1e52010-03-30 21:47:33 +00002075 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002076
John McCall16df1e52010-03-30 21:47:33 +00002077 // If we actually found the member through a using declaration, cast
2078 // down to the using declaration's type.
2079 //
2080 // Pointer equality is fine here because only one declaration of a
2081 // class ever has member declarations.
2082 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2083 assert(isa<UsingShadowDecl>(FoundDecl));
2084 QualType URecordType = Context.getTypeDeclType(
2085 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2086
2087 // We only need to do this if the naming-class to declaring-class
2088 // conversion is non-trivial.
2089 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2090 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002091 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002092 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002093 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002094 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002095
John McCall16df1e52010-03-30 21:47:33 +00002096 QualType UType = URecordType;
2097 if (PointerConversions)
2098 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002099 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2100 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002101 FromType = UType;
2102 FromRecordType = URecordType;
2103 }
2104
2105 // We don't do access control for the conversion from the
2106 // declaring class to the true declaring class.
2107 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002108 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002109
John McCallcf142162010-08-07 06:22:56 +00002110 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002111 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2112 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002113 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002114 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002115
John Wiegley01296292011-04-08 18:41:53 +00002116 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2117 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002118}
Douglas Gregor3256d042009-06-30 15:47:41 +00002119
John McCalle66edc12009-11-24 19:00:30 +00002120bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002121 const LookupResult &R,
2122 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002123 // Only when used directly as the postfix-expression of a call.
2124 if (!HasTrailingLParen)
2125 return false;
2126
2127 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002128 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002129 return false;
2130
2131 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002132 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002133 return false;
2134
2135 // Turn off ADL when we find certain kinds of declarations during
2136 // normal lookup:
2137 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2138 NamedDecl *D = *I;
2139
2140 // C++0x [basic.lookup.argdep]p3:
2141 // -- a declaration of a class member
2142 // Since using decls preserve this property, we check this on the
2143 // original decl.
John McCall57500772009-12-16 12:17:52 +00002144 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002145 return false;
2146
2147 // C++0x [basic.lookup.argdep]p3:
2148 // -- a block-scope function declaration that is not a
2149 // using-declaration
2150 // NOTE: we also trigger this for function templates (in fact, we
2151 // don't check the decl type at all, since all other decl types
2152 // turn off ADL anyway).
2153 if (isa<UsingShadowDecl>(D))
2154 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2155 else if (D->getDeclContext()->isFunctionOrMethod())
2156 return false;
2157
2158 // C++0x [basic.lookup.argdep]p3:
2159 // -- a declaration that is neither a function or a function
2160 // template
2161 // And also for builtin functions.
2162 if (isa<FunctionDecl>(D)) {
2163 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2164
2165 // But also builtin functions.
2166 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2167 return false;
2168 } else if (!isa<FunctionTemplateDecl>(D))
2169 return false;
2170 }
2171
2172 return true;
2173}
2174
2175
John McCalld14a8642009-11-21 08:51:07 +00002176/// Diagnoses obvious problems with the use of the given declaration
2177/// as an expression. This is only actually called for lookups that
2178/// were not overloaded, and it doesn't promise that the declaration
2179/// will in fact be used.
2180static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002181 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002182 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2183 return true;
2184 }
2185
2186 if (isa<ObjCInterfaceDecl>(D)) {
2187 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2188 return true;
2189 }
2190
2191 if (isa<NamespaceDecl>(D)) {
2192 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2193 return true;
2194 }
2195
2196 return false;
2197}
2198
John McCalldadc5752010-08-24 06:29:42 +00002199ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002200Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002201 LookupResult &R,
2202 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002203 // If this is a single, fully-resolved result and we don't need ADL,
2204 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002205 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002206 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2207 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002208
2209 // We only need to check the declaration if there's exactly one
2210 // result, because in the overloaded case the results can only be
2211 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002212 if (R.isSingleResult() &&
2213 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002214 return ExprError();
2215
John McCall58cc69d2010-01-27 01:50:18 +00002216 // Otherwise, just build an unresolved lookup expression. Suppress
2217 // any lookup-related diagnostics; we'll hash these out later, when
2218 // we've picked a target.
2219 R.suppressDiagnostics();
2220
John McCalld14a8642009-11-21 08:51:07 +00002221 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002222 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002223 SS.getWithLocInContext(Context),
2224 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002225 NeedsADL, R.isOverloadedResult(),
2226 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002227
2228 return Owned(ULE);
2229}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002230
John McCalld14a8642009-11-21 08:51:07 +00002231/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002232ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002233Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002234 const DeclarationNameInfo &NameInfo,
2235 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002236 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002237 assert(!isa<FunctionTemplateDecl>(D) &&
2238 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002239
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002240 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002241 if (CheckDeclInExpr(*this, Loc, D))
2242 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002243
Douglas Gregore7488b92009-12-01 16:58:18 +00002244 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2245 // Specifically diagnose references to class templates that are missing
2246 // a template argument list.
2247 Diag(Loc, diag::err_template_decl_ref)
2248 << Template << SS.getRange();
2249 Diag(Template->getLocation(), diag::note_template_decl_here);
2250 return ExprError();
2251 }
2252
2253 // Make sure that we're referring to a value.
2254 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2255 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002256 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002257 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002258 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002259 return ExprError();
2260 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002261
Douglas Gregor171c45a2009-02-18 21:56:37 +00002262 // Check whether this declaration can be used. Note that we suppress
2263 // this check when we're going to perform argument-dependent lookup
2264 // on this function name, because this might not be the function
2265 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002266 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002267 return ExprError();
2268
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002269 // Only create DeclRefExpr's for valid Decl's.
2270 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002271 return ExprError();
2272
John McCallf3a88602011-02-03 08:15:49 +00002273 // Handle members of anonymous structs and unions. If we got here,
2274 // and the reference is to a class member indirect field, then this
2275 // must be the subject of a pointer-to-member expression.
2276 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2277 if (!indirectField->isCXXClassMember())
2278 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2279 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002280
Chris Lattner2a9d9892008-10-20 05:16:36 +00002281 // If the identifier reference is inside a block, and it refers to a value
2282 // that is outside the block, create a BlockDeclRefExpr instead of a
2283 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2284 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002285 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002286 // We do not do this for things like enum constants, global variables, etc,
2287 // as they do not get snapshotted.
2288 //
John McCall351762c2011-02-07 10:33:21 +00002289 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002290 case CR_Error:
2291 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002292
John McCallc63de662011-02-02 13:00:07 +00002293 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002294 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2295 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2296
2297 case CR_CaptureByRef:
2298 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2299 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002300
2301 case CR_NoCapture: {
2302 // If this reference is not in a block or if the referenced
2303 // variable is within the block, create a normal DeclRefExpr.
2304
2305 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002306 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002307
2308 switch (D->getKind()) {
2309 // Ignore all the non-ValueDecl kinds.
2310#define ABSTRACT_DECL(kind)
2311#define VALUE(type, base)
2312#define DECL(type, base) \
2313 case Decl::type:
2314#include "clang/AST/DeclNodes.inc"
2315 llvm_unreachable("invalid value decl kind");
2316 return ExprError();
2317
2318 // These shouldn't make it here.
2319 case Decl::ObjCAtDefsField:
2320 case Decl::ObjCIvar:
2321 llvm_unreachable("forming non-member reference to ivar?");
2322 return ExprError();
2323
2324 // Enum constants are always r-values and never references.
2325 // Unresolved using declarations are dependent.
2326 case Decl::EnumConstant:
2327 case Decl::UnresolvedUsingValue:
2328 valueKind = VK_RValue;
2329 break;
2330
2331 // Fields and indirect fields that got here must be for
2332 // pointer-to-member expressions; we just call them l-values for
2333 // internal consistency, because this subexpression doesn't really
2334 // exist in the high-level semantics.
2335 case Decl::Field:
2336 case Decl::IndirectField:
2337 assert(getLangOptions().CPlusPlus &&
2338 "building reference to field in C?");
2339
2340 // These can't have reference type in well-formed programs, but
2341 // for internal consistency we do this anyway.
2342 type = type.getNonReferenceType();
2343 valueKind = VK_LValue;
2344 break;
2345
2346 // Non-type template parameters are either l-values or r-values
2347 // depending on the type.
2348 case Decl::NonTypeTemplateParm: {
2349 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2350 type = reftype->getPointeeType();
2351 valueKind = VK_LValue; // even if the parameter is an r-value reference
2352 break;
2353 }
2354
2355 // For non-references, we need to strip qualifiers just in case
2356 // the template parameter was declared as 'const int' or whatever.
2357 valueKind = VK_RValue;
2358 type = type.getUnqualifiedType();
2359 break;
2360 }
2361
2362 case Decl::Var:
2363 // In C, "extern void blah;" is valid and is an r-value.
2364 if (!getLangOptions().CPlusPlus &&
2365 !type.hasQualifiers() &&
2366 type->isVoidType()) {
2367 valueKind = VK_RValue;
2368 break;
2369 }
2370 // fallthrough
2371
2372 case Decl::ImplicitParam:
2373 case Decl::ParmVar:
2374 // These are always l-values.
2375 valueKind = VK_LValue;
2376 type = type.getNonReferenceType();
2377 break;
2378
2379 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002380 const FunctionType *fty = type->castAs<FunctionType>();
2381
2382 // If we're referring to a function with an __unknown_anytype
2383 // result type, make the entire expression __unknown_anytype.
2384 if (fty->getResultType() == Context.UnknownAnyTy) {
2385 type = Context.UnknownAnyTy;
2386 valueKind = VK_RValue;
2387 break;
2388 }
2389
John McCallf4cd4f92011-02-09 01:13:10 +00002390 // Functions are l-values in C++.
2391 if (getLangOptions().CPlusPlus) {
2392 valueKind = VK_LValue;
2393 break;
2394 }
2395
2396 // C99 DR 316 says that, if a function type comes from a
2397 // function definition (without a prototype), that type is only
2398 // used for checking compatibility. Therefore, when referencing
2399 // the function, we pretend that we don't have the full function
2400 // type.
John McCall2979fe02011-04-12 00:42:48 +00002401 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2402 isa<FunctionProtoType>(fty))
2403 type = Context.getFunctionNoProtoType(fty->getResultType(),
2404 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002405
2406 // Functions are r-values in C.
2407 valueKind = VK_RValue;
2408 break;
2409 }
2410
2411 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002412 // If we're referring to a method with an __unknown_anytype
2413 // result type, make the entire expression __unknown_anytype.
2414 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002415 if (const FunctionProtoType *proto
2416 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002417 if (proto->getResultType() == Context.UnknownAnyTy) {
2418 type = Context.UnknownAnyTy;
2419 valueKind = VK_RValue;
2420 break;
2421 }
2422
John McCallf4cd4f92011-02-09 01:13:10 +00002423 // C++ methods are l-values if static, r-values if non-static.
2424 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2425 valueKind = VK_LValue;
2426 break;
2427 }
2428 // fallthrough
2429
2430 case Decl::CXXConversion:
2431 case Decl::CXXDestructor:
2432 case Decl::CXXConstructor:
2433 valueKind = VK_RValue;
2434 break;
2435 }
2436
2437 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2438 }
2439
John McCallc63de662011-02-02 13:00:07 +00002440 }
John McCall7decc9e2010-11-18 06:31:45 +00002441
John McCall351762c2011-02-07 10:33:21 +00002442 llvm_unreachable("unknown capture result");
2443 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002444}
Chris Lattnere168f762006-11-10 05:29:30 +00002445
John McCall2979fe02011-04-12 00:42:48 +00002446ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002447 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002448
Chris Lattnere168f762006-11-10 05:29:30 +00002449 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002450 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002451 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2452 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2453 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002454 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002455
Chris Lattnera81a0272008-01-12 08:14:25 +00002456 // Pre-defined identifiers are of type char[x], where x is the length of the
2457 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002458
Anders Carlsson2fb08242009-09-08 18:24:21 +00002459 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002460 if (!currentDecl && getCurBlock())
2461 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002462 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002463 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002464 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002465 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002466
Anders Carlsson0b209a82009-09-11 01:22:35 +00002467 QualType ResTy;
2468 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2469 ResTy = Context.DependentTy;
2470 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002471 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002472
Anders Carlsson0b209a82009-09-11 01:22:35 +00002473 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002474 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002475 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2476 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002477 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002478}
2479
John McCalldadc5752010-08-24 06:29:42 +00002480ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002481 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002482 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002483 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002484 if (Invalid)
2485 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002486
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002487 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002488 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002489 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002490 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002491
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002492 QualType Ty;
2493 if (!getLangOptions().CPlusPlus)
2494 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2495 else if (Literal.isWide())
2496 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002497 else if (Literal.isUTF16())
2498 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2499 else if (Literal.isUTF32())
2500 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002501 else if (Literal.isMultiChar())
2502 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002503 else
2504 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002505
Douglas Gregorfb65e592011-07-27 05:40:30 +00002506 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2507 if (Literal.isWide())
2508 Kind = CharacterLiteral::Wide;
2509 else if (Literal.isUTF16())
2510 Kind = CharacterLiteral::UTF16;
2511 else if (Literal.isUTF32())
2512 Kind = CharacterLiteral::UTF32;
2513
2514 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2515 Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002516}
2517
John McCalldadc5752010-08-24 06:29:42 +00002518ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002519 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002520 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2521 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002522 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002523 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002524 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002525 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002526 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002527
Chris Lattner23b7eb62007-06-15 23:05:46 +00002528 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002529 // Add padding so that NumericLiteralParser can overread by one character.
2530 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002531 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002532
Chris Lattner67ca9252007-05-21 01:08:44 +00002533 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002534 bool Invalid = false;
2535 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2536 if (Invalid)
2537 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002538
Mike Stump11289f42009-09-09 15:08:12 +00002539 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002540 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002541 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002542 return ExprError();
2543
Chris Lattner1c20a172007-08-26 03:42:43 +00002544 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002545
Chris Lattner1c20a172007-08-26 03:42:43 +00002546 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002547 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002548 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002549 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002550 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002551 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002552 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002553 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002554
2555 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2556
John McCall53b93a02009-12-24 09:08:04 +00002557 using llvm::APFloat;
2558 APFloat Val(Format);
2559
2560 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002561
2562 // Overflow is always an error, but underflow is only an error if
2563 // we underflowed to zero (APFloat reports denormals as underflow).
2564 if ((result & APFloat::opOverflow) ||
2565 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002566 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002567 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002568 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002569 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002570 APFloat::getLargest(Format).toString(buffer);
2571 } else {
John McCall62abc942010-02-26 23:35:57 +00002572 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002573 APFloat::getSmallest(Format).toString(buffer);
2574 }
2575
2576 Diag(Tok.getLocation(), diagnostic)
2577 << Ty
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002578 << StringRef(buffer.data(), buffer.size());
John McCall53b93a02009-12-24 09:08:04 +00002579 }
2580
2581 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002582 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002583
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002584 if (Ty == Context.DoubleTy) {
2585 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002586 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002587 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2588 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002589 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002590 }
2591 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002592 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002593 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002594 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002595 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002596
Neil Boothac582c52007-08-29 22:00:19 +00002597 // long long is a C99 feature.
2598 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002599 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002600 Diag(Tok.getLocation(), diag::ext_longlong);
2601
Chris Lattner67ca9252007-05-21 01:08:44 +00002602 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002603 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002604
Chris Lattner67ca9252007-05-21 01:08:44 +00002605 if (Literal.GetIntegerValue(ResultVal)) {
2606 // If this value didn't fit into uintmax_t, warn and force to ull.
2607 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002608 Ty = Context.UnsignedLongLongTy;
2609 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002610 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002611 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002612 // If this value fits into a ULL, try to figure out what else it fits into
2613 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002614
Chris Lattner67ca9252007-05-21 01:08:44 +00002615 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2616 // be an unsigned int.
2617 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2618
2619 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002620 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002621 if (!Literal.isLong && !Literal.isLongLong) {
2622 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002623 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002624
Chris Lattner67ca9252007-05-21 01:08:44 +00002625 // Does it fit in a unsigned int?
2626 if (ResultVal.isIntN(IntSize)) {
2627 // Does it fit in a signed int?
2628 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002629 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002630 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002631 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002632 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002633 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002634 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002635
Chris Lattner67ca9252007-05-21 01:08:44 +00002636 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002637 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002638 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002639
Chris Lattner67ca9252007-05-21 01:08:44 +00002640 // Does it fit in a unsigned long?
2641 if (ResultVal.isIntN(LongSize)) {
2642 // Does it fit in a signed long?
2643 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002644 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002645 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002646 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002647 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002648 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002649 }
2650
Chris Lattner67ca9252007-05-21 01:08:44 +00002651 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002652 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002653 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002654
Chris Lattner67ca9252007-05-21 01:08:44 +00002655 // Does it fit in a unsigned long long?
2656 if (ResultVal.isIntN(LongLongSize)) {
2657 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002658 // To be compatible with MSVC, hex integer literals ending with the
2659 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002660 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2661 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002662 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002663 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002664 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002665 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002666 }
2667 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002668
Chris Lattner67ca9252007-05-21 01:08:44 +00002669 // If we still couldn't decide a type, we probably have something that
2670 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002671 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002672 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002673 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002674 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002675 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002676
Chris Lattner55258cf2008-05-09 05:59:00 +00002677 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002678 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002679 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002680 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002681 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002682
Chris Lattner1c20a172007-08-26 03:42:43 +00002683 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2684 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002685 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002686 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002687
2688 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002689}
2690
John McCalldadc5752010-08-24 06:29:42 +00002691ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00002692 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002693 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002694 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002695}
2696
Chandler Carruth62da79c2011-05-26 08:53:12 +00002697static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2698 SourceLocation Loc,
2699 SourceRange ArgRange) {
2700 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2701 // scalar or vector data type argument..."
2702 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2703 // type (C99 6.2.5p18) or void.
2704 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2705 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2706 << T << ArgRange;
2707 return true;
2708 }
2709
2710 assert((T->isVoidType() || !T->isIncompleteType()) &&
2711 "Scalar types should always be complete");
2712 return false;
2713}
2714
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002715static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2716 SourceLocation Loc,
2717 SourceRange ArgRange,
2718 UnaryExprOrTypeTrait TraitKind) {
2719 // C99 6.5.3.4p1:
2720 if (T->isFunctionType()) {
2721 // alignof(function) is allowed as an extension.
2722 if (TraitKind == UETT_SizeOf)
2723 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2724 return false;
2725 }
2726
2727 // Allow sizeof(void)/alignof(void) as an extension.
2728 if (T->isVoidType()) {
2729 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2730 return false;
2731 }
2732
2733 return true;
2734}
2735
2736static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2737 SourceLocation Loc,
2738 SourceRange ArgRange,
2739 UnaryExprOrTypeTrait TraitKind) {
2740 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2741 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2742 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2743 << T << (TraitKind == UETT_SizeOf)
2744 << ArgRange;
2745 return true;
2746 }
2747
2748 return false;
2749}
2750
Chandler Carruth14502c22011-05-26 08:53:10 +00002751/// \brief Check the constrains on expression operands to unary type expression
2752/// and type traits.
2753///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002754/// Completes any types necessary and validates the constraints on the operand
2755/// expression. The logic mostly mirrors the type-based overload, but may modify
2756/// the expression as it completes the type for that expression through template
2757/// instantiation, etc.
Chandler Carruth14502c22011-05-26 08:53:10 +00002758bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op,
2759 UnaryExprOrTypeTrait ExprKind) {
Chandler Carruth7c430c02011-05-27 01:33:31 +00002760 QualType ExprTy = Op->getType();
2761
2762 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2763 // the result is the size of the referenced type."
2764 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2765 // result shall be the alignment of the referenced type."
2766 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2767 ExprTy = Ref->getPointeeType();
2768
2769 if (ExprKind == UETT_VecStep)
2770 return CheckVecStepTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2771 Op->getSourceRange());
2772
2773 // Whitelist some types as extensions
2774 if (!CheckExtensionTraitOperandType(*this, ExprTy, Op->getExprLoc(),
2775 Op->getSourceRange(), ExprKind))
2776 return false;
2777
2778 if (RequireCompleteExprType(Op,
2779 PDiag(diag::err_sizeof_alignof_incomplete_type)
2780 << ExprKind << Op->getSourceRange(),
2781 std::make_pair(SourceLocation(), PDiag(0))))
2782 return true;
2783
2784 // Completeing the expression's type may have changed it.
2785 ExprTy = Op->getType();
2786 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2787 ExprTy = Ref->getPointeeType();
2788
2789 if (CheckObjCTraitOperandConstraints(*this, ExprTy, Op->getExprLoc(),
2790 Op->getSourceRange(), ExprKind))
2791 return true;
2792
Nico Weber0870deb2011-06-15 02:47:03 +00002793 if (ExprKind == UETT_SizeOf) {
2794 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Op->IgnoreParens())) {
2795 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2796 QualType OType = PVD->getOriginalType();
2797 QualType Type = PVD->getType();
2798 if (Type->isPointerType() && OType->isArrayType()) {
2799 Diag(Op->getExprLoc(), diag::warn_sizeof_array_param)
2800 << Type << OType;
2801 Diag(PVD->getLocation(), diag::note_declared_at);
2802 }
2803 }
2804 }
2805 }
2806
Chandler Carruth7c430c02011-05-27 01:33:31 +00002807 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002808}
2809
2810/// \brief Check the constraints on operands to unary expression and type
2811/// traits.
2812///
2813/// This will complete any types necessary, and validate the various constraints
2814/// on those operands.
2815///
Steve Naroff71b59a92007-06-04 22:22:31 +00002816/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002817/// C99 6.3.2.1p[2-4] all state:
2818/// Except when it is the operand of the sizeof operator ...
2819///
2820/// C++ [expr.sizeof]p4
2821/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2822/// standard conversions are not applied to the operand of sizeof.
2823///
2824/// This policy is followed for all of the unary trait expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002825bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
2826 SourceLocation OpLoc,
2827 SourceRange ExprRange,
2828 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002829 if (exprType->isDependentType())
2830 return false;
2831
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002832 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2833 // the result is the size of the referenced type."
2834 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2835 // result shall be the alignment of the referenced type."
2836 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2837 exprType = Ref->getPointeeType();
2838
Chandler Carruth62da79c2011-05-26 08:53:12 +00002839 if (ExprKind == UETT_VecStep)
2840 return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002841
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002842 // Whitelist some types as extensions
2843 if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange,
2844 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00002845 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002846
Chris Lattner62975a72009-04-24 00:30:45 +00002847 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002848 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002849 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002850 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002851
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002852 if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange,
2853 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002854 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002855
Chris Lattner62975a72009-04-24 00:30:45 +00002856 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002857}
2858
Chandler Carruth14502c22011-05-26 08:53:10 +00002859static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002860 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002861
Mike Stump11289f42009-09-09 15:08:12 +00002862 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002863 if (isa<DeclRefExpr>(E))
2864 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002865
2866 // Cannot know anything else if the expression is dependent.
2867 if (E->isTypeDependent())
2868 return false;
2869
Douglas Gregor71235ec2009-05-02 02:18:30 +00002870 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002871 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2872 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00002873 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002874 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002875
2876 // Alignment of a field access is always okay, so long as it isn't a
2877 // bit-field.
2878 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002879 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002880 return false;
2881
Chandler Carruth14502c22011-05-26 08:53:10 +00002882 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002883}
2884
Chandler Carruth14502c22011-05-26 08:53:10 +00002885bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002886 E = E->IgnoreParens();
2887
2888 // Cannot know anything else if the expression is dependent.
2889 if (E->isTypeDependent())
2890 return false;
2891
Chandler Carruth14502c22011-05-26 08:53:10 +00002892 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002893}
2894
Douglas Gregor0950e412009-03-13 21:01:28 +00002895/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002896ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002897Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2898 SourceLocation OpLoc,
2899 UnaryExprOrTypeTrait ExprKind,
2900 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002901 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002902 return ExprError();
2903
John McCallbcd03502009-12-07 02:54:59 +00002904 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002905
Douglas Gregor0950e412009-03-13 21:01:28 +00002906 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002907 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002908 return ExprError();
2909
2910 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002911 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2912 Context.getSizeType(),
2913 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002914}
2915
2916/// \brief Build a sizeof or alignof expression given an expression
2917/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002918ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00002919Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2920 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00002921 ExprResult PE = CheckPlaceholderExpr(E);
2922 if (PE.isInvalid())
2923 return ExprError();
2924
2925 E = PE.get();
2926
Douglas Gregor0950e412009-03-13 21:01:28 +00002927 // Verify that the operand is valid.
2928 bool isInvalid = false;
2929 if (E->isTypeDependent()) {
2930 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002931 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002932 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002933 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002934 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002935 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00002936 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00002937 isInvalid = true;
2938 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00002939 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002940 }
2941
2942 if (isInvalid)
2943 return ExprError();
2944
2945 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00002946 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00002947 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00002948 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002949}
2950
Peter Collingbournee190dee2011-03-11 19:24:49 +00002951/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2952/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00002953/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002954ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002955Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2956 UnaryExprOrTypeTrait ExprKind, bool isType,
2957 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002958 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002959 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002960
Sebastian Redl6f282892008-11-11 17:56:53 +00002961 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00002962 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002963 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002964 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002965 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002966
Douglas Gregor0950e412009-03-13 21:01:28 +00002967 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00002968 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00002969 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002970}
2971
John Wiegley01296292011-04-08 18:41:53 +00002972static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall4bc41ae2010-11-18 19:01:18 +00002973 bool isReal) {
John Wiegley01296292011-04-08 18:41:53 +00002974 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002975 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002976
John McCall34376a62010-12-04 03:47:34 +00002977 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00002978 if (V.get()->getObjectKind() != OK_Ordinary) {
2979 V = S.DefaultLvalueConversion(V.take());
2980 if (V.isInvalid())
2981 return QualType();
2982 }
John McCall34376a62010-12-04 03:47:34 +00002983
Chris Lattnere267f5d2007-08-26 05:39:26 +00002984 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00002985 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002986 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002987
Chris Lattnere267f5d2007-08-26 05:39:26 +00002988 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00002989 if (V.get()->getType()->isArithmeticType())
2990 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002991
John McCall36226622010-10-12 02:09:17 +00002992 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00002993 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00002994 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00002995 if (PR.get() != V.get()) {
2996 V = move(PR);
John McCall4bc41ae2010-11-18 19:01:18 +00002997 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00002998 }
2999
Chris Lattnere267f5d2007-08-26 05:39:26 +00003000 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003001 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00003002 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003003 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003004}
3005
3006
Chris Lattnere168f762006-11-10 05:29:30 +00003007
John McCalldadc5752010-08-24 06:29:42 +00003008ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003009Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003010 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003011 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003012 switch (Kind) {
3013 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003014 case tok::plusplus: Opc = UO_PostInc; break;
3015 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003016 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003017
John McCallb268a282010-08-23 23:25:46 +00003018 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003019}
3020
John McCalldadc5752010-08-24 06:29:42 +00003021ExprResult
John McCallb268a282010-08-23 23:25:46 +00003022Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3023 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003024 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003025 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003026 if (Result.isInvalid()) return ExprError();
3027 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003028
John McCallb268a282010-08-23 23:25:46 +00003029 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003030
Douglas Gregor40412ac2008-11-19 17:17:41 +00003031 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003032 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003033 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003034 Context.DependentTy,
3035 VK_LValue, OK_Ordinary,
3036 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003037 }
3038
Mike Stump11289f42009-09-09 15:08:12 +00003039 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003040 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003041 LHSExp->getType()->isEnumeralType() ||
3042 RHSExp->getType()->isRecordType() ||
3043 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00003044 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003045 }
3046
John McCallb268a282010-08-23 23:25:46 +00003047 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003048}
3049
3050
John McCalldadc5752010-08-24 06:29:42 +00003051ExprResult
John McCallb268a282010-08-23 23:25:46 +00003052Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3053 Expr *Idx, SourceLocation RLoc) {
3054 Expr *LHSExp = Base;
3055 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003056
Chris Lattner36d572b2007-07-16 00:14:47 +00003057 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003058 if (!LHSExp->getType()->getAs<VectorType>()) {
3059 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3060 if (Result.isInvalid())
3061 return ExprError();
3062 LHSExp = Result.take();
3063 }
3064 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3065 if (Result.isInvalid())
3066 return ExprError();
3067 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003068
Chris Lattner36d572b2007-07-16 00:14:47 +00003069 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003070 ExprValueKind VK = VK_LValue;
3071 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003072
Steve Naroffc1aadb12007-03-28 21:49:40 +00003073 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003074 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003075 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003076 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003077 Expr *BaseExpr, *IndexExpr;
3078 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003079 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3080 BaseExpr = LHSExp;
3081 IndexExpr = RHSExp;
3082 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003083 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003084 BaseExpr = LHSExp;
3085 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003086 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003087 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003088 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003089 BaseExpr = RHSExp;
3090 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003091 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003092 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003093 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003094 BaseExpr = LHSExp;
3095 IndexExpr = RHSExp;
3096 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003097 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003098 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003099 // Handle the uncommon case of "123[Ptr]".
3100 BaseExpr = RHSExp;
3101 IndexExpr = LHSExp;
3102 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003103 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003104 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003105 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003106 VK = LHSExp->getValueKind();
3107 if (VK != VK_RValue)
3108 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003109
Chris Lattner36d572b2007-07-16 00:14:47 +00003110 // FIXME: need to deal with const...
3111 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003112 } else if (LHSTy->isArrayType()) {
3113 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003114 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003115 // wasn't promoted because of the C90 rule that doesn't
3116 // allow promoting non-lvalue arrays. Warn, then
3117 // force the promotion here.
3118 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3119 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003120 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3121 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003122 LHSTy = LHSExp->getType();
3123
3124 BaseExpr = LHSExp;
3125 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003126 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003127 } else if (RHSTy->isArrayType()) {
3128 // Same as previous, except for 123[f().a] case
3129 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3130 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003131 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3132 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003133 RHSTy = RHSExp->getType();
3134
3135 BaseExpr = RHSExp;
3136 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003137 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003138 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003139 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3140 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003141 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003142 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003143 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003144 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3145 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003146
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003147 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003148 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3149 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003150 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3151
Douglas Gregorac1fb652009-03-24 19:52:54 +00003152 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003153 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3154 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003155 // incomplete types are not object types.
3156 if (ResultType->isFunctionType()) {
3157 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3158 << ResultType << BaseExpr->getSourceRange();
3159 return ExprError();
3160 }
Mike Stump11289f42009-09-09 15:08:12 +00003161
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003162 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3163 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003164 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3165 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003166
3167 // C forbids expressions of unqualified void type from being l-values.
3168 // See IsCForbiddenLValueType.
3169 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003170 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003171 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003172 PDiag(diag::err_subscript_incomplete_type)
3173 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003174 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003175
Chris Lattner62975a72009-04-24 00:30:45 +00003176 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003177 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003178 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3179 << ResultType << BaseExpr->getSourceRange();
3180 return ExprError();
3181 }
Mike Stump11289f42009-09-09 15:08:12 +00003182
John McCall4bc41ae2010-11-18 19:01:18 +00003183 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003184 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003185
Mike Stump4e1f26a2009-02-19 03:04:26 +00003186 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003187 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003188}
3189
John McCalldadc5752010-08-24 06:29:42 +00003190ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003191 FunctionDecl *FD,
3192 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003193 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003194 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003195 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003196 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003197 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003198 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003199 return ExprError();
3200 }
3201
3202 if (Param->hasUninstantiatedDefaultArg()) {
3203 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003204
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003205 // Instantiate the expression.
3206 MultiLevelTemplateArgumentList ArgList
3207 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003208
Nico Weber44887f62010-11-29 18:19:25 +00003209 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003210 = ArgList.getInnermost();
3211 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3212 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003213
Nico Weber44887f62010-11-29 18:19:25 +00003214 ExprResult Result;
3215 {
3216 // C++ [dcl.fct.default]p5:
3217 // The names in the [default argument] expression are bound, and
3218 // the semantic constraints are checked, at the point where the
3219 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003220 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00003221 Result = SubstExpr(UninstExpr, ArgList);
3222 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003223 if (Result.isInvalid())
3224 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003225
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003226 // Check the expression as an initializer for the parameter.
3227 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003228 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003229 InitializationKind Kind
3230 = InitializationKind::CreateCopy(Param->getLocation(),
3231 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3232 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003233
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003234 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3235 Result = InitSeq.Perform(*this, Entity, Kind,
3236 MultiExprArg(*this, &ResultE, 1));
3237 if (Result.isInvalid())
3238 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003239
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003240 // Build the default argument expression.
3241 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3242 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003243 }
3244
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003245 // If the default expression creates temporaries, we need to
3246 // push them to the current stack of expression temporaries so they'll
3247 // be properly destroyed.
3248 // FIXME: We should really be rebuilding the default argument with new
3249 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003250 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3251 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3252 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3253 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3254 ExprTemporaries.push_back(Temporary);
John McCall31168b02011-06-15 23:02:42 +00003255 ExprNeedsCleanups = true;
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003256 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003257
3258 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003259 // Just mark all of the declarations in this potentially-evaluated expression
3260 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003261 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00003262 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003263}
3264
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003265/// ConvertArgumentsForCall - Converts the arguments specified in
3266/// Args/NumArgs to the parameter types of the function FDecl with
3267/// function prototype Proto. Call is the call expression itself, and
3268/// Fn is the function expression. For a C++ member function, this
3269/// routine does not attempt to convert the object argument. Returns
3270/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003271bool
3272Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003273 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003274 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003275 Expr **Args, unsigned NumArgs,
3276 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00003277 // Bail out early if calling a builtin with custom typechecking.
3278 // We don't need to do this in the
3279 if (FDecl)
3280 if (unsigned ID = FDecl->getBuiltinID())
3281 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3282 return false;
3283
Mike Stump4e1f26a2009-02-19 03:04:26 +00003284 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003285 // assignment, to the types of the corresponding parameter, ...
3286 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003287 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003288
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003289 // If too few arguments are available (and we don't have default
3290 // arguments for the remaining parameters), don't make the call.
3291 if (NumArgs < NumArgsInProto) {
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003292 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) {
3293 Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003294 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00003295 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003296
3297 // Emit the location of the prototype.
3298 if (FDecl && !FDecl->getBuiltinID())
3299 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3300 << FDecl;
3301
3302 return true;
3303 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003304 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003305 }
3306
3307 // If too many are passed and not variadic, error on the extras and drop
3308 // them.
3309 if (NumArgs > NumArgsInProto) {
3310 if (!Proto->isVariadic()) {
3311 Diag(Args[NumArgsInProto]->getLocStart(),
3312 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003313 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003314 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003315 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3316 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003317
3318 // Emit the location of the prototype.
3319 if (FDecl && !FDecl->getBuiltinID())
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003320 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3321 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003322
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003323 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003324 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003325 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003326 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003327 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003328 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003329 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003330 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3331 if (Fn->getType()->isBlockPointerType())
3332 CallType = VariadicBlock; // Block
3333 else if (isa<MemberExpr>(Fn))
3334 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003335 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003336 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003337 if (Invalid)
3338 return true;
3339 unsigned TotalNumArgs = AllArgs.size();
3340 for (unsigned i = 0; i < TotalNumArgs; ++i)
3341 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003342
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003343 return false;
3344}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003345
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003346bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3347 FunctionDecl *FDecl,
3348 const FunctionProtoType *Proto,
3349 unsigned FirstProtoArg,
3350 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003351 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003352 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003353 unsigned NumArgsInProto = Proto->getNumArgs();
3354 unsigned NumArgsToCheck = NumArgs;
3355 bool Invalid = false;
3356 if (NumArgs != NumArgsInProto)
3357 // Use default arguments for missing arguments
3358 NumArgsToCheck = NumArgsInProto;
3359 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003360 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003361 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003362 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003363
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003364 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003365 if (ArgIx < NumArgs) {
3366 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003367
Eli Friedman3164fb12009-03-22 22:00:50 +00003368 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3369 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003370 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003371 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003372 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003373
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003374 // Pass the argument
3375 ParmVarDecl *Param = 0;
3376 if (FDecl && i < FDecl->getNumParams())
3377 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003378
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003379 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003380 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003381 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3382 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003383 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003384 SourceLocation(),
3385 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003386 if (ArgE.isInvalid())
3387 return true;
3388
3389 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003390 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003391 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003392
John McCalldadc5752010-08-24 06:29:42 +00003393 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003394 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003395 if (ArgExpr.isInvalid())
3396 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003397
Anders Carlsson355933d2009-08-25 03:49:14 +00003398 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003399 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003400 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003401 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003402
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003403 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003404 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003405
3406 // Assume that extern "C" functions with variadic arguments that
3407 // return __unknown_anytype aren't *really* variadic.
3408 if (Proto->getResultType() == Context.UnknownAnyTy &&
3409 FDecl && FDecl->isExternC()) {
3410 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3411 ExprResult arg;
3412 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3413 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3414 else
3415 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3416 Invalid |= arg.isInvalid();
3417 AllArgs.push_back(arg.take());
3418 }
3419
3420 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3421 } else {
3422 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003423 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3424 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003425 Invalid |= Arg.isInvalid();
3426 AllArgs.push_back(Arg.take());
3427 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003428 }
3429 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003430 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003431}
3432
John McCall2979fe02011-04-12 00:42:48 +00003433/// Given a function expression of unknown-any type, try to rebuild it
3434/// to have a function type.
3435static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3436
Steve Naroff83895f72007-09-16 03:34:24 +00003437/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003438/// This provides the location of the left/right parens and a list of comma
3439/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003440ExprResult
John McCallb268a282010-08-23 23:25:46 +00003441Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003442 MultiExprArg args, SourceLocation RParenLoc,
3443 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003444 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003445
3446 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003447 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003448 if (Result.isInvalid()) return ExprError();
3449 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003450
John McCallb268a282010-08-23 23:25:46 +00003451 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003452
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003453 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003454 // If this is a pseudo-destructor expression, build the call immediately.
3455 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3456 if (NumArgs > 0) {
3457 // Pseudo-destructor calls should not have any arguments.
3458 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003459 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003460 SourceRange(Args[0]->getLocStart(),
3461 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003462
Douglas Gregorad8a3362009-09-04 17:36:40 +00003463 NumArgs = 0;
3464 }
Mike Stump11289f42009-09-09 15:08:12 +00003465
Douglas Gregorad8a3362009-09-04 17:36:40 +00003466 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003467 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003468 }
Mike Stump11289f42009-09-09 15:08:12 +00003469
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003470 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003471 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003472 // FIXME: Will need to cache the results of name lookup (including ADL) in
3473 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003474 bool Dependent = false;
3475 if (Fn->isTypeDependent())
3476 Dependent = true;
3477 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3478 Dependent = true;
3479
Peter Collingbourne41f85462011-02-09 21:07:24 +00003480 if (Dependent) {
3481 if (ExecConfig) {
3482 return Owned(new (Context) CUDAKernelCallExpr(
3483 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3484 Context.DependentTy, VK_RValue, RParenLoc));
3485 } else {
3486 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3487 Context.DependentTy, VK_RValue,
3488 RParenLoc));
3489 }
3490 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003491
3492 // Determine whether this is a call to an object (C++ [over.call.object]).
3493 if (Fn->getType()->isRecordType())
3494 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003495 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003496
John McCall2979fe02011-04-12 00:42:48 +00003497 if (Fn->getType() == Context.UnknownAnyTy) {
3498 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3499 if (result.isInvalid()) return ExprError();
3500 Fn = result.take();
3501 }
3502
John McCall0009fcc2011-04-26 20:42:42 +00003503 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003504 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003505 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003506 }
John McCall0009fcc2011-04-26 20:42:42 +00003507 }
John McCall10eae182009-11-30 22:42:35 +00003508
John McCall0009fcc2011-04-26 20:42:42 +00003509 // Check for overloaded calls. This can happen even in C due to extensions.
3510 if (Fn->getType() == Context.OverloadTy) {
3511 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3512
3513 // We aren't supposed to apply this logic if there's an '&' involved.
3514 if (!find.IsAddressOfOperand) {
3515 OverloadExpr *ovl = find.Expression;
3516 if (isa<UnresolvedLookupExpr>(ovl)) {
3517 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3518 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3519 RParenLoc, ExecConfig);
3520 } else {
John McCall2d74de92009-12-01 22:10:20 +00003521 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003522 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003523 }
3524 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003525 }
3526
Douglas Gregore254f902009-02-04 00:32:51 +00003527 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003528
Eli Friedmane14b1992009-12-26 03:35:45 +00003529 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003530
John McCall57500772009-12-16 12:17:52 +00003531 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003532 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3533 if (UnOp->getOpcode() == UO_AddrOf)
3534 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3535
John McCall57500772009-12-16 12:17:52 +00003536 if (isa<DeclRefExpr>(NakedFn))
3537 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003538 else if (isa<MemberExpr>(NakedFn))
3539 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003540
Peter Collingbourne41f85462011-02-09 21:07:24 +00003541 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3542 ExecConfig);
3543}
3544
3545ExprResult
3546Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3547 MultiExprArg execConfig, SourceLocation GGGLoc) {
3548 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3549 if (!ConfigDecl)
3550 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3551 << "cudaConfigureCall");
3552 QualType ConfigQTy = ConfigDecl->getType();
3553
3554 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3555 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3556
3557 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00003558}
3559
Tanya Lattner55808c12011-06-04 00:47:47 +00003560/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3561///
3562/// __builtin_astype( value, dst type )
3563///
3564ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty,
3565 SourceLocation BuiltinLoc,
3566 SourceLocation RParenLoc) {
3567 ExprValueKind VK = VK_RValue;
3568 ExprObjectKind OK = OK_Ordinary;
3569 QualType DstTy = GetTypeFromParser(destty);
3570 QualType SrcTy = expr->getType();
3571 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3572 return ExprError(Diag(BuiltinLoc,
3573 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003574 << DstTy
3575 << SrcTy
Tanya Lattner55808c12011-06-04 00:47:47 +00003576 << expr->getSourceRange());
Richard Trieucfc491d2011-08-02 04:35:43 +00003577 return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc,
3578 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003579}
3580
John McCall57500772009-12-16 12:17:52 +00003581/// BuildResolvedCallExpr - Build a call to a resolved expression,
3582/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003583/// unary-convert to an expression of function-pointer or
3584/// block-pointer type.
3585///
3586/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003587ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003588Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3589 SourceLocation LParenLoc,
3590 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003591 SourceLocation RParenLoc,
3592 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00003593 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3594
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003595 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003596 ExprResult Result = UsualUnaryConversions(Fn);
3597 if (Result.isInvalid())
3598 return ExprError();
3599 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003600
Chris Lattner08464942007-12-28 05:29:59 +00003601 // Make the call expr early, before semantic checks. This guarantees cleanup
3602 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003603 CallExpr *TheCall;
3604 if (Config) {
3605 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3606 cast<CallExpr>(Config),
3607 Args, NumArgs,
3608 Context.BoolTy,
3609 VK_RValue,
3610 RParenLoc);
3611 } else {
3612 TheCall = new (Context) CallExpr(Context, Fn,
3613 Args, NumArgs,
3614 Context.BoolTy,
3615 VK_RValue,
3616 RParenLoc);
3617 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003618
John McCallbebede42011-02-26 05:39:39 +00003619 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3620
3621 // Bail out early if calling a builtin with custom typechecking.
3622 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3623 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3624
John McCall31996342011-04-07 08:22:57 +00003625 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003626 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003627 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003628 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3629 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003630 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003631 if (FuncT == 0)
3632 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3633 << Fn->getType() << Fn->getSourceRange());
3634 } else if (const BlockPointerType *BPT =
3635 Fn->getType()->getAs<BlockPointerType>()) {
3636 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3637 } else {
John McCall31996342011-04-07 08:22:57 +00003638 // Handle calls to expressions of unknown-any type.
3639 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003640 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003641 if (rewrite.isInvalid()) return ExprError();
3642 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003643 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003644 goto retry;
3645 }
3646
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003647 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3648 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003649 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003650
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003651 if (getLangOptions().CUDA) {
3652 if (Config) {
3653 // CUDA: Kernel calls must be to global functions
3654 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3655 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3656 << FDecl->getName() << Fn->getSourceRange());
3657
3658 // CUDA: Kernel function must have 'void' return type
3659 if (!FuncT->getResultType()->isVoidType())
3660 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3661 << Fn->getType() << Fn->getSourceRange());
3662 }
3663 }
3664
Eli Friedman3164fb12009-03-22 22:00:50 +00003665 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003666 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00003667 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003668 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003669 return ExprError();
3670
Chris Lattner08464942007-12-28 05:29:59 +00003671 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003672 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003673 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003674
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003675 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003676 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003677 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003678 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003679 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003680 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003681
Douglas Gregord8e97de2009-04-02 15:37:10 +00003682 if (FDecl) {
3683 // Check if we have too few/too many template arguments, based
3684 // on our knowledge of the function definition.
3685 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003686 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003687 const FunctionProtoType *Proto
3688 = Def->getType()->getAs<FunctionProtoType>();
3689 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003690 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3691 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003692 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003693
3694 // If the function we're calling isn't a function prototype, but we have
3695 // a function prototype from a prior declaratiom, use that prototype.
3696 if (!FDecl->hasPrototype())
3697 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003698 }
3699
Steve Naroff0b661582007-08-28 23:30:39 +00003700 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003701 for (unsigned i = 0; i != NumArgs; i++) {
3702 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003703
3704 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003705 InitializedEntity Entity
3706 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003707 Proto->getArgType(i),
3708 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003709 ExprResult ArgE = PerformCopyInitialization(Entity,
3710 SourceLocation(),
3711 Owned(Arg));
3712 if (ArgE.isInvalid())
3713 return true;
3714
3715 Arg = ArgE.takeAs<Expr>();
3716
3717 } else {
John Wiegley01296292011-04-08 18:41:53 +00003718 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3719
3720 if (ArgE.isInvalid())
3721 return true;
3722
3723 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003724 }
3725
Douglas Gregor83025412010-10-26 05:45:40 +00003726 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3727 Arg->getType(),
3728 PDiag(diag::err_call_incomplete_argument)
3729 << Arg->getSourceRange()))
3730 return ExprError();
3731
Chris Lattner08464942007-12-28 05:29:59 +00003732 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003733 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003734 }
Chris Lattner08464942007-12-28 05:29:59 +00003735
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003736 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3737 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003738 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3739 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003740
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003741 // Check for sentinels
3742 if (NDecl)
3743 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003744
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003745 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003746 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003747 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003748 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003749
John McCallbebede42011-02-26 05:39:39 +00003750 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003751 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003752 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003753 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003754 return ExprError();
3755 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003756
John McCallb268a282010-08-23 23:25:46 +00003757 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003758}
3759
John McCalldadc5752010-08-24 06:29:42 +00003760ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003761Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003762 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003763 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003764 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003765 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003766
3767 TypeSourceInfo *TInfo;
3768 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3769 if (!TInfo)
3770 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3771
John McCallb268a282010-08-23 23:25:46 +00003772 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003773}
3774
John McCalldadc5752010-08-24 06:29:42 +00003775ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003776Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00003777 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003778 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003779
Eli Friedman37a186d2008-05-20 05:22:08 +00003780 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003781 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3782 PDiag(diag::err_illegal_decl_array_incomplete_type)
3783 << SourceRange(LParenLoc,
3784 literalExpr->getSourceRange().getEnd())))
3785 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00003786 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003787 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3788 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003789 } else if (!literalType->isDependentType() &&
3790 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003791 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003792 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003793 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003794 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003795
Douglas Gregor85dabae2009-12-16 01:38:02 +00003796 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003797 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003798 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00003799 = InitializationKind::CreateCStyleCast(LParenLoc,
3800 SourceRange(LParenLoc, RParenLoc));
Eli Friedmana553d4a2009-12-22 02:35:53 +00003801 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003802 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00003803 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003804 &literalType);
3805 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003806 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00003807 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003808
Chris Lattner79413952008-12-04 23:50:19 +00003809 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003810 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003811 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003812 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003813 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003814
John McCall7decc9e2010-11-18 06:31:45 +00003815 // In C, compound literals are l-values for some reason.
3816 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3817
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00003818 return MaybeBindToTemporary(
3819 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
3820 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003821}
3822
John McCalldadc5752010-08-24 06:29:42 +00003823ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00003824Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003825 SourceLocation RBraceLoc) {
3826 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00003827 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00003828
Steve Naroff30d242c2007-09-15 18:49:24 +00003829 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003830 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003831
Ted Kremenekac034612010-04-13 23:39:13 +00003832 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3833 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003834 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003835 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003836}
3837
John McCalld7646252010-11-14 08:17:51 +00003838/// Prepares for a scalar cast, performing all the necessary stages
3839/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00003840static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00003841 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3842 // Also, callers should have filtered out the invalid cases with
3843 // pointers. Everything else should be possible.
3844
John Wiegley01296292011-04-08 18:41:53 +00003845 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00003846 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00003847 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00003848
John McCall8cb679e2010-11-15 09:13:47 +00003849 switch (SrcTy->getScalarTypeKind()) {
3850 case Type::STK_MemberPointer:
3851 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00003852
John McCall8cb679e2010-11-15 09:13:47 +00003853 case Type::STK_Pointer:
3854 switch (DestTy->getScalarTypeKind()) {
3855 case Type::STK_Pointer:
3856 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00003857 CK_AnyPointerToObjCPointerCast :
3858 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00003859 case Type::STK_Bool:
3860 return CK_PointerToBoolean;
3861 case Type::STK_Integral:
3862 return CK_PointerToIntegral;
3863 case Type::STK_Floating:
3864 case Type::STK_FloatingComplex:
3865 case Type::STK_IntegralComplex:
3866 case Type::STK_MemberPointer:
3867 llvm_unreachable("illegal cast from pointer");
3868 }
3869 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003870
John McCall8cb679e2010-11-15 09:13:47 +00003871 case Type::STK_Bool: // casting from bool is like casting from an integer
3872 case Type::STK_Integral:
3873 switch (DestTy->getScalarTypeKind()) {
3874 case Type::STK_Pointer:
Richard Trieucfc491d2011-08-02 04:35:43 +00003875 if (Src.get()->isNullPointerConstant(S.Context,
3876 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00003877 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00003878 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00003879 case Type::STK_Bool:
3880 return CK_IntegralToBoolean;
3881 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00003882 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00003883 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003884 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003885 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003886 Src = S.ImpCastExprToType(Src.take(),
3887 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003888 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00003889 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003890 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003891 Src = S.ImpCastExprToType(Src.take(),
3892 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003893 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00003894 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003895 case Type::STK_MemberPointer:
3896 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003897 }
3898 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003899
John McCall8cb679e2010-11-15 09:13:47 +00003900 case Type::STK_Floating:
3901 switch (DestTy->getScalarTypeKind()) {
3902 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003903 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00003904 case Type::STK_Bool:
3905 return CK_FloatingToBoolean;
3906 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00003907 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003908 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003909 Src = S.ImpCastExprToType(Src.take(),
3910 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003911 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00003912 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003913 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003914 Src = S.ImpCastExprToType(Src.take(),
3915 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003916 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00003917 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003918 case Type::STK_Pointer:
3919 llvm_unreachable("valid float->pointer cast?");
3920 case Type::STK_MemberPointer:
3921 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003922 }
3923 break;
3924
John McCall8cb679e2010-11-15 09:13:47 +00003925 case Type::STK_FloatingComplex:
3926 switch (DestTy->getScalarTypeKind()) {
3927 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003928 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00003929 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003930 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00003931 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003932 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003933 if (S.Context.hasSameType(ET, DestTy))
3934 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003935 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003936 return CK_FloatingCast;
3937 }
John McCall8cb679e2010-11-15 09:13:47 +00003938 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003939 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003940 case Type::STK_Integral:
Richard Trieucfc491d2011-08-02 04:35:43 +00003941 Src = S.ImpCastExprToType(Src.take(),
3942 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003943 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003944 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003945 case Type::STK_Pointer:
3946 llvm_unreachable("valid complex float->pointer cast?");
3947 case Type::STK_MemberPointer:
3948 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003949 }
3950 break;
3951
John McCall8cb679e2010-11-15 09:13:47 +00003952 case Type::STK_IntegralComplex:
3953 switch (DestTy->getScalarTypeKind()) {
3954 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003955 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003956 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003957 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00003958 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003959 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003960 if (S.Context.hasSameType(ET, DestTy))
3961 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003962 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003963 return CK_IntegralCast;
3964 }
John McCall8cb679e2010-11-15 09:13:47 +00003965 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003966 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003967 case Type::STK_Floating:
Richard Trieucfc491d2011-08-02 04:35:43 +00003968 Src = S.ImpCastExprToType(Src.take(),
3969 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003970 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003971 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003972 case Type::STK_Pointer:
3973 llvm_unreachable("valid complex int->pointer cast?");
3974 case Type::STK_MemberPointer:
3975 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003976 }
3977 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00003978 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003979
John McCalld7646252010-11-14 08:17:51 +00003980 llvm_unreachable("Unhandled scalar cast");
3981 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00003982}
3983
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003984/// CheckCastTypes - Check type constraints for casting between types.
John McCall31168b02011-06-15 23:02:42 +00003985ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyR,
3986 QualType castType, Expr *castExpr,
3987 CastKind& Kind, ExprValueKind &VK,
John Wiegley01296292011-04-08 18:41:53 +00003988 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall31996342011-04-07 08:22:57 +00003989 if (castExpr->getType() == Context.UnknownAnyTy)
3990 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
3991
Sebastian Redl9f831db2009-07-25 15:41:38 +00003992 if (getLangOptions().CPlusPlus)
John McCall31168b02011-06-15 23:02:42 +00003993 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Douglas Gregor15417cf2010-11-03 00:35:38 +00003994 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00003995 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00003996 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003997
John McCall3aef3d82011-04-10 19:13:55 +00003998 assert(!castExpr->getType()->isPlaceholderType());
3999
John McCall7decc9e2010-11-18 06:31:45 +00004000 // We only support r-value casts in C.
4001 VK = VK_RValue;
4002
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004003 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4004 // type needs to be scalar.
4005 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00004006 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley01296292011-04-08 18:41:53 +00004007 ExprResult castExprRes = IgnoredValueConversions(castExpr);
4008 if (castExprRes.isInvalid())
4009 return ExprError();
4010 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00004011
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004012 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00004013 Kind = CK_ToVoid;
John Wiegley01296292011-04-08 18:41:53 +00004014 return Owned(castExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00004015 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004016
John Wiegley01296292011-04-08 18:41:53 +00004017 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
4018 if (castExprRes.isInvalid())
4019 return ExprError();
4020 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00004021
Eli Friedmane98194d2010-07-17 20:43:49 +00004022 if (RequireCompleteType(TyR.getBegin(), castType,
4023 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00004024 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00004025
Anders Carlssonef918ac2009-10-16 02:35:04 +00004026 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004027 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004028 (castType->isStructureType() || castType->isUnionType())) {
4029 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00004030 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004031 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4032 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004033 Kind = CK_NoOp;
John Wiegley01296292011-04-08 18:41:53 +00004034 return Owned(castExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00004035 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004036
Anders Carlsson525b76b2009-10-16 02:48:28 +00004037 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004038 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004039 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004040 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004041 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004042 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004043 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00004044 castExpr->getType()) &&
4045 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004046 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4047 << castExpr->getSourceRange();
4048 break;
4049 }
4050 }
John Wiegley01296292011-04-08 18:41:53 +00004051 if (Field == FieldEnd) {
4052 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004053 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004054 return ExprError();
4055 }
John McCalle3027922010-08-25 11:45:40 +00004056 Kind = CK_ToUnion;
John Wiegley01296292011-04-08 18:41:53 +00004057 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004058 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004059
Anders Carlsson525b76b2009-10-16 02:48:28 +00004060 // Reject any other conversions to non-scalar types.
John Wiegley01296292011-04-08 18:41:53 +00004061 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlsson525b76b2009-10-16 02:48:28 +00004062 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004063 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004064 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004065
John McCalld7646252010-11-14 08:17:51 +00004066 // The type we're casting to is known to be a scalar or vector.
4067
4068 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004069 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00004070 !castExpr->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004071 Diag(castExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004072 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004073 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004074 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004075 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004076
4077 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00004078 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004079
Anton Yartsev28ccef72011-03-27 09:32:40 +00004080 if (castType->isVectorType()) {
4081 if (castType->getAs<VectorType>()->getVectorKind() ==
4082 VectorType::AltiVecVector &&
4083 (castExpr->getType()->isIntegerType() ||
4084 castExpr->getType()->isFloatingType())) {
4085 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004086 return Owned(castExpr);
4087 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
4088 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00004089 } else
John Wiegley01296292011-04-08 18:41:53 +00004090 return Owned(castExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00004091 }
John Wiegley01296292011-04-08 18:41:53 +00004092 if (castExpr->getType()->isVectorType()) {
4093 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
4094 return ExprError();
4095 else
4096 return Owned(castExpr);
4097 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00004098
John McCalld7646252010-11-14 08:17:51 +00004099 // The source and target types are both scalars, i.e.
4100 // - arithmetic types (fundamental, enum, and complex)
4101 // - all kinds of pointers
4102 // Note that member pointers were filtered out with C++, above.
4103
John Wiegley01296292011-04-08 18:41:53 +00004104 if (isa<ObjCSelectorExpr>(castExpr)) {
4105 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
4106 return ExprError();
4107 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004108
John McCalld7646252010-11-14 08:17:51 +00004109 // If either type is a pointer, the other type has to be either an
4110 // integer or a pointer.
John McCall31168b02011-06-15 23:02:42 +00004111 QualType castExprType = castExpr->getType();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004112 if (!castType->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00004113 if (!castExprType->isIntegralType(Context) &&
John Wiegley01296292011-04-08 18:41:53 +00004114 castExprType->isArithmeticType()) {
4115 Diag(castExpr->getLocStart(),
4116 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004117 << castExprType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004118 return ExprError();
4119 }
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004120 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley01296292011-04-08 18:41:53 +00004121 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
4122 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004123 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004124 return ExprError();
4125 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004126 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004127
John McCall31168b02011-06-15 23:02:42 +00004128 if (getLangOptions().ObjCAutoRefCount) {
4129 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
4130 CheckObjCARCConversion(SourceRange(CastStartLoc, castExpr->getLocEnd()),
4131 castType, castExpr, CCK_CStyleCast);
4132
4133 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
4134 if (const PointerType *ExprPtr = castExprType->getAs<PointerType>()) {
4135 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4136 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4137 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4138 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4139 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
4140 Diag(castExpr->getLocStart(),
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004141 diag::err_typecheck_incompatible_ownership)
John McCall31168b02011-06-15 23:02:42 +00004142 << castExprType << castType << AA_Casting
4143 << castExpr->getSourceRange();
4144
4145 return ExprError();
4146 }
4147 }
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004148 }
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004149 else if (!CheckObjCARCUnavailableWeakConversion(castType, castExprType)) {
4150 Diag(castExpr->getLocStart(),
Fariborz Jahanianf2913402011-07-08 17:41:42 +00004151 diag::err_arc_convesion_of_weak_unavailable) << 1
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004152 << castExprType << castType
4153 << castExpr->getSourceRange();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004154 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00004155 }
4156 }
4157
John Wiegley01296292011-04-08 18:41:53 +00004158 castExprRes = Owned(castExpr);
4159 Kind = PrepareScalarCast(*this, castExprRes, castType);
4160 if (castExprRes.isInvalid())
4161 return ExprError();
4162 castExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00004163
John McCalld7646252010-11-14 08:17:51 +00004164 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00004165 CheckCastAlign(castExpr, castType, TyR);
4166
John Wiegley01296292011-04-08 18:41:53 +00004167 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004168}
4169
Anders Carlsson525b76b2009-10-16 02:48:28 +00004170bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004171 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004172 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004173
Anders Carlssonde71adf2007-11-27 05:51:55 +00004174 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004175 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004176 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004177 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004178 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004179 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004180 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004181 } else
4182 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004183 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004184 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004185
John McCalle3027922010-08-25 11:45:40 +00004186 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004187 return false;
4188}
4189
John Wiegley01296292011-04-08 18:41:53 +00004190ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4191 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004192 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004193
Anders Carlsson43d70f82009-10-16 05:23:41 +00004194 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004195
Nate Begemanc8961a42009-06-27 22:05:55 +00004196 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4197 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00004198 if (SrcTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004199 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
4200 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004201 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004202 return ExprError();
4203 }
John McCalle3027922010-08-25 11:45:40 +00004204 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004205 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004206 }
4207
Nate Begemanbd956c42009-06-28 02:36:38 +00004208 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004209 // conversion will take place first from scalar to elt type, and then
4210 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004211 if (SrcTy->isPointerType())
4212 return Diag(R.getBegin(),
4213 diag::err_invalid_conversion_between_vector_and_scalar)
4214 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004215
4216 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004217 ExprResult CastExprRes = Owned(CastExpr);
4218 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4219 if (CastExprRes.isInvalid())
4220 return ExprError();
4221 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004222
John McCalle3027922010-08-25 11:45:40 +00004223 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004224 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004225}
4226
John McCalldadc5752010-08-24 06:29:42 +00004227ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004228Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4229 Declarator &D, ParsedType &Ty,
John McCallb268a282010-08-23 23:25:46 +00004230 SourceLocation RParenLoc, Expr *castExpr) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004231 assert(!D.isInvalidType() && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004232 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004233
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004234 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, castExpr->getType());
4235 if (D.isInvalidType())
4236 return ExprError();
4237
4238 if (getLangOptions().CPlusPlus) {
4239 // Check that there are no default arguments (C++ only).
4240 CheckExtraCXXDefaultArguments(D);
4241 }
4242
4243 QualType castType = castTInfo->getType();
4244 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004245
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004246 bool isVectorLiteral = false;
4247
4248 // Check for an altivec or OpenCL literal,
4249 // i.e. all the elements are integer constants.
4250 ParenExpr *PE = dyn_cast<ParenExpr>(castExpr);
4251 ParenListExpr *PLE = dyn_cast<ParenListExpr>(castExpr);
4252 if (getLangOptions().AltiVec && castType->isVectorType() && (PE || PLE)) {
4253 if (PLE && PLE->getNumExprs() == 0) {
4254 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4255 return ExprError();
4256 }
4257 if (PE || PLE->getNumExprs() == 1) {
4258 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4259 if (!E->getType()->isVectorType())
4260 isVectorLiteral = true;
4261 }
4262 else
4263 isVectorLiteral = true;
4264 }
4265
4266 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4267 // then handle it as such.
4268 if (isVectorLiteral)
4269 return BuildVectorLiteral(LParenLoc, RParenLoc, castExpr, castTInfo);
4270
Nate Begeman5ec4b312009-08-10 23:49:36 +00004271 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004272 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4273 // sequence of BinOp comma operators.
4274 if (isa<ParenListExpr>(castExpr)) {
4275 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, castExpr);
4276 if (Result.isInvalid()) return ExprError();
4277 castExpr = Result.take();
4278 }
John McCallebe54742010-01-15 18:56:44 +00004279
John McCallb268a282010-08-23 23:25:46 +00004280 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00004281}
4282
John McCalldadc5752010-08-24 06:29:42 +00004283ExprResult
John McCallebe54742010-01-15 18:56:44 +00004284Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00004285 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00004286 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00004287 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00004288 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00004289 ExprResult CastResult =
John McCall31168b02011-06-15 23:02:42 +00004290 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
4291 castExpr, Kind, VK, BasePath);
John Wiegley01296292011-04-08 18:41:53 +00004292 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004293 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004294 castExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00004295
Richard Trieucfc491d2011-08-02 04:35:43 +00004296 return Owned(CStyleCastExpr::Create(
4297 Context, Ty->getType().getNonLValueExprType(Context), VK, Kind, castExpr,
4298 &BasePath, Ty, LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004299}
4300
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004301ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4302 SourceLocation RParenLoc, Expr *E,
4303 TypeSourceInfo *TInfo) {
4304 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4305 "Expected paren or paren list expression");
4306
4307 Expr **exprs;
4308 unsigned numExprs;
4309 Expr *subExpr;
4310 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4311 exprs = PE->getExprs();
4312 numExprs = PE->getNumExprs();
4313 } else {
4314 subExpr = cast<ParenExpr>(E)->getSubExpr();
4315 exprs = &subExpr;
4316 numExprs = 1;
4317 }
4318
4319 QualType Ty = TInfo->getType();
4320 assert(Ty->isVectorType() && "Expected vector type");
4321
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004322 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004323 const VectorType *VTy = Ty->getAs<VectorType>();
4324 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4325
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004326 // '(...)' form of vector initialization in AltiVec: the number of
4327 // initializers must be one or must match the size of the vector.
4328 // If a single value is specified in the initializer then it will be
4329 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004330 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004331 // The number of initializers must be one or must match the size of the
4332 // vector. If a single value is specified in the initializer then it will
4333 // be replicated to all the components of the vector
4334 if (numExprs == 1) {
4335 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4336 ExprResult Literal = Owned(exprs[0]);
4337 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4338 PrepareScalarCast(*this, Literal, ElemTy));
4339 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4340 }
4341 else if (numExprs < numElems) {
4342 Diag(E->getExprLoc(),
4343 diag::err_incorrect_number_of_vector_initializers);
4344 return ExprError();
4345 }
4346 else
4347 for (unsigned i = 0, e = numExprs; i != e; ++i)
4348 initExprs.push_back(exprs[i]);
4349 }
Tanya Lattner83559382011-07-15 23:07:01 +00004350 else {
4351 // For OpenCL, when the number of initializers is a single value,
4352 // it will be replicated to all components of the vector.
4353 if (getLangOptions().OpenCL &&
4354 VTy->getVectorKind() == VectorType::GenericVector &&
4355 numExprs == 1) {
4356 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4357 ExprResult Literal = Owned(exprs[0]);
4358 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4359 PrepareScalarCast(*this, Literal, ElemTy));
4360 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4361 }
4362
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004363 for (unsigned i = 0, e = numExprs; i != e; ++i)
4364 initExprs.push_back(exprs[i]);
Tanya Lattner83559382011-07-15 23:07:01 +00004365 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004366 // FIXME: This means that pretty-printing the final AST will produce curly
4367 // braces instead of the original commas.
4368 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4369 &initExprs[0],
4370 initExprs.size(), RParenLoc);
4371 initE->setType(Ty);
4372 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4373}
4374
Nate Begeman5ec4b312009-08-10 23:49:36 +00004375/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4376/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004377ExprResult
John McCallb268a282010-08-23 23:25:46 +00004378Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004379 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4380 if (!E)
4381 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00004382
John McCalldadc5752010-08-24 06:29:42 +00004383 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004384
Nate Begeman5ec4b312009-08-10 23:49:36 +00004385 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004386 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4387 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004388
John McCallb268a282010-08-23 23:25:46 +00004389 if (Result.isInvalid()) return ExprError();
4390
4391 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004392}
4393
John McCalldadc5752010-08-24 06:29:42 +00004394ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00004395 SourceLocation R,
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004396 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004397 unsigned nexprs = Val.size();
4398 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004399 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4400 Expr *expr;
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004401 if (nexprs == 1)
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004402 expr = new (Context) ParenExpr(L, R, exprs[0]);
4403 else
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004404 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4405 exprs[nexprs-1]->getType());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004406 return Owned(expr);
4407}
4408
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004409/// \brief Emit a specialized diagnostic when one expression is a null pointer
4410/// constant and the other is not a pointer.
4411bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
4412 SourceLocation QuestionLoc) {
4413 Expr *NullExpr = LHS;
4414 Expr *NonPointerExpr = RHS;
4415 Expr::NullPointerConstantKind NullKind =
4416 NullExpr->isNullPointerConstant(Context,
4417 Expr::NPC_ValueDependentIsNotNull);
4418
4419 if (NullKind == Expr::NPCK_NotNull) {
4420 NullExpr = RHS;
4421 NonPointerExpr = LHS;
4422 NullKind =
4423 NullExpr->isNullPointerConstant(Context,
4424 Expr::NPC_ValueDependentIsNotNull);
4425 }
4426
4427 if (NullKind == Expr::NPCK_NotNull)
4428 return false;
4429
4430 if (NullKind == Expr::NPCK_ZeroInteger) {
4431 // In this case, check to make sure that we got here from a "NULL"
4432 // string in the source code.
4433 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004434 SourceLocation loc = NullExpr->getExprLoc();
4435 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004436 return false;
4437 }
4438
4439 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4440 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4441 << NonPointerExpr->getType() << DiagType
4442 << NonPointerExpr->getSourceRange();
4443 return true;
4444}
4445
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004446/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4447/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004448/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004449QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4450 ExprResult &RHS, ExprValueKind &VK,
4451 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004452 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004453
John McCall3aef3d82011-04-10 19:13:55 +00004454 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00004455 if (!lhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004456 LHS = move(lhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004457
John McCall3aef3d82011-04-10 19:13:55 +00004458 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00004459 if (!rhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004460 RHS = move(rhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004461
Sebastian Redl1a99f442009-04-16 17:51:27 +00004462 // C++ is sufficiently different to merit its own checker.
4463 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004464 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004465
4466 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004467 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004468
John Wiegley01296292011-04-08 18:41:53 +00004469 Cond = UsualUnaryConversions(Cond.take());
4470 if (Cond.isInvalid())
4471 return QualType();
4472 LHS = UsualUnaryConversions(LHS.take());
4473 if (LHS.isInvalid())
4474 return QualType();
4475 RHS = UsualUnaryConversions(RHS.take());
4476 if (RHS.isInvalid())
4477 return QualType();
4478
4479 QualType CondTy = Cond.get()->getType();
4480 QualType LHSTy = LHS.get()->getType();
4481 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004482
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004483 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004484 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00004485 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4486 // Throw an error if its not either.
4487 if (getLangOptions().OpenCL) {
4488 if (!CondTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004489 Diag(Cond.get()->getLocStart(),
Nate Begemanabb5a732010-09-20 22:41:17 +00004490 diag::err_typecheck_cond_expect_scalar_or_vector)
4491 << CondTy;
4492 return QualType();
4493 }
4494 }
4495 else {
John Wiegley01296292011-04-08 18:41:53 +00004496 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004497 << CondTy;
4498 return QualType();
4499 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004500 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004501
Chris Lattnere2949f42008-01-06 22:42:25 +00004502 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004503 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004504 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004505
Nate Begemanabb5a732010-09-20 22:41:17 +00004506 // OpenCL: If the condition is a vector, and both operands are scalar,
4507 // attempt to implicity convert them to the vector type to act like the
4508 // built in select.
4509 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
4510 // Both operands should be of scalar type.
4511 if (!LHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00004512 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004513 << CondTy;
4514 return QualType();
4515 }
4516 if (!RHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00004517 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004518 << CondTy;
4519 return QualType();
4520 }
4521 // Implicity convert these scalars to the type of the condition.
John Wiegley01296292011-04-08 18:41:53 +00004522 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4523 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begemanabb5a732010-09-20 22:41:17 +00004524 }
4525
Chris Lattnere2949f42008-01-06 22:42:25 +00004526 // If both operands have arithmetic type, do the usual arithmetic conversions
4527 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004528 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4529 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004530 if (LHS.isInvalid() || RHS.isInvalid())
4531 return QualType();
4532 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004533 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004534
Chris Lattnere2949f42008-01-06 22:42:25 +00004535 // If both operands are the same structure or union type, the result is that
4536 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004537 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4538 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004539 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004540 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004541 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004542 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004543 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004544 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004545
Chris Lattnere2949f42008-01-06 22:42:25 +00004546 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004547 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004548 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4549 if (!LHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00004550 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4551 << RHS.get()->getSourceRange();
Chris Lattner432cff52009-02-18 04:28:32 +00004552 if (!RHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00004553 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4554 << LHS.get()->getSourceRange();
4555 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
4556 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00004557 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00004558 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00004559 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4560 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00004561 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Richard Trieucfc491d2011-08-02 04:35:43 +00004562 RHS.get()->isNullPointerConstant(Context,
4563 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004564 // promote the null to a pointer.
John Wiegley01296292011-04-08 18:41:53 +00004565 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004566 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004567 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004568 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Richard Trieucfc491d2011-08-02 04:35:43 +00004569 LHS.get()->isNullPointerConstant(Context,
4570 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00004571 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004572 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004573 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004574
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004575 // All objective-c pointer type analysis is done here.
4576 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4577 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004578 if (LHS.isInvalid() || RHS.isInvalid())
4579 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004580 if (!compositeType.isNull())
4581 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004582
4583
Steve Naroff05efa972009-07-01 14:36:47 +00004584 // Handle block pointer types.
4585 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4586 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4587 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4588 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004589 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4590 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004591 return destType;
4592 }
4593 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004594 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4595 << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004596 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00004597 }
Steve Naroff05efa972009-07-01 14:36:47 +00004598 // We have 2 block pointer types.
4599 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4600 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00004601 return LHSTy;
4602 }
Steve Naroff05efa972009-07-01 14:36:47 +00004603 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004604 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4605 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004606
Steve Naroff05efa972009-07-01 14:36:47 +00004607 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4608 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00004609 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00004610 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4611 << RHS.get()->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00004612 // In this situation, we assume void* type. No especially good
4613 // reason, but this is what gcc does, and we do have to pick
4614 // to get a consistent AST.
4615 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004616 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4617 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00004618 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004619 }
Steve Naroff05efa972009-07-01 14:36:47 +00004620 // The block pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004621 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4622 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00004623 return LHSTy;
4624 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004625
Steve Naroff05efa972009-07-01 14:36:47 +00004626 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4627 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4628 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004629 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4630 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00004631
4632 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4633 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4634 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00004635 QualType destPointee
4636 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004637 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004638 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004639 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004640 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004641 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004642 return destType;
4643 }
4644 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004645 QualType destPointee
4646 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004647 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004648 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004649 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004650 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004651 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004652 return destType;
4653 }
4654
4655 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4656 // Two identical pointer types are always compatible.
4657 return LHSTy;
4658 }
4659 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4660 rhptee.getUnqualifiedType())) {
4661 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00004662 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4663 << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004664 // In this situation, we assume void* type. No especially good
4665 // reason, but this is what gcc does, and we do have to pick
4666 // to get a consistent AST.
4667 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004668 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4669 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004670 return incompatTy;
4671 }
4672 // The pointer types are compatible.
4673 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4674 // differently qualified versions of compatible types, the result type is
4675 // a pointer to an appropriately qualified version of the *composite*
4676 // type.
4677 // FIXME: Need to calculate the composite type.
4678 // FIXME: Need to add qualifiers
John Wiegley01296292011-04-08 18:41:53 +00004679 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4680 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004681 return LHSTy;
4682 }
Mike Stump11289f42009-09-09 15:08:12 +00004683
John McCalle84af4e2010-11-13 01:35:44 +00004684 // GCC compatibility: soften pointer/integer mismatch. Note that
4685 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00004686 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4687 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
Richard Trieucfc491d2011-08-02 04:35:43 +00004688 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4689 << RHS.get()->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004690 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004691 return RHSTy;
4692 }
4693 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4694 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
Richard Trieucfc491d2011-08-02 04:35:43 +00004695 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4696 << RHS.get()->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004697 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004698 return LHSTy;
4699 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00004700
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004701 // Emit a better diagnostic if one of the expressions is a null pointer
4702 // constant and the other is not a pointer type. In this case, the user most
4703 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004704 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004705 return QualType();
4706
Chris Lattnere2949f42008-01-06 22:42:25 +00004707 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004708 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004709 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4710 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004711 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004712}
4713
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004714/// FindCompositeObjCPointerType - Helper method to find composite type of
4715/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004716QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00004717 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004718 QualType LHSTy = LHS.get()->getType();
4719 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004720
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004721 // Handle things like Class and struct objc_class*. Here we case the result
4722 // to the pseudo-builtin, because that will be implicitly cast back to the
4723 // redefinition type if an attempt is made to access its fields.
4724 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00004725 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004726 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004727 return LHSTy;
4728 }
4729 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00004730 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004731 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004732 return RHSTy;
4733 }
4734 // And the same for struct objc_object* / id
4735 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00004736 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004737 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004738 return LHSTy;
4739 }
4740 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00004741 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004742 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004743 return RHSTy;
4744 }
4745 // And the same for struct objc_selector* / SEL
4746 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00004747 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004748 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004749 return LHSTy;
4750 }
4751 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00004752 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004753 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004754 return RHSTy;
4755 }
4756 // Check constraints for Objective-C object pointers types.
4757 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004758
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004759 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4760 // Two identical object pointer types are always compatible.
4761 return LHSTy;
4762 }
4763 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4764 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4765 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004766
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004767 // If both operands are interfaces and either operand can be
4768 // assigned to the other, use that type as the composite
4769 // type. This allows
4770 // xxx ? (A*) a : (B*) b
4771 // where B is a subclass of A.
4772 //
4773 // Additionally, as for assignment, if either type is 'id'
4774 // allow silent coercion. Finally, if the types are
4775 // incompatible then make sure to use 'id' as the composite
4776 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004777
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004778 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4779 // It could return the composite type.
4780 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4781 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4782 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4783 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4784 } else if ((LHSTy->isObjCQualifiedIdType() ||
4785 RHSTy->isObjCQualifiedIdType()) &&
4786 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4787 // Need to handle "id<xx>" explicitly.
4788 // GCC allows qualified id and any Objective-C type to devolve to
4789 // id. Currently localizing to here until clear this should be
4790 // part of ObjCQualifiedIdTypesAreCompatible.
4791 compositeType = Context.getObjCIdType();
4792 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4793 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004794 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004795 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4796 ;
4797 else {
4798 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4799 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004800 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004801 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004802 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4803 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004804 return incompatTy;
4805 }
4806 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004807 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4808 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004809 return compositeType;
4810 }
4811 // Check Objective-C object pointer types and 'void *'
4812 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4813 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4814 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4815 QualType destPointee
4816 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4817 QualType destType = Context.getPointerType(destPointee);
4818 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004819 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004820 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004821 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004822 return destType;
4823 }
4824 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4825 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4826 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4827 QualType destPointee
4828 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4829 QualType destType = Context.getPointerType(destPointee);
4830 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004831 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004832 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004833 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004834 return destType;
4835 }
4836 return QualType();
4837}
4838
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004839/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004840/// ParenRange in parentheses.
4841static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004842 const PartialDiagnostic &Note,
4843 SourceRange ParenRange) {
4844 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4845 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4846 EndLoc.isValid()) {
4847 Self.Diag(Loc, Note)
4848 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4849 << FixItHint::CreateInsertion(EndLoc, ")");
4850 } else {
4851 // We can't display the parentheses, so just show the bare note.
4852 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004853 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004854}
4855
4856static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4857 return Opc >= BO_Mul && Opc <= BO_Shr;
4858}
4859
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004860/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4861/// expression, either using a built-in or overloaded operator,
4862/// and sets *OpCode to the opcode and *RHS to the right-hand side expression.
4863static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
4864 Expr **RHS) {
4865 E = E->IgnoreParenImpCasts();
4866 E = E->IgnoreConversionOperator();
4867 E = E->IgnoreParenImpCasts();
4868
4869 // Built-in binary operator.
4870 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4871 if (IsArithmeticOp(OP->getOpcode())) {
4872 *Opcode = OP->getOpcode();
4873 *RHS = OP->getRHS();
4874 return true;
4875 }
4876 }
4877
4878 // Overloaded operator.
4879 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4880 if (Call->getNumArgs() != 2)
4881 return false;
4882
4883 // Make sure this is really a binary operator that is safe to pass into
4884 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4885 OverloadedOperatorKind OO = Call->getOperator();
4886 if (OO < OO_Plus || OO > OO_Arrow)
4887 return false;
4888
4889 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4890 if (IsArithmeticOp(OpKind)) {
4891 *Opcode = OpKind;
4892 *RHS = Call->getArg(1);
4893 return true;
4894 }
4895 }
4896
4897 return false;
4898}
4899
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004900static bool IsLogicOp(BinaryOperatorKind Opc) {
4901 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4902}
4903
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004904/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4905/// or is a logical expression such as (x==y) which has int type, but is
4906/// commonly interpreted as boolean.
4907static bool ExprLooksBoolean(Expr *E) {
4908 E = E->IgnoreParenImpCasts();
4909
4910 if (E->getType()->isBooleanType())
4911 return true;
4912 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4913 return IsLogicOp(OP->getOpcode());
4914 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4915 return OP->getOpcode() == UO_LNot;
4916
4917 return false;
4918}
4919
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004920/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4921/// and binary operator are mixed in a way that suggests the programmer assumed
4922/// the conditional operator has higher precedence, for example:
4923/// "int x = a + someBinaryCondition ? 1 : 2".
4924static void DiagnoseConditionalPrecedence(Sema &Self,
4925 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004926 Expr *Condition,
4927 Expr *LHS,
4928 Expr *RHS) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004929 BinaryOperatorKind CondOpcode;
4930 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004931
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004932 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004933 return;
4934 if (!ExprLooksBoolean(CondRHS))
4935 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004936
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004937 // The condition is an arithmetic binary expression, with a right-
4938 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004939
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004940 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004941 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004942 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004943
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004944 SuggestParentheses(Self, OpLoc,
4945 Self.PDiag(diag::note_precedence_conditional_silence)
4946 << BinaryOperator::getOpcodeStr(CondOpcode),
4947 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00004948
4949 SuggestParentheses(Self, OpLoc,
4950 Self.PDiag(diag::note_precedence_conditional_first),
4951 SourceRange(CondRHS->getLocStart(), RHS->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004952}
4953
Steve Naroff83895f72007-09-16 03:34:24 +00004954/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004955/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00004956ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00004957 SourceLocation ColonLoc,
4958 Expr *CondExpr, Expr *LHSExpr,
4959 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00004960 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4961 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00004962 OpaqueValueExpr *opaqueValue = 0;
4963 Expr *commonExpr = 0;
4964 if (LHSExpr == 0) {
4965 commonExpr = CondExpr;
4966
4967 // We usually want to apply unary conversions *before* saving, except
4968 // in the special case of a C++ l-value conditional.
4969 if (!(getLangOptions().CPlusPlus
4970 && !commonExpr->isTypeDependent()
4971 && commonExpr->getValueKind() == RHSExpr->getValueKind()
4972 && commonExpr->isGLValue()
4973 && commonExpr->isOrdinaryOrBitFieldObject()
4974 && RHSExpr->isOrdinaryOrBitFieldObject()
4975 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004976 ExprResult commonRes = UsualUnaryConversions(commonExpr);
4977 if (commonRes.isInvalid())
4978 return ExprError();
4979 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00004980 }
4981
4982 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
4983 commonExpr->getType(),
4984 commonExpr->getValueKind(),
4985 commonExpr->getObjectKind());
4986 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00004987 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00004988
John McCall7decc9e2010-11-18 06:31:45 +00004989 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004990 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00004991 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
4992 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00004993 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004994 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
4995 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004996 return ExprError();
4997
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004998 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
4999 RHS.get());
5000
John McCallc07a0c72011-02-17 10:25:35 +00005001 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005002 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5003 LHS.take(), ColonLoc,
5004 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005005
5006 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005007 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005008 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5009 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005010}
5011
John McCallaba90822011-01-31 23:13:11 +00005012// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005013// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005014// routine is it effectively iqnores the qualifiers on the top level pointee.
5015// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5016// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005017static Sema::AssignConvertType
5018checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5019 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5020 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005021
Steve Naroff1f4d7272007-05-11 04:00:31 +00005022 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005023 const Type *lhptee, *rhptee;
5024 Qualifiers lhq, rhq;
5025 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5026 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005027
John McCallaba90822011-01-31 23:13:11 +00005028 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005029
5030 // C99 6.5.16.1p1: This following citation is common to constraints
5031 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5032 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005033 Qualifiers lq;
5034
John McCall31168b02011-06-15 23:02:42 +00005035 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5036 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5037 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5038 // Ignore lifetime for further calculation.
5039 lhq.removeObjCLifetime();
5040 rhq.removeObjCLifetime();
5041 }
5042
John McCall4fff8f62011-02-01 00:10:29 +00005043 if (!lhq.compatiblyIncludes(rhq)) {
5044 // Treat address-space mismatches as fatal. TODO: address subspaces
5045 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5046 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5047
John McCall31168b02011-06-15 23:02:42 +00005048 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005049 // and from void*.
John McCall31168b02011-06-15 23:02:42 +00005050 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5051 .compatiblyIncludes(
5052 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall78535952011-03-26 02:56:45 +00005053 && (lhptee->isVoidType() || rhptee->isVoidType()))
5054 ; // keep old
5055
John McCall31168b02011-06-15 23:02:42 +00005056 // Treat lifetime mismatches as fatal.
5057 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5058 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5059
John McCall4fff8f62011-02-01 00:10:29 +00005060 // For GCC compatibility, other qualifier mismatches are treated
5061 // as still compatible in C.
5062 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5063 }
Steve Naroff3f597292007-05-11 22:18:03 +00005064
Mike Stump4e1f26a2009-02-19 03:04:26 +00005065 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5066 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005067 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005068 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005069 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005070 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005071
Chris Lattner0a788432008-01-03 22:56:36 +00005072 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005073 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005074 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005075 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005076
Chris Lattner0a788432008-01-03 22:56:36 +00005077 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005078 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005079 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005080
5081 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005082 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005083 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005084 }
John McCall4fff8f62011-02-01 00:10:29 +00005085
Mike Stump4e1f26a2009-02-19 03:04:26 +00005086 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005087 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005088 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5089 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005090 // Check if the pointee types are compatible ignoring the sign.
5091 // We explicitly check for char so that we catch "char" vs
5092 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005093 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005094 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005095 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005096 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005097
Chris Lattnerec3a1562009-10-17 20:33:28 +00005098 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005099 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005100 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005101 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005102
John McCall4fff8f62011-02-01 00:10:29 +00005103 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005104 // Types are compatible ignoring the sign. Qualifier incompatibility
5105 // takes priority over sign incompatibility because the sign
5106 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005107 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005108 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005109
John McCallaba90822011-01-31 23:13:11 +00005110 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005111 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005112
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005113 // If we are a multi-level pointer, it's possible that our issue is simply
5114 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5115 // the eventual target type is the same and the pointers have the same
5116 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005117 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005118 do {
John McCall4fff8f62011-02-01 00:10:29 +00005119 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5120 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005121 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005122
John McCall4fff8f62011-02-01 00:10:29 +00005123 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005124 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005125 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005126
Eli Friedman80160bd2009-03-22 23:59:44 +00005127 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005128 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005129 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005130 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005131}
5132
John McCallaba90822011-01-31 23:13:11 +00005133/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005134/// block pointer types are compatible or whether a block and normal pointer
5135/// are compatible. It is more restrict than comparing two function pointer
5136// types.
John McCallaba90822011-01-31 23:13:11 +00005137static Sema::AssignConvertType
5138checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5139 QualType rhsType) {
5140 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5141 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5142
Steve Naroff081c7422008-09-04 15:10:53 +00005143 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005144
Steve Naroff081c7422008-09-04 15:10:53 +00005145 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00005146 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5147 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005148
John McCallaba90822011-01-31 23:13:11 +00005149 // In C++, the types have to match exactly.
5150 if (S.getLangOptions().CPlusPlus)
5151 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005152
John McCallaba90822011-01-31 23:13:11 +00005153 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005154
Steve Naroff081c7422008-09-04 15:10:53 +00005155 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005156 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5157 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005158
John McCallaba90822011-01-31 23:13:11 +00005159 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5160 return Sema::IncompatibleBlockPointer;
5161
Steve Naroff081c7422008-09-04 15:10:53 +00005162 return ConvTy;
5163}
5164
John McCallaba90822011-01-31 23:13:11 +00005165/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005166/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005167static Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005168checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType,
5169 QualType rhsType) {
John McCallaba90822011-01-31 23:13:11 +00005170 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5171 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5172
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005173 if (lhsType->isObjCBuiltinType()) {
5174 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005175 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5176 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005177 return Sema::IncompatiblePointer;
5178 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005179 }
5180 if (rhsType->isObjCBuiltinType()) {
5181 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005182 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5183 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005184 return Sema::IncompatiblePointer;
5185 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005186 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005187 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005188 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005189 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005190 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005191
John McCallaba90822011-01-31 23:13:11 +00005192 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5193 return Sema::CompatiblePointerDiscardsQualifiers;
5194
5195 if (S.Context.typesAreCompatible(lhsType, rhsType))
5196 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005197 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005198 return Sema::IncompatibleObjCQualifiedId;
5199 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005200}
5201
John McCall29600e12010-11-16 02:32:08 +00005202Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005203Sema::CheckAssignmentConstraints(SourceLocation Loc,
5204 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00005205 // Fake up an opaque expression. We don't actually care about what
5206 // cast operations are required, so if CheckAssignmentConstraints
5207 // adds casts to this they'll be wasted, but fortunately that doesn't
5208 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00005209 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00005210 ExprResult rhsPtr = &rhs;
John McCall29600e12010-11-16 02:32:08 +00005211 CastKind K = CK_Invalid;
5212
5213 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5214}
5215
Mike Stump4e1f26a2009-02-19 03:04:26 +00005216/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5217/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005218/// pointers. Here are some objectionable examples that GCC considers warnings:
5219///
5220/// int a, *pint;
5221/// short *pshort;
5222/// struct foo *pfoo;
5223///
5224/// pint = pshort; // warning: assignment from incompatible pointer type
5225/// a = pint; // warning: assignment makes integer from pointer without a cast
5226/// pint = a; // warning: assignment makes pointer from integer without a cast
5227/// pint = pfoo; // warning: assignment from incompatible pointer type
5228///
5229/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005230/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005231///
John McCall8cb679e2010-11-15 09:13:47 +00005232/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005233Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005234Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCall8cb679e2010-11-15 09:13:47 +00005235 CastKind &Kind) {
John Wiegley01296292011-04-08 18:41:53 +00005236 QualType rhsType = rhs.get()->getType();
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005237 QualType origLhsType = lhsType;
John McCall29600e12010-11-16 02:32:08 +00005238
Chris Lattnera52c2f22008-01-04 23:18:45 +00005239 // Get canonical types. We're not formatting these types, just comparing
5240 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00005241 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5242 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005243
John McCalle5255932011-01-31 22:28:28 +00005244 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00005245 if (lhsType == rhsType) {
5246 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005247 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005248 }
5249
Douglas Gregor6b754842008-10-28 00:22:11 +00005250 // If the left-hand side is a reference type, then we are in a
5251 // (rare!) case where we've allowed the use of references in C,
5252 // e.g., as a parameter type in a built-in function. In this case,
5253 // just make sure that the type referenced is compatible with the
5254 // right-hand side type. The caller is responsible for adjusting
5255 // lhsType so that the resulting expression does not have reference
5256 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005257 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005258 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5259 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005260 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005261 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005262 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005263 }
John McCalle5255932011-01-31 22:28:28 +00005264
Nate Begemanbd956c42009-06-28 02:36:38 +00005265 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5266 // to the same ExtVector type.
5267 if (lhsType->isExtVectorType()) {
5268 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005269 return Incompatible;
5270 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005271 // CK_VectorSplat does T -> vector T, so first cast to the
5272 // element type.
5273 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5274 if (elType != rhsType) {
5275 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley01296292011-04-08 18:41:53 +00005276 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005277 }
5278 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005279 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005280 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005281 }
Mike Stump11289f42009-09-09 15:08:12 +00005282
John McCalle5255932011-01-31 22:28:28 +00005283 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00005284 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005285 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005286 // Allow assignments of an AltiVec vector type to an equivalent GCC
5287 // vector type and vice versa
5288 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5289 Kind = CK_BitCast;
5290 return Compatible;
5291 }
5292
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005293 // If we are allowing lax vector conversions, and LHS and RHS are both
5294 // vectors, the total size only needs to be the same. This is a bitcast;
5295 // no bits are changed but the result type is different.
5296 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00005297 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00005298 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005299 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005300 }
Chris Lattner881a2122008-01-04 23:32:24 +00005301 }
5302 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005303 }
Eli Friedman3360d892008-05-30 18:07:22 +00005304
John McCalle5255932011-01-31 22:28:28 +00005305 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00005306 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00005307 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00005308 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005309 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005310 }
Eli Friedman3360d892008-05-30 18:07:22 +00005311
John McCalle5255932011-01-31 22:28:28 +00005312 // Conversions to normal pointers.
5313 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5314 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00005315 if (isa<PointerType>(rhsType)) {
5316 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00005317 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00005318 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005319
John McCalle5255932011-01-31 22:28:28 +00005320 // int -> T*
5321 if (rhsType->isIntegerType()) {
5322 Kind = CK_IntegralToPointer; // FIXME: null?
5323 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005324 }
John McCalle5255932011-01-31 22:28:28 +00005325
5326 // C pointers are not compatible with ObjC object pointers,
5327 // with two exceptions:
5328 if (isa<ObjCObjectPointerType>(rhsType)) {
5329 // - conversions to void*
5330 if (lhsPointer->getPointeeType()->isVoidType()) {
5331 Kind = CK_AnyPointerToObjCPointerCast;
5332 return Compatible;
5333 }
5334
5335 // - conversions from 'Class' to the redefinition type
5336 if (rhsType->isObjCClassType() &&
5337 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005338 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005339 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005340 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005341
John McCalle5255932011-01-31 22:28:28 +00005342 Kind = CK_BitCast;
5343 return IncompatiblePointer;
5344 }
5345
5346 // U^ -> void*
5347 if (rhsType->getAs<BlockPointerType>()) {
5348 if (lhsPointer->getPointeeType()->isVoidType()) {
5349 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005350 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005351 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005352 }
John McCalle5255932011-01-31 22:28:28 +00005353
Steve Naroff081c7422008-09-04 15:10:53 +00005354 return Incompatible;
5355 }
5356
John McCalle5255932011-01-31 22:28:28 +00005357 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00005358 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005359 // U^ -> T^
5360 if (rhsType->isBlockPointerType()) {
5361 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00005362 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00005363 }
5364
5365 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005366 if (rhsType->isIntegerType()) {
5367 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005368 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005369 }
5370
John McCalle5255932011-01-31 22:28:28 +00005371 // id -> T^
5372 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5373 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005374 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005375 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005376
John McCalle5255932011-01-31 22:28:28 +00005377 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005378 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005379 if (RHSPT->getPointeeType()->isVoidType()) {
5380 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005381 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005382 }
John McCall8cb679e2010-11-15 09:13:47 +00005383
Chris Lattnera52c2f22008-01-04 23:18:45 +00005384 return Incompatible;
5385 }
5386
John McCalle5255932011-01-31 22:28:28 +00005387 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005388 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005389 // A* -> B*
5390 if (rhsType->isObjCObjectPointerType()) {
5391 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005392 Sema::AssignConvertType result =
5393 checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
5394 if (getLangOptions().ObjCAutoRefCount &&
5395 result == Compatible &&
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005396 !CheckObjCARCUnavailableWeakConversion(origLhsType, rhsType))
5397 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005398 return result;
John McCalle5255932011-01-31 22:28:28 +00005399 }
5400
5401 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00005402 if (rhsType->isIntegerType()) {
5403 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005404 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005405 }
5406
John McCalle5255932011-01-31 22:28:28 +00005407 // In general, C pointers are not compatible with ObjC object pointers,
5408 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00005409 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005410 // - conversions from 'void*'
5411 if (rhsType->isVoidPointerType()) {
5412 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005413 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005414 }
5415
5416 // - conversions to 'Class' from its redefinition type
5417 if (lhsType->isObjCClassType() &&
5418 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
5419 Kind = CK_BitCast;
5420 return Compatible;
5421 }
5422
5423 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005424 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005425 }
John McCalle5255932011-01-31 22:28:28 +00005426
5427 // T^ -> A*
5428 if (rhsType->isBlockPointerType()) {
5429 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005430 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005431 }
5432
Steve Naroff7cae42b2009-07-10 23:34:53 +00005433 return Incompatible;
5434 }
John McCalle5255932011-01-31 22:28:28 +00005435
5436 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00005437 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005438 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005439 if (lhsType == Context.BoolTy) {
5440 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005441 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005442 }
Eli Friedman3360d892008-05-30 18:07:22 +00005443
John McCalle5255932011-01-31 22:28:28 +00005444 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005445 if (lhsType->isIntegerType()) {
5446 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005447 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005448 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005449
Chris Lattnera52c2f22008-01-04 23:18:45 +00005450 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005451 }
John McCalle5255932011-01-31 22:28:28 +00005452
5453 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005454 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005455 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005456 if (lhsType == Context.BoolTy) {
5457 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005458 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005459 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005460
John McCalle5255932011-01-31 22:28:28 +00005461 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005462 if (lhsType->isIntegerType()) {
5463 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005464 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005465 }
5466
Steve Naroff7cae42b2009-07-10 23:34:53 +00005467 return Incompatible;
5468 }
Eli Friedman3360d892008-05-30 18:07:22 +00005469
John McCalle5255932011-01-31 22:28:28 +00005470 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00005471 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005472 if (Context.typesAreCompatible(lhsType, rhsType)) {
5473 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005474 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005475 }
Bill Wendling216423b2007-05-30 06:30:29 +00005476 }
John McCalle5255932011-01-31 22:28:28 +00005477
Steve Naroff98cf3e92007-06-06 18:38:38 +00005478 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005479}
5480
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005481/// \brief Constructs a transparent union from an expression that is
5482/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005483static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5484 ExprResult &EResult, QualType UnionType,
5485 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005486 // Build an initializer list that designates the appropriate member
5487 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005488 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005489 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005490 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005491 SourceLocation());
5492 Initializer->setType(UnionType);
5493 Initializer->setInitializedFieldInUnion(Field);
5494
5495 // Build a compound literal constructing a value of the transparent
5496 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005497 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005498 EResult = S.Owned(
5499 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5500 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005501}
5502
5503Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005504Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
5505 ExprResult &rExpr) {
John Wiegley01296292011-04-08 18:41:53 +00005506 QualType FromType = rExpr.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005507
Mike Stump11289f42009-09-09 15:08:12 +00005508 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005509 // transparent_union GCC extension.
5510 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005511 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005512 return Incompatible;
5513
5514 // The field to initialize within the transparent union.
5515 RecordDecl *UD = UT->getDecl();
5516 FieldDecl *InitField = 0;
5517 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005518 for (RecordDecl::field_iterator it = UD->field_begin(),
5519 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005520 it != itend; ++it) {
5521 if (it->getType()->isPointerType()) {
5522 // If the transparent union contains a pointer type, we allow:
5523 // 1) void pointer
5524 // 2) null pointer constant
5525 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005526 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley01296292011-04-08 18:41:53 +00005527 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005528 InitField = *it;
5529 break;
5530 }
Mike Stump11289f42009-09-09 15:08:12 +00005531
John Wiegley01296292011-04-08 18:41:53 +00005532 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005533 Expr::NPC_ValueDependentIsNull)) {
Richard Trieucfc491d2011-08-02 04:35:43 +00005534 rExpr = ImpCastExprToType(rExpr.take(), it->getType(),
5535 CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005536 InitField = *it;
5537 break;
5538 }
5539 }
5540
John McCall8cb679e2010-11-15 09:13:47 +00005541 CastKind Kind = CK_Invalid;
John Wiegley01296292011-04-08 18:41:53 +00005542 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005543 == Compatible) {
John Wiegley01296292011-04-08 18:41:53 +00005544 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005545 InitField = *it;
5546 break;
5547 }
5548 }
5549
5550 if (!InitField)
5551 return Incompatible;
5552
John Wiegley01296292011-04-08 18:41:53 +00005553 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005554 return Compatible;
5555}
5556
Chris Lattner9bad62c2008-01-04 18:04:52 +00005557Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005558Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005559 if (getLangOptions().CPlusPlus) {
5560 if (!lhsType->isRecordType()) {
5561 // C++ 5.17p3: If the left operand is not of class type, the
5562 // expression is implicitly converted (C++ 4) to the
5563 // cv-unqualified type of the left operand.
John Wiegley01296292011-04-08 18:41:53 +00005564 ExprResult Res = PerformImplicitConversion(rExpr.get(),
5565 lhsType.getUnqualifiedType(),
5566 AA_Assigning);
5567 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005568 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005569 Sema::AssignConvertType result = Compatible;
5570 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieucfc491d2011-08-02 04:35:43 +00005571 !CheckObjCARCUnavailableWeakConversion(lhsType,
5572 rExpr.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005573 result = IncompatibleObjCWeakRef;
John Wiegley01296292011-04-08 18:41:53 +00005574 rExpr = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005575 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005576 }
5577
5578 // FIXME: Currently, we fall through and treat C++ classes like C
5579 // structures.
John McCall34376a62010-12-04 03:47:34 +00005580 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005581
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005582 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5583 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00005584 if ((lhsType->isPointerType() ||
5585 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00005586 lhsType->isBlockPointerType())
John Wiegley01296292011-04-08 18:41:53 +00005587 && rExpr.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005588 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00005589 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005590 return Compatible;
5591 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005592
Chris Lattnere6dcd502007-10-16 02:55:40 +00005593 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005594 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005595 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005596 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005597 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005598 // Suppress this for references: C++ 8.5.3p5.
John Wiegley01296292011-04-08 18:41:53 +00005599 if (!lhsType->isReferenceType()) {
5600 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
5601 if (rExpr.isInvalid())
5602 return Incompatible;
5603 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005604
John McCall8cb679e2010-11-15 09:13:47 +00005605 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005606 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00005607 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005608
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005609 // C99 6.5.16.1p2: The value of the right operand is converted to the
5610 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005611 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5612 // so that we can use references in built-in functions even in C.
5613 // The getNonReferenceType() call makes sure that the resulting expression
5614 // does not have reference type.
John Wiegley01296292011-04-08 18:41:53 +00005615 if (result != Incompatible && rExpr.get()->getType() != lhsType)
Richard Trieucfc491d2011-08-02 04:35:43 +00005616 rExpr = ImpCastExprToType(rExpr.take(),
5617 lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005618 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005619}
5620
Richard Trieucfc491d2011-08-02 04:35:43 +00005621QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex,
5622 ExprResult &rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005623 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley01296292011-04-08 18:41:53 +00005624 << lex.get()->getType() << rex.get()->getType()
5625 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005626 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005627}
5628
Eli Friedman1408bc92011-06-23 18:10:35 +00005629QualType Sema::CheckVectorOperands(ExprResult &lex, ExprResult &rex,
5630 SourceLocation Loc, bool isCompAssign) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005631 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005632 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00005633 QualType lhsType =
John Wiegley01296292011-04-08 18:41:53 +00005634 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattner574dee62008-07-26 22:17:49 +00005635 QualType rhsType =
John Wiegley01296292011-04-08 18:41:53 +00005636 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005637
Nate Begeman191a6b12008-07-14 18:02:46 +00005638 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005639 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00005640 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005641
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005642 // Handle the case of equivalent AltiVec and GCC vector types
5643 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5644 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005645 if (lhsType->isExtVectorType()) {
5646 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5647 return lhsType;
5648 }
5649
5650 if (!isCompAssign)
5651 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005652 return rhsType;
5653 }
5654
Eli Friedman1408bc92011-06-23 18:10:35 +00005655 if (getLangOptions().LaxVectorConversions &&
5656 Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) {
5657 // If we are allowing lax vector conversions, and LHS and RHS are both
5658 // vectors, the total size only needs to be the same. This is a
5659 // bitcast; no bits are changed but the result type is different.
5660 // FIXME: Should we really be allowing this?
5661 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5662 return lhsType;
5663 }
5664
Nate Begemanbd956c42009-06-28 02:36:38 +00005665 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5666 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5667 bool swapped = false;
Eli Friedman1408bc92011-06-23 18:10:35 +00005668 if (rhsType->isExtVectorType() && !isCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005669 swapped = true;
5670 std::swap(rex, lex);
5671 std::swap(rhsType, lhsType);
5672 }
Mike Stump11289f42009-09-09 15:08:12 +00005673
Nate Begeman886448d2009-06-28 19:12:57 +00005674 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00005675 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005676 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005677 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00005678 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5679 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00005680 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005681 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00005682 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005683 if (swapped) std::swap(rex, lex);
5684 return lhsType;
5685 }
5686 }
5687 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5688 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005689 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5690 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00005691 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005692 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00005693 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005694 if (swapped) std::swap(rex, lex);
5695 return lhsType;
5696 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005697 }
5698 }
Mike Stump11289f42009-09-09 15:08:12 +00005699
Nate Begeman886448d2009-06-28 19:12:57 +00005700 // Vectors of different size or scalar and non-ext-vector are errors.
Eli Friedman1408bc92011-06-23 18:10:35 +00005701 if (swapped) std::swap(rex, lex);
Chris Lattner377d1f82008-11-18 22:52:51 +00005702 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley01296292011-04-08 18:41:53 +00005703 << lex.get()->getType() << rex.get()->getType()
5704 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005705 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005706}
5707
Richard Trieucfc491d2011-08-02 04:35:43 +00005708QualType Sema::CheckMultiplyDivideOperands(ExprResult &lex, ExprResult &rex,
5709 SourceLocation Loc,
5710 bool isCompAssign, bool isDiv) {
5711 if (lex.get()->getType()->isVectorType() ||
5712 rex.get()->getType()->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00005713 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005714
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005715 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00005716 if (lex.isInvalid() || rex.isInvalid())
5717 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005718
John Wiegley01296292011-04-08 18:41:53 +00005719 if (!lex.get()->getType()->isArithmeticType() ||
5720 !rex.get()->getType()->isArithmeticType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00005721 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005722
Chris Lattnerfaa54172010-01-12 21:23:57 +00005723 // Check for division by zero.
5724 if (isDiv &&
Richard Trieucfc491d2011-08-02 04:35:43 +00005725 rex.get()->isNullPointerConstant(Context,
5726 Expr::NPC_ValueDependentIsNotNull))
John Wiegley01296292011-04-08 18:41:53 +00005727 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
Richard Trieucfc491d2011-08-02 04:35:43 +00005728 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005729
Chris Lattnerfaa54172010-01-12 21:23:57 +00005730 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005731}
5732
Chris Lattnerfaa54172010-01-12 21:23:57 +00005733QualType Sema::CheckRemainderOperands(
John Wiegley01296292011-04-08 18:41:53 +00005734 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
Richard Trieucfc491d2011-08-02 04:35:43 +00005735 if (lex.get()->getType()->isVectorType() ||
5736 rex.get()->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005737 if (lex.get()->getType()->hasIntegerRepresentation() &&
5738 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedman1408bc92011-06-23 18:10:35 +00005739 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005740 return InvalidOperands(Loc, lex, rex);
5741 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005742
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005743 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00005744 if (lex.isInvalid() || rex.isInvalid())
5745 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005746
Richard Trieucfc491d2011-08-02 04:35:43 +00005747 if (!lex.get()->getType()->isIntegerType() ||
5748 !rex.get()->getType()->isIntegerType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00005749 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005750
Chris Lattnerfaa54172010-01-12 21:23:57 +00005751 // Check for remainder by zero.
Richard Trieucfc491d2011-08-02 04:35:43 +00005752 if (rex.get()->isNullPointerConstant(Context,
5753 Expr::NPC_ValueDependentIsNotNull))
John Wiegley01296292011-04-08 18:41:53 +00005754 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
5755 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005756
Chris Lattnerfaa54172010-01-12 21:23:57 +00005757 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005758}
5759
Chandler Carruthc9332212011-06-27 08:02:19 +00005760/// \brief Diagnose invalid arithmetic on two void pointers.
5761static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
5762 Expr *LHS, Expr *RHS) {
5763 S.Diag(Loc, S.getLangOptions().CPlusPlus
5764 ? diag::err_typecheck_pointer_arith_void_type
5765 : diag::ext_gnu_void_ptr)
5766 << 1 /* two pointers */ << LHS->getSourceRange() << RHS->getSourceRange();
5767}
5768
5769/// \brief Diagnose invalid arithmetic on a void pointer.
5770static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5771 Expr *Pointer) {
5772 S.Diag(Loc, S.getLangOptions().CPlusPlus
5773 ? diag::err_typecheck_pointer_arith_void_type
5774 : diag::ext_gnu_void_ptr)
5775 << 0 /* one pointer */ << Pointer->getSourceRange();
5776}
5777
5778/// \brief Diagnose invalid arithmetic on two function pointers.
5779static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5780 Expr *LHS, Expr *RHS) {
5781 assert(LHS->getType()->isAnyPointerType());
5782 assert(RHS->getType()->isAnyPointerType());
5783 S.Diag(Loc, S.getLangOptions().CPlusPlus
5784 ? diag::err_typecheck_pointer_arith_function_type
5785 : diag::ext_gnu_ptr_func_arith)
5786 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5787 // We only show the second type if it differs from the first.
5788 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5789 RHS->getType())
5790 << RHS->getType()->getPointeeType()
5791 << LHS->getSourceRange() << RHS->getSourceRange();
5792}
5793
5794/// \brief Diagnose invalid arithmetic on a function pointer.
5795static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5796 Expr *Pointer) {
5797 assert(Pointer->getType()->isAnyPointerType());
5798 S.Diag(Loc, S.getLangOptions().CPlusPlus
5799 ? diag::err_typecheck_pointer_arith_function_type
5800 : diag::ext_gnu_ptr_func_arith)
5801 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5802 << 0 /* one pointer, so only one type */
5803 << Pointer->getSourceRange();
5804}
5805
5806/// \brief Check the validity of an arithmetic pointer operand.
5807///
5808/// If the operand has pointer type, this code will check for pointer types
5809/// which are invalid in arithmetic operations. These will be diagnosed
5810/// appropriately, including whether or not the use is supported as an
5811/// extension.
5812///
5813/// \returns True when the operand is valid to use (even if as an extension).
5814static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5815 Expr *Operand) {
5816 if (!Operand->getType()->isAnyPointerType()) return true;
5817
5818 QualType PointeeTy = Operand->getType()->getPointeeType();
5819 if (PointeeTy->isVoidType()) {
5820 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5821 return !S.getLangOptions().CPlusPlus;
5822 }
5823 if (PointeeTy->isFunctionType()) {
5824 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5825 return !S.getLangOptions().CPlusPlus;
5826 }
5827
5828 if ((Operand->getType()->isPointerType() &&
5829 !Operand->getType()->isDependentType()) ||
5830 Operand->getType()->isObjCObjectPointerType()) {
5831 QualType PointeeTy = Operand->getType()->getPointeeType();
5832 if (S.RequireCompleteType(
5833 Loc, PointeeTy,
5834 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5835 << PointeeTy << Operand->getSourceRange()))
5836 return false;
5837 }
5838
5839 return true;
5840}
5841
5842/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5843/// operands.
5844///
5845/// This routine will diagnose any invalid arithmetic on pointer operands much
5846/// like \see checkArithmeticOpPointerOperand. However, it has special logic
5847/// for emitting a single diagnostic even for operations where both LHS and RHS
5848/// are (potentially problematic) pointers.
5849///
5850/// \returns True when the operand is valid to use (even if as an extension).
5851static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
5852 Expr *LHS, Expr *RHS) {
5853 bool isLHSPointer = LHS->getType()->isAnyPointerType();
5854 bool isRHSPointer = RHS->getType()->isAnyPointerType();
5855 if (!isLHSPointer && !isRHSPointer) return true;
5856
5857 QualType LHSPointeeTy, RHSPointeeTy;
5858 if (isLHSPointer) LHSPointeeTy = LHS->getType()->getPointeeType();
5859 if (isRHSPointer) RHSPointeeTy = RHS->getType()->getPointeeType();
5860
5861 // Check for arithmetic on pointers to incomplete types.
5862 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
5863 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
5864 if (isLHSVoidPtr || isRHSVoidPtr) {
5865 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHS);
5866 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHS);
5867 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHS, RHS);
5868
5869 return !S.getLangOptions().CPlusPlus;
5870 }
5871
5872 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
5873 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
5874 if (isLHSFuncPtr || isRHSFuncPtr) {
5875 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHS);
5876 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, RHS);
5877 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS, RHS);
5878
5879 return !S.getLangOptions().CPlusPlus;
5880 }
5881
5882 Expr *Operands[] = { LHS, RHS };
5883 for (unsigned i = 0; i < 2; ++i) {
5884 Expr *Operand = Operands[i];
5885 if ((Operand->getType()->isPointerType() &&
5886 !Operand->getType()->isDependentType()) ||
5887 Operand->getType()->isObjCObjectPointerType()) {
5888 QualType PointeeTy = Operand->getType()->getPointeeType();
5889 if (S.RequireCompleteType(
5890 Loc, PointeeTy,
5891 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5892 << PointeeTy << Operand->getSourceRange()))
5893 return false;
5894 }
5895 }
5896 return true;
5897}
5898
Chris Lattnerfaa54172010-01-12 21:23:57 +00005899QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00005900 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
Richard Trieucfc491d2011-08-02 04:35:43 +00005901 if (lex.get()->getType()->isVectorType() ||
5902 rex.get()->getType()->isVectorType()) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005903 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005904 if (CompLHSTy) *CompLHSTy = compType;
5905 return compType;
5906 }
Steve Naroff7a5af782007-07-13 16:58:59 +00005907
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005908 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00005909 if (lex.isInvalid() || rex.isInvalid())
5910 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00005911
Steve Naroffe4718892007-04-27 18:30:00 +00005912 // handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00005913 if (lex.get()->getType()->isArithmeticType() &&
5914 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005915 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005916 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005917 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00005918
Eli Friedman8e122982008-05-18 18:08:51 +00005919 // Put any potential pointer into PExp
John Wiegley01296292011-04-08 18:41:53 +00005920 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00005921 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00005922 std::swap(PExp, IExp);
5923
Steve Naroff6b712a72009-07-14 18:25:06 +00005924 if (PExp->getType()->isAnyPointerType()) {
Eli Friedman8e122982008-05-18 18:08:51 +00005925 if (IExp->getType()->isIntegerType()) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005926 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
5927 return QualType();
5928
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005929 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005930
Chris Lattner12bdebb2009-04-24 23:50:08 +00005931 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005932 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005933 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5934 << PointeeTy << PExp->getSourceRange();
5935 return QualType();
5936 }
Mike Stump11289f42009-09-09 15:08:12 +00005937
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005938 if (CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00005939 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman629ffb92009-08-20 04:21:42 +00005940 if (LHSTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +00005941 LHSTy = lex.get()->getType();
Eli Friedman629ffb92009-08-20 04:21:42 +00005942 if (LHSTy->isPromotableIntegerType())
5943 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005944 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005945 *CompLHSTy = LHSTy;
5946 }
Eli Friedman8e122982008-05-18 18:08:51 +00005947 return PExp->getType();
5948 }
5949 }
5950
Chris Lattner326f7572008-11-18 01:30:42 +00005951 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005952}
5953
Chris Lattner2a3569b2008-04-07 05:30:13 +00005954// C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00005955QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Richard Trieucfc491d2011-08-02 04:35:43 +00005956 SourceLocation Loc,
5957 QualType* CompLHSTy) {
5958 if (lex.get()->getType()->isVectorType() ||
5959 rex.get()->getType()->isVectorType()) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005960 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005961 if (CompLHSTy) *CompLHSTy = compType;
5962 return compType;
5963 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005964
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005965 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00005966 if (lex.isInvalid() || rex.isInvalid())
5967 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005968
Chris Lattner4d62f422007-12-09 21:53:25 +00005969 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005970
Chris Lattner4d62f422007-12-09 21:53:25 +00005971 // Handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00005972 if (lex.get()->getType()->isArithmeticType() &&
5973 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005974 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005975 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005976 }
Mike Stump11289f42009-09-09 15:08:12 +00005977
Chris Lattner4d62f422007-12-09 21:53:25 +00005978 // Either ptr - int or ptr - ptr.
John Wiegley01296292011-04-08 18:41:53 +00005979 if (lex.get()->getType()->isAnyPointerType()) {
5980 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005981
Chris Lattner12bdebb2009-04-24 23:50:08 +00005982 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005983 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005984 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley01296292011-04-08 18:41:53 +00005985 << lpointee << lex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00005986 return QualType();
5987 }
Mike Stump11289f42009-09-09 15:08:12 +00005988
Chris Lattner4d62f422007-12-09 21:53:25 +00005989 // The result type of a pointer-int computation is the pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005990 if (rex.get()->getType()->isIntegerType()) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005991 if (!checkArithmeticOpPointerOperand(*this, Loc, lex.get()))
5992 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005993
John Wiegley01296292011-04-08 18:41:53 +00005994 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
5995 return lex.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005996 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005997
Chris Lattner4d62f422007-12-09 21:53:25 +00005998 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00005999 if (const PointerType *RHSPTy
6000 = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006001 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006002
Eli Friedman168fe152009-05-16 13:54:38 +00006003 if (getLangOptions().CPlusPlus) {
6004 // Pointee types must be the same: C++ [expr.add]
6005 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6006 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00006007 << lex.get()->getType() << rex.get()->getType()
6008 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00006009 return QualType();
6010 }
6011 } else {
6012 // Pointee types must be compatible C99 6.5.6p3
6013 if (!Context.typesAreCompatible(
6014 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6015 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6016 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00006017 << lex.get()->getType() << rex.get()->getType()
6018 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00006019 return QualType();
6020 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006021 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006022
Chandler Carruthc9332212011-06-27 08:02:19 +00006023 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
6024 lex.get(), rex.get()))
6025 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006026
John Wiegley01296292011-04-08 18:41:53 +00006027 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006028 return Context.getPointerDiffType();
6029 }
6030 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006031
Chris Lattner326f7572008-11-18 01:30:42 +00006032 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006033}
6034
Douglas Gregor0bf31402010-10-08 23:50:27 +00006035static bool isScopedEnumerationType(QualType T) {
6036 if (const EnumType *ET = dyn_cast<EnumType>(T))
6037 return ET->getDecl()->isScoped();
6038 return false;
6039}
6040
John Wiegley01296292011-04-08 18:41:53 +00006041static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006042 SourceLocation Loc, unsigned Opc,
6043 QualType LHSTy) {
6044 llvm::APSInt Right;
6045 // Check right/shifter operand
Richard Trieucfc491d2011-08-02 04:35:43 +00006046 if (rex.get()->isValueDependent() ||
6047 !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006048 return;
6049
6050 if (Right.isNegative()) {
John Wiegley01296292011-04-08 18:41:53 +00006051 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006052 S.PDiag(diag::warn_shift_negative)
John Wiegley01296292011-04-08 18:41:53 +00006053 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006054 return;
6055 }
6056 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley01296292011-04-08 18:41:53 +00006057 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006058 if (Right.uge(LeftBits)) {
John Wiegley01296292011-04-08 18:41:53 +00006059 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006060 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley01296292011-04-08 18:41:53 +00006061 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006062 return;
6063 }
6064 if (Opc != BO_Shl)
6065 return;
6066
6067 // When left shifting an ICE which is signed, we can check for overflow which
6068 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6069 // integers have defined behavior modulo one more than the maximum value
6070 // representable in the result type, so never warn for those.
6071 llvm::APSInt Left;
Richard Trieucfc491d2011-08-02 04:35:43 +00006072 if (lex.get()->isValueDependent() ||
6073 !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006074 LHSTy->hasUnsignedIntegerRepresentation())
6075 return;
6076 llvm::APInt ResultBits =
6077 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6078 if (LeftBits.uge(ResultBits))
6079 return;
6080 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6081 Result = Result.shl(Right);
6082
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006083 // Print the bit representation of the signed integer as an unsigned
6084 // hexadecimal number.
6085 llvm::SmallString<40> HexResult;
6086 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6087
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006088 // If we are only missing a sign bit, this is less likely to result in actual
6089 // bugs -- if the result is cast back to an unsigned type, it will have the
6090 // expected value. Thus we place this behind a different warning that can be
6091 // turned off separately if needed.
6092 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006093 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6094 << HexResult.str() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00006095 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006096 return;
6097 }
6098
6099 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006100 << HexResult.str() << Result.getMinSignedBits() << LHSTy
Richard Trieucfc491d2011-08-02 04:35:43 +00006101 << Left.getBitWidth() << lex.get()->getSourceRange()
6102 << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006103}
6104
Chris Lattner2a3569b2008-04-07 05:30:13 +00006105// C99 6.5.7
Richard Trieucfc491d2011-08-02 04:35:43 +00006106QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex,
6107 SourceLocation Loc, unsigned Opc,
6108 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00006109 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley01296292011-04-08 18:41:53 +00006110 if (!lex.get()->getType()->hasIntegerRepresentation() ||
6111 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006112 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006113
Douglas Gregor0bf31402010-10-08 23:50:27 +00006114 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6115 // hasIntegerRepresentation() above instead of this.
John Wiegley01296292011-04-08 18:41:53 +00006116 if (isScopedEnumerationType(lex.get()->getType()) ||
6117 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00006118 return InvalidOperands(Loc, lex, rex);
6119 }
6120
Nate Begemane46ee9a2009-10-25 02:26:48 +00006121 // Vector shifts promote their scalar inputs to vector type.
Richard Trieucfc491d2011-08-02 04:35:43 +00006122 if (lex.get()->getType()->isVectorType() ||
6123 rex.get()->getType()->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00006124 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006125
Chris Lattner5c11c412007-12-12 05:47:28 +00006126 // Shifts don't perform usual arithmetic conversions, they just do integer
6127 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006128
John McCall57cdd882010-12-16 19:28:59 +00006129 // For the LHS, do usual unary conversions, but then reset them away
6130 // if this is a compound assignment.
John Wiegley01296292011-04-08 18:41:53 +00006131 ExprResult old_lex = lex;
6132 lex = UsualUnaryConversions(lex.take());
6133 if (lex.isInvalid())
6134 return QualType();
6135 QualType LHSTy = lex.get()->getType();
John McCall57cdd882010-12-16 19:28:59 +00006136 if (isCompAssign) lex = old_lex;
6137
6138 // The RHS is simpler.
John Wiegley01296292011-04-08 18:41:53 +00006139 rex = UsualUnaryConversions(rex.take());
6140 if (rex.isInvalid())
6141 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006142
Ryan Flynnf53fab82009-08-07 16:20:20 +00006143 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006144 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006145
Chris Lattner5c11c412007-12-12 05:47:28 +00006146 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006147 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006148}
6149
Chandler Carruth17773fc2010-07-10 12:30:03 +00006150static bool IsWithinTemplateSpecialization(Decl *D) {
6151 if (DeclContext *DC = D->getDeclContext()) {
6152 if (isa<ClassTemplateSpecializationDecl>(DC))
6153 return true;
6154 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6155 return FD->isFunctionTemplateSpecialization();
6156 }
6157 return false;
6158}
6159
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006160// C99 6.5.8, C++ [expr.rel]
Richard Trieucfc491d2011-08-02 04:35:43 +00006161QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex,
6162 SourceLocation Loc, unsigned OpaqueOpc,
6163 bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00006164 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006165
Chris Lattner9a152e22009-12-05 05:40:13 +00006166 // Handle vector comparisons separately.
Richard Trieucfc491d2011-08-02 04:35:43 +00006167 if (lex.get()->getType()->isVectorType() ||
6168 rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006169 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006170
John Wiegley01296292011-04-08 18:41:53 +00006171 QualType lType = lex.get()->getType();
6172 QualType rType = rex.get()->getType();
Douglas Gregor1beec452011-03-12 01:48:56 +00006173
John Wiegley01296292011-04-08 18:41:53 +00006174 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
6175 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006176 QualType LHSStrippedType = LHSStripped->getType();
6177 QualType RHSStrippedType = RHSStripped->getType();
6178
Douglas Gregor1beec452011-03-12 01:48:56 +00006179
6180
Chandler Carruth712563b2011-02-17 08:37:06 +00006181 // Two different enums will raise a warning when compared.
6182 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
6183 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
6184 if (LHSEnumType->getDecl()->getIdentifier() &&
6185 RHSEnumType->getDecl()->getIdentifier() &&
6186 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
6187 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6188 << LHSStrippedType << RHSStrippedType
John Wiegley01296292011-04-08 18:41:53 +00006189 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth712563b2011-02-17 08:37:06 +00006190 }
6191 }
6192 }
6193
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006194 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00006195 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley01296292011-04-08 18:41:53 +00006196 !lex.get()->getLocStart().isMacroID() &&
6197 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006198 // For non-floating point types, check for self-comparisons of the form
6199 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6200 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006201 //
6202 // NOTE: Don't warn about comparison expressions resulting from macro
6203 // expansion. Also don't warn about comparisons which are only self
6204 // comparisons within a template specialization. The warnings should catch
6205 // obvious cases in the definition of the template anyways. The idea is to
6206 // warn when the typed comparison operator will always evaluate to the same
6207 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006208 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006209 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006210 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006211 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006212 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006213 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006214 << (Opc == BO_EQ
6215 || Opc == BO_LE
6216 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00006217 } else if (lType->isArrayType() && rType->isArrayType() &&
6218 !DRL->getDecl()->getType()->isReferenceType() &&
6219 !DRR->getDecl()->getType()->isReferenceType()) {
6220 // what is it always going to eval to?
6221 char always_evals_to;
6222 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006223 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006224 always_evals_to = 0; // false
6225 break;
John McCalle3027922010-08-25 11:45:40 +00006226 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006227 always_evals_to = 1; // true
6228 break;
6229 default:
6230 // best we can say is 'a constant'
6231 always_evals_to = 2; // e.g. array1 <= array2
6232 break;
6233 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006234 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006235 << 1 // array
6236 << always_evals_to);
6237 }
6238 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006239 }
Mike Stump11289f42009-09-09 15:08:12 +00006240
Chris Lattner222b8bd2009-03-08 19:39:53 +00006241 if (isa<CastExpr>(LHSStripped))
6242 LHSStripped = LHSStripped->IgnoreParenCasts();
6243 if (isa<CastExpr>(RHSStripped))
6244 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006245
Chris Lattner222b8bd2009-03-08 19:39:53 +00006246 // Warn about comparisons against a string constant (unless the other
6247 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006248 Expr *literalString = 0;
6249 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006250 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006251 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006252 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006253 literalString = lex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006254 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006255 } else if ((isa<StringLiteral>(RHSStripped) ||
6256 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006257 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006258 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006259 literalString = rex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006260 literalStringStripped = RHSStripped;
6261 }
6262
6263 if (literalString) {
6264 std::string resultComparison;
6265 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006266 case BO_LT: resultComparison = ") < 0"; break;
6267 case BO_GT: resultComparison = ") > 0"; break;
6268 case BO_LE: resultComparison = ") <= 0"; break;
6269 case BO_GE: resultComparison = ") >= 0"; break;
6270 case BO_EQ: resultComparison = ") == 0"; break;
6271 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006272 default: assert(false && "Invalid comparison operator");
6273 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006274
Ted Kremenek3427fac2011-02-23 01:52:04 +00006275 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006276 PDiag(diag::warn_stringcompare)
6277 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006278 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006279 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006280 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006281
Douglas Gregorec170db2010-06-08 19:50:34 +00006282 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieucfc491d2011-08-02 04:35:43 +00006283 if (lex.get()->getType()->isArithmeticType() &&
6284 rex.get()->getType()->isArithmeticType()) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006285 UsualArithmeticConversions(lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00006286 if (lex.isInvalid() || rex.isInvalid())
6287 return QualType();
6288 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006289 else {
John Wiegley01296292011-04-08 18:41:53 +00006290 lex = UsualUnaryConversions(lex.take());
6291 if (lex.isInvalid())
6292 return QualType();
6293
6294 rex = UsualUnaryConversions(rex.take());
6295 if (rex.isInvalid())
6296 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006297 }
6298
John Wiegley01296292011-04-08 18:41:53 +00006299 lType = lex.get()->getType();
6300 rType = rex.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006301
Douglas Gregorca63811b2008-11-19 03:25:36 +00006302 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006303 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006304
Chris Lattnerb620c342007-08-26 01:18:55 +00006305 if (isRelational) {
6306 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006307 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006308 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006309 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006310 if (lType->hasFloatingRepresentation())
John Wiegley01296292011-04-08 18:41:53 +00006311 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006312
Chris Lattnerb620c342007-08-26 01:18:55 +00006313 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006314 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006315 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006316
John Wiegley01296292011-04-08 18:41:53 +00006317 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006318 Expr::NPC_ValueDependentIsNull);
John Wiegley01296292011-04-08 18:41:53 +00006319 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006320 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006321
Douglas Gregorf267edd2010-06-15 21:38:40 +00006322 // All of the following pointer-related warnings are GCC extensions, except
6323 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00006324 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006325 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006326 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00006327 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006328 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006329
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006330 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006331 if (LCanPointeeTy == RCanPointeeTy)
6332 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006333 if (!isRelational &&
6334 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6335 // Valid unless comparison between non-null pointer and function pointer
6336 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006337 // In a SFINAE context, we treat this as a hard error to maintain
6338 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006339 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6340 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00006341 Diag(Loc,
6342 isSFINAEContext()?
6343 diag::err_typecheck_comparison_of_fptr_to_void
6344 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieucfc491d2011-08-02 04:35:43 +00006345 << lType << rType << lex.get()->getSourceRange()
6346 << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006347
6348 if (isSFINAEContext())
6349 return QualType();
6350
John Wiegley01296292011-04-08 18:41:53 +00006351 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006352 return ResultTy;
6353 }
6354 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006355
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006356 // C++ [expr.rel]p2:
6357 // [...] Pointer conversions (4.10) and qualification
6358 // conversions (4.4) are performed on pointer operands (or on
6359 // a pointer operand and a null pointer constant) to bring
6360 // them to their composite pointer type. [...]
6361 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006362 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006363 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006364 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006365 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006366 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006367 if (T.isNull()) {
6368 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00006369 << lType << rType << lex.get()->getSourceRange()
6370 << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006371 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006372 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006373 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006374 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006375 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00006376 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006377 }
6378
John Wiegley01296292011-04-08 18:41:53 +00006379 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6380 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006381 return ResultTy;
6382 }
Eli Friedman16c209612009-08-23 00:27:47 +00006383 // C99 6.5.9p2 and C99 6.5.8p2
6384 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6385 RCanPointeeTy.getUnqualifiedType())) {
6386 // Valid unless a relational comparison of function pointers
6387 if (isRelational && LCanPointeeTy->isFunctionType()) {
6388 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00006389 << lType << rType << lex.get()->getSourceRange()
6390 << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006391 }
6392 } else if (!isRelational &&
6393 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6394 // Valid unless comparison between non-null pointer and function pointer
6395 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6396 && !LHSIsNull && !RHSIsNull) {
6397 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieucfc491d2011-08-02 04:35:43 +00006398 << lType << rType << lex.get()->getSourceRange()
6399 << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006400 }
6401 } else {
6402 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00006403 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00006404 << lType << rType << lex.get()->getSourceRange()
6405 << rex.get()->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00006406 }
John McCall7684dde2011-03-11 04:25:25 +00006407 if (LCanPointeeTy != RCanPointeeTy) {
6408 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006409 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006410 else
John Wiegley01296292011-04-08 18:41:53 +00006411 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006412 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006413 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006414 }
Mike Stump11289f42009-09-09 15:08:12 +00006415
Sebastian Redl576fd422009-05-10 18:38:11 +00006416 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006417 // Comparison of nullptr_t with itself.
6418 if (lType->isNullPtrType() && rType->isNullPtrType())
6419 return ResultTy;
6420
Mike Stump11289f42009-09-09 15:08:12 +00006421 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006422 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006423 if (RHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00006424 ((lType->isAnyPointerType() || lType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00006425 (!isRelational &&
6426 (lType->isMemberPointerType() || lType->isBlockPointerType())))) {
John Wiegley01296292011-04-08 18:41:53 +00006427 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00006428 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006429 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006430 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006431 return ResultTy;
6432 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006433 if (LHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00006434 ((rType->isAnyPointerType() || rType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00006435 (!isRelational &&
6436 (rType->isMemberPointerType() || rType->isBlockPointerType())))) {
John Wiegley01296292011-04-08 18:41:53 +00006437 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00006438 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006439 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006440 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006441 return ResultTy;
6442 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006443
6444 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00006445 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006446 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6447 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006448 // In addition, pointers to members can be compared, or a pointer to
6449 // member and a null pointer constant. Pointer to member conversions
6450 // (4.11) and qualification conversions (4.4) are performed to bring
6451 // them to a common type. If one operand is a null pointer constant,
6452 // the common type is the type of the other operand. Otherwise, the
6453 // common type is a pointer to member type similar (4.4) to the type
6454 // of one of the operands, with a cv-qualification signature (4.4)
6455 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006456 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006457 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006458 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006459 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006460 if (T.isNull()) {
6461 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00006462 << lType << rType << lex.get()->getSourceRange()
6463 << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006464 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006465 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006466 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006467 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006468 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00006469 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006470 }
Mike Stump11289f42009-09-09 15:08:12 +00006471
John Wiegley01296292011-04-08 18:41:53 +00006472 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6473 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006474 return ResultTy;
6475 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006476
6477 // Handle scoped enumeration types specifically, since they don't promote
6478 // to integers.
John Wiegley01296292011-04-08 18:41:53 +00006479 if (lex.get()->getType()->isEnumeralType() &&
Richard Trieucfc491d2011-08-02 04:35:43 +00006480 Context.hasSameUnqualifiedType(lex.get()->getType(),
6481 rex.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006482 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00006483 }
Mike Stump11289f42009-09-09 15:08:12 +00006484
Steve Naroff081c7422008-09-04 15:10:53 +00006485 // Handle block pointer types.
Richard Trieucfc491d2011-08-02 04:35:43 +00006486 if (!isRelational && lType->isBlockPointerType() &&
6487 rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006488 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6489 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006490
Steve Naroff081c7422008-09-04 15:10:53 +00006491 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006492 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006493 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieucfc491d2011-08-02 04:35:43 +00006494 << lType << rType << lex.get()->getSourceRange()
6495 << rex.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006496 }
John Wiegley01296292011-04-08 18:41:53 +00006497 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006498 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006499 }
John Wiegley01296292011-04-08 18:41:53 +00006500
Steve Naroffe18f94c2008-09-28 01:11:11 +00006501 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00006502 if (!isRelational
6503 && ((lType->isBlockPointerType() && rType->isPointerType())
6504 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006505 if (!LHSIsNull && !RHSIsNull) {
John McCall7684dde2011-03-11 04:25:25 +00006506 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006507 ->getPointeeType()->isVoidType())
John McCall7684dde2011-03-11 04:25:25 +00006508 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006509 ->getPointeeType()->isVoidType())))
6510 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieucfc491d2011-08-02 04:35:43 +00006511 << lType << rType << lex.get()->getSourceRange()
6512 << rex.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006513 }
John McCall7684dde2011-03-11 04:25:25 +00006514 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006515 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006516 else
John Wiegley01296292011-04-08 18:41:53 +00006517 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006518 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006519 }
Steve Naroff081c7422008-09-04 15:10:53 +00006520
John McCall7684dde2011-03-11 04:25:25 +00006521 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
6522 const PointerType *LPT = lType->getAs<PointerType>();
6523 const PointerType *RPT = rType->getAs<PointerType>();
6524 if (LPT || RPT) {
6525 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6526 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006527
Steve Naroff753567f2008-11-17 19:49:16 +00006528 if (!LPtrToVoid && !RPtrToVoid &&
6529 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006530 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00006531 << lType << rType << lex.get()->getSourceRange()
6532 << rex.get()->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006533 }
John McCall7684dde2011-03-11 04:25:25 +00006534 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006535 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006536 else
John Wiegley01296292011-04-08 18:41:53 +00006537 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006538 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006539 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006540 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006541 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006542 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00006543 << lType << rType << lex.get()->getSourceRange()
6544 << rex.get()->getSourceRange();
John McCall7684dde2011-03-11 04:25:25 +00006545 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006546 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006547 else
John Wiegley01296292011-04-08 18:41:53 +00006548 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006549 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006550 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006551 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006552 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6553 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006554 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006555 bool isError = false;
6556 if ((LHSIsNull && lType->isIntegerType()) ||
6557 (RHSIsNull && rType->isIntegerType())) {
6558 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006559 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006560 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006561 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006562 else if (getLangOptions().CPlusPlus) {
6563 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6564 isError = true;
6565 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006566 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006567
Chris Lattnerd99bd522009-08-23 00:03:44 +00006568 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006569 Diag(Loc, DiagID)
Richard Trieucfc491d2011-08-02 04:35:43 +00006570 << lType << rType << lex.get()->getSourceRange()
6571 << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006572 if (isError)
6573 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006574 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006575
6576 if (lType->isIntegerType())
John Wiegley01296292011-04-08 18:41:53 +00006577 lex = ImpCastExprToType(lex.take(), rType,
John McCalle84af4e2010-11-13 01:35:44 +00006578 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006579 else
John Wiegley01296292011-04-08 18:41:53 +00006580 rex = ImpCastExprToType(rex.take(), lType,
John McCalle84af4e2010-11-13 01:35:44 +00006581 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006582 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006583 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006584
Steve Naroff4b191572008-09-04 16:56:14 +00006585 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00006586 if (!isRelational && RHSIsNull
6587 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley01296292011-04-08 18:41:53 +00006588 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006589 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006590 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00006591 if (!isRelational && LHSIsNull
6592 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley01296292011-04-08 18:41:53 +00006593 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006594 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006595 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006596
Chris Lattner326f7572008-11-18 01:30:42 +00006597 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006598}
6599
Nate Begeman191a6b12008-07-14 18:02:46 +00006600/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006601/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006602/// like a scalar comparison, a vector comparison produces a vector of integer
6603/// types.
John Wiegley01296292011-04-08 18:41:53 +00006604QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner326f7572008-11-18 01:30:42 +00006605 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00006606 bool isRelational) {
6607 // Check to make sure we're operating on vectors of the same type and width,
6608 // Allowing one side to be a scalar of element type.
Eli Friedman1408bc92011-06-23 18:10:35 +00006609 QualType vType = CheckVectorOperands(lex, rex, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00006610 if (vType.isNull())
6611 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006612
John Wiegley01296292011-04-08 18:41:53 +00006613 QualType lType = lex.get()->getType();
6614 QualType rType = rex.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006615
Anton Yartsev530deb92011-03-27 15:36:07 +00006616 // If AltiVec, the comparison results in a numeric type, i.e.
6617 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00006618 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00006619 return Context.getLogicalOperationType();
6620
Nate Begeman191a6b12008-07-14 18:02:46 +00006621 // For non-floating point types, check for self-comparisons of the form
6622 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6623 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006624 if (!lType->hasFloatingRepresentation()) {
John Wiegley01296292011-04-08 18:41:53 +00006625 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
6626 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00006627 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00006628 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00006629 PDiag(diag::warn_comparison_always)
6630 << 0 // self-
6631 << 2 // "a constant"
6632 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006633 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006634
Nate Begeman191a6b12008-07-14 18:02:46 +00006635 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006636 if (!isRelational && lType->hasFloatingRepresentation()) {
6637 assert (rType->hasFloatingRepresentation());
John Wiegley01296292011-04-08 18:41:53 +00006638 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00006639 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006640
Nate Begeman191a6b12008-07-14 18:02:46 +00006641 // Return the type for the comparison, which is the same as vector type for
6642 // integer vectors, or an integer type of identical size and number of
6643 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006644 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00006645 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006646
John McCall9dd450b2009-09-21 23:43:11 +00006647 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006648 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006649 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006650 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006651 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006652 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6653
Mike Stump4e1f26a2009-02-19 03:04:26 +00006654 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006655 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006656 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6657}
6658
Steve Naroff218bc2b2007-05-04 21:54:46 +00006659inline QualType Sema::CheckBitwiseOperands(
John Wiegley01296292011-04-08 18:41:53 +00006660 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
Richard Trieucfc491d2011-08-02 04:35:43 +00006661 if (lex.get()->getType()->isVectorType() ||
6662 rex.get()->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00006663 if (lex.get()->getType()->hasIntegerRepresentation() &&
6664 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedman1408bc92011-06-23 18:10:35 +00006665 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006666
6667 return InvalidOperands(Loc, lex, rex);
6668 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006669
John Wiegley01296292011-04-08 18:41:53 +00006670 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
Richard Trieucfc491d2011-08-02 04:35:43 +00006671 QualType compType = UsualArithmeticConversions(lexResult, rexResult,
6672 isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00006673 if (lexResult.isInvalid() || rexResult.isInvalid())
6674 return QualType();
6675 lex = lexResult.take();
6676 rex = rexResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006677
John Wiegley01296292011-04-08 18:41:53 +00006678 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6679 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006680 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00006681 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006682}
6683
Steve Naroff218bc2b2007-05-04 21:54:46 +00006684inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley01296292011-04-08 18:41:53 +00006685 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00006686
6687 // Diagnose cases where the user write a logical and/or but probably meant a
6688 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6689 // is a constant.
Richard Trieucfc491d2011-08-02 04:35:43 +00006690 if (lex.get()->getType()->isIntegerType() &&
6691 !lex.get()->getType()->isBooleanType() &&
John Wiegley01296292011-04-08 18:41:53 +00006692 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00006693 // Don't warn in macros or template instantiations.
6694 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00006695 // If the RHS can be constant folded, and if it constant folds to something
6696 // that isn't 0 or 1 (which indicate a potential logical operation that
6697 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006698 // Parens on the RHS are ignored.
Chris Lattner938533d2010-07-24 01:10:11 +00006699 Expr::EvalResult Result;
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006700 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6701 if ((getLangOptions().Bool && !rex.get()->getType()->isBooleanType()) ||
6702 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6703 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6704 << rex.get()->getSourceRange()
6705 << (Opc == BO_LAnd ? "&&" : "||")
6706 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00006707 }
6708 }
Chris Lattner8406c512010-07-13 19:41:32 +00006709
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006710 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00006711 lex = UsualUnaryConversions(lex.take());
6712 if (lex.isInvalid())
6713 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006714
John Wiegley01296292011-04-08 18:41:53 +00006715 rex = UsualUnaryConversions(rex.take());
6716 if (rex.isInvalid())
6717 return QualType();
6718
Richard Trieucfc491d2011-08-02 04:35:43 +00006719 if (!lex.get()->getType()->isScalarType() ||
6720 !rex.get()->getType()->isScalarType())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006721 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006722
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006723 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006724 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006725
John McCall4a2429a2010-06-04 00:29:51 +00006726 // The following is safe because we only use this method for
6727 // non-overloadable operands.
6728
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006729 // C++ [expr.log.and]p1
6730 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006731 // The operands are both contextually converted to type bool.
John Wiegley01296292011-04-08 18:41:53 +00006732 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
6733 if (lexRes.isInvalid())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006734 return InvalidOperands(Loc, lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00006735 lex = move(lexRes);
6736
6737 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
6738 if (rexRes.isInvalid())
6739 return InvalidOperands(Loc, lex, rex);
6740 rex = move(rexRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006741
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006742 // C++ [expr.log.and]p2
6743 // C++ [expr.log.or]p2
6744 // The result is a bool.
6745 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006746}
6747
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006748/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6749/// is a read-only property; return true if so. A readonly property expression
6750/// depends on various declarations and thus must be treated specially.
6751///
Mike Stump11289f42009-09-09 15:08:12 +00006752static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006753 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6754 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00006755 if (PropExpr->isImplicitProperty()) return false;
6756
6757 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6758 QualType BaseType = PropExpr->isSuperReceiver() ?
6759 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00006760 PropExpr->getBase()->getType();
6761
John McCallb7bd14f2010-12-02 01:19:52 +00006762 if (const ObjCObjectPointerType *OPT =
6763 BaseType->getAsObjCInterfacePointerType())
6764 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6765 if (S.isPropertyReadonly(PDecl, IFace))
6766 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006767 }
6768 return false;
6769}
6770
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006771static bool IsConstProperty(Expr *E, Sema &S) {
6772 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6773 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6774 if (PropExpr->isImplicitProperty()) return false;
6775
6776 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6777 QualType T = PDecl->getType();
6778 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00006779 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006780 CanQualType CT = S.Context.getCanonicalType(T);
6781 return CT.isConstQualified();
6782 }
6783 return false;
6784}
6785
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006786static bool IsReadonlyMessage(Expr *E, Sema &S) {
6787 if (E->getStmtClass() != Expr::MemberExprClass)
6788 return false;
6789 const MemberExpr *ME = cast<MemberExpr>(E);
6790 NamedDecl *Member = ME->getMemberDecl();
6791 if (isa<FieldDecl>(Member)) {
6792 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
6793 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
6794 return false;
6795 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
6796 }
6797 return false;
6798}
6799
Chris Lattner30bd3272008-11-18 01:22:49 +00006800/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6801/// emit an error and return true. If so, return false.
6802static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006803 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00006804 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006805 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006806 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6807 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006808 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
6809 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006810 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
6811 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00006812 if (IsLV == Expr::MLV_Valid)
6813 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006814
Chris Lattner30bd3272008-11-18 01:22:49 +00006815 unsigned Diag = 0;
6816 bool NeedType = false;
6817 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00006818 case Expr::MLV_ConstQualified:
6819 Diag = diag::err_typecheck_assign_const;
6820
John McCalld4631322011-06-17 06:42:21 +00006821 // In ARC, use some specialized diagnostics for occasions where we
6822 // infer 'const'. These are always pseudo-strong variables.
John McCall31168b02011-06-15 23:02:42 +00006823 if (S.getLangOptions().ObjCAutoRefCount) {
6824 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
6825 if (declRef && isa<VarDecl>(declRef->getDecl())) {
6826 VarDecl *var = cast<VarDecl>(declRef->getDecl());
6827
John McCalld4631322011-06-17 06:42:21 +00006828 // Use the normal diagnostic if it's pseudo-__strong but the
6829 // user actually wrote 'const'.
6830 if (var->isARCPseudoStrong() &&
6831 (!var->getTypeSourceInfo() ||
6832 !var->getTypeSourceInfo()->getType().isConstQualified())) {
6833 // There are two pseudo-strong cases:
6834 // - self
John McCall31168b02011-06-15 23:02:42 +00006835 ObjCMethodDecl *method = S.getCurMethodDecl();
6836 if (method && var == method->getSelfDecl())
6837 Diag = diag::err_typecheck_arr_assign_self;
John McCalld4631322011-06-17 06:42:21 +00006838
6839 // - fast enumeration variables
6840 else
John McCall31168b02011-06-15 23:02:42 +00006841 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00006842
John McCall31168b02011-06-15 23:02:42 +00006843 SourceRange Assign;
6844 if (Loc != OrigLoc)
6845 Assign = SourceRange(OrigLoc, OrigLoc);
6846 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
6847 // We need to preserve the AST regardless, so migration tool
6848 // can do its job.
6849 return false;
6850 }
6851 }
6852 }
6853
6854 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006855 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006856 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6857 NeedType = true;
6858 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006859 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006860 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6861 NeedType = true;
6862 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00006863 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00006864 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6865 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006866 case Expr::MLV_Valid:
6867 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00006868 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006869 case Expr::MLV_MemberFunction:
6870 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00006871 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6872 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006873 case Expr::MLV_IncompleteType:
6874 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00006875 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006876 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00006877 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00006878 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00006879 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6880 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00006881 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00006882 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6883 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00006884 case Expr::MLV_ReadonlyProperty:
6885 Diag = diag::error_readonly_property_assignment;
6886 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00006887 case Expr::MLV_NoSetterProperty:
6888 Diag = diag::error_nosetter_property_assignment;
6889 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006890 case Expr::MLV_InvalidMessageExpression:
6891 Diag = diag::error_readonly_message_assignment;
6892 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00006893 case Expr::MLV_SubObjCPropertySetting:
6894 Diag = diag::error_no_subobject_property_setting;
6895 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006896 }
Steve Naroffad373bd2007-07-31 12:34:36 +00006897
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006898 SourceRange Assign;
6899 if (Loc != OrigLoc)
6900 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00006901 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006902 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006903 else
Mike Stump11289f42009-09-09 15:08:12 +00006904 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006905 return true;
6906}
6907
6908
6909
6910// C99 6.5.16.1
John Wiegley01296292011-04-08 18:41:53 +00006911QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00006912 SourceLocation Loc,
6913 QualType CompoundType) {
6914 // Verify that LHS is a modifiable lvalue, and emit error if not.
6915 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00006916 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00006917
6918 QualType LHSType = LHS->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00006919 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
6920 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006921 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00006922 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006923 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006924 // Simple assignment "x = y".
John Wiegley01296292011-04-08 18:41:53 +00006925 if (LHS->getObjectKind() == OK_ObjCProperty) {
6926 ExprResult LHSResult = Owned(LHS);
6927 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
6928 if (LHSResult.isInvalid())
6929 return QualType();
6930 LHS = LHSResult.take();
6931 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006932 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00006933 if (RHS.isInvalid())
6934 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006935 // Special case of NSObject attributes on c-style pointer types.
6936 if (ConvTy == IncompatiblePointer &&
6937 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006938 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006939 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006940 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006941 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006942
John McCall7decc9e2010-11-18 06:31:45 +00006943 if (ConvTy == Compatible &&
6944 getLangOptions().ObjCNonFragileABI &&
6945 LHSType->isObjCObjectType())
6946 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
6947 << LHSType;
6948
Chris Lattnerea714382008-08-21 18:04:13 +00006949 // If the RHS is a unary plus or minus, check to see if they = and + are
6950 // right next to each other. If so, the user may have typo'd "x =+ 4"
6951 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00006952 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00006953 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
6954 RHSCheck = ICE->getSubExpr();
6955 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00006956 if ((UO->getOpcode() == UO_Plus ||
6957 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00006958 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00006959 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00006960 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
6961 // And there is a space or other character before the subexpr of the
6962 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00006963 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
6964 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00006965 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00006966 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00006967 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00006968 }
Chris Lattnerea714382008-08-21 18:04:13 +00006969 }
John McCall31168b02011-06-15 23:02:42 +00006970
6971 if (ConvTy == Compatible) {
6972 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
6973 checkRetainCycles(LHS, RHS.get());
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006974 else if (getLangOptions().ObjCAutoRefCount)
6975 checkUnsafeExprAssigns(Loc, LHS, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00006976 }
Chris Lattnerea714382008-08-21 18:04:13 +00006977 } else {
6978 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00006979 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006980 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00006981
Chris Lattner326f7572008-11-18 01:30:42 +00006982 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00006983 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00006984 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006985
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +00006986 CheckForNullPointerDereference(*this, LHS);
Ted Kremenek64699be2011-02-16 01:57:07 +00006987 // Check for trivial buffer overflows.
Ted Kremenekdf26df72011-03-01 18:41:00 +00006988 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremenek64699be2011-02-16 01:57:07 +00006989
Steve Naroff98cf3e92007-06-06 18:38:38 +00006990 // C99 6.5.16p3: The type of an assignment expression is the type of the
6991 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00006992 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00006993 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
6994 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00006995 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00006996 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00006997 return (getLangOptions().CPlusPlus
6998 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00006999}
7000
Chris Lattner326f7572008-11-18 01:30:42 +00007001// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007002static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007003 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00007004 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007005
John McCall3aef3d82011-04-10 19:13:55 +00007006 LHS = S.CheckPlaceholderExpr(LHS.take());
7007 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007008 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007009 return QualType();
7010
John McCall73d36182010-10-12 07:14:40 +00007011 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7012 // operands, but not unary promotions.
7013 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007014
John McCall34376a62010-12-04 03:47:34 +00007015 // So we treat the LHS as a ignored value, and in C++ we allow the
7016 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007017 LHS = S.IgnoredValueConversions(LHS.take());
7018 if (LHS.isInvalid())
7019 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007020
7021 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007022 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7023 if (RHS.isInvalid())
7024 return QualType();
7025 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007026 S.RequireCompleteType(Loc, RHS.get()->getType(),
7027 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007028 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007029
John Wiegley01296292011-04-08 18:41:53 +00007030 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007031}
7032
Steve Naroff7a5af782007-07-13 16:58:59 +00007033/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7034/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007035static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7036 ExprValueKind &VK,
7037 SourceLocation OpLoc,
7038 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007039 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007040 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007041
Chris Lattner6b0cf142008-11-21 07:05:48 +00007042 QualType ResType = Op->getType();
7043 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007044
John McCall4bc41ae2010-11-18 19:01:18 +00007045 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007046 // Decrement of bool is not allowed.
7047 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007048 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007049 return QualType();
7050 }
7051 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007052 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007053 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007054 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007055 } else if (ResType->isAnyPointerType()) {
7056 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00007057
Chris Lattner6b0cf142008-11-21 07:05:48 +00007058 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007059 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007060 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007061
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007062 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00007063 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7064 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007065 << PointeeTy << Op->getSourceRange();
7066 return QualType();
7067 }
Eli Friedman090addd2010-01-03 00:20:48 +00007068 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007069 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007070 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007071 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007072 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007073 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007074 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007075 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7076 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007077 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7078 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007079 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007080 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00007081 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007082 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007083 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007084 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007085 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007086 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007087 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007088 // In C++, a prefix increment is the same type as the operand. Otherwise
7089 // (in C or with postfix), the increment is the unqualified type of the
7090 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00007091 if (isPrefix && S.getLangOptions().CPlusPlus) {
7092 VK = VK_LValue;
7093 return ResType;
7094 } else {
7095 VK = VK_RValue;
7096 return ResType.getUnqualifiedType();
7097 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007098}
7099
John Wiegley01296292011-04-08 18:41:53 +00007100ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00007101 assert(E->getValueKind() == VK_LValue &&
7102 E->getObjectKind() == OK_ObjCProperty);
7103 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7104
Douglas Gregor33823722011-06-11 01:09:30 +00007105 QualType T = E->getType();
7106 QualType ReceiverType;
7107 if (PRE->isObjectReceiver())
7108 ReceiverType = PRE->getBase()->getType();
7109 else if (PRE->isSuperReceiver())
7110 ReceiverType = PRE->getSuperReceiverType();
7111 else
7112 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
7113
John McCall34376a62010-12-04 03:47:34 +00007114 ExprValueKind VK = VK_RValue;
7115 if (PRE->isImplicitProperty()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007116 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007117 PRE->getImplicitPropertyGetter()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007118 T = getMessageSendResultType(ReceiverType, GetterMethod,
7119 PRE->isClassReceiver(),
7120 PRE->isSuperReceiver());
7121 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007122 }
7123 else {
7124 Diag(PRE->getLocation(), diag::err_getter_not_found)
7125 << PRE->getBase()->getType();
7126 }
John McCall34376a62010-12-04 03:47:34 +00007127 }
Douglas Gregor33823722011-06-11 01:09:30 +00007128
7129 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCall34376a62010-12-04 03:47:34 +00007130 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007131
7132 ExprResult Result = MaybeBindToTemporary(E);
7133 if (!Result.isInvalid())
7134 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00007135
7136 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00007137}
7138
Richard Trieucfc491d2011-08-02 04:35:43 +00007139void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
7140 QualType &LHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00007141 assert(LHS.get()->getValueKind() == VK_LValue &&
7142 LHS.get()->getObjectKind() == OK_ObjCProperty);
7143 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00007144
John McCall31168b02011-06-15 23:02:42 +00007145 bool Consumed = false;
7146
John Wiegley01296292011-04-08 18:41:53 +00007147 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00007148 // If using property-dot syntax notation for assignment, and there is a
7149 // setter, RHS expression is being passed to the setter argument. So,
7150 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00007151 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00007152 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7153 LHSTy = (*P)->getType();
John McCall31168b02011-06-15 23:02:42 +00007154 Consumed = (getLangOptions().ObjCAutoRefCount &&
7155 (*P)->hasAttr<NSConsumedAttr>());
John McCall34376a62010-12-04 03:47:34 +00007156
7157 // Otherwise, if the getter returns an l-value, just call that.
7158 } else {
John Wiegley01296292011-04-08 18:41:53 +00007159 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00007160 ExprValueKind VK = Expr::getValueKindForType(Result);
7161 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00007162 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7163 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00007164 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007165 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007166 }
John McCall31168b02011-06-15 23:02:42 +00007167 } else if (getLangOptions().ObjCAutoRefCount) {
7168 const ObjCMethodDecl *setter
7169 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7170 if (setter) {
7171 ObjCMethodDecl::param_iterator P = setter->param_begin();
7172 LHSTy = (*P)->getType();
7173 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7174 }
John McCall34376a62010-12-04 03:47:34 +00007175 }
7176
John McCall31168b02011-06-15 23:02:42 +00007177 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7178 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007179 InitializedEntity Entity =
John McCall31168b02011-06-15 23:02:42 +00007180 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley01296292011-04-08 18:41:53 +00007181 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCall31168b02011-06-15 23:02:42 +00007182 if (!ArgE.isInvalid()) {
John Wiegley01296292011-04-08 18:41:53 +00007183 RHS = ArgE;
John McCall31168b02011-06-15 23:02:42 +00007184 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7185 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7186 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007187 }
7188}
7189
7190
Anders Carlsson806700f2008-02-01 07:15:58 +00007191/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007192/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007193/// where the declaration is needed for type checking. We only need to
7194/// handle cases when the expression references a function designator
7195/// or is an lvalue. Here are some examples:
7196/// - &(x) => x
7197/// - &*****f => f for f a function designator.
7198/// - &s.xx => s
7199/// - &s.zz[1].yy -> s, if zz is an array
7200/// - *(x + 1) -> x, if x is an array
7201/// - &"123"[2] -> 0
7202/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007203static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007204 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007205 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007206 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007207 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007208 // If this is an arrow operator, the address is an offset from
7209 // the base's value, so the object the base refers to is
7210 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007211 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007212 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007213 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007214 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007215 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007216 // FIXME: This code shouldn't be necessary! We should catch the implicit
7217 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007218 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7219 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7220 if (ICE->getSubExpr()->getType()->isArrayType())
7221 return getPrimaryDecl(ICE->getSubExpr());
7222 }
7223 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007224 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007225 case Stmt::UnaryOperatorClass: {
7226 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007227
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007228 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007229 case UO_Real:
7230 case UO_Imag:
7231 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007232 return getPrimaryDecl(UO->getSubExpr());
7233 default:
7234 return 0;
7235 }
7236 }
Steve Naroff47500512007-04-19 23:00:49 +00007237 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007238 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007239 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007240 // If the result of an implicit cast is an l-value, we care about
7241 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007242 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007243 default:
7244 return 0;
7245 }
7246}
7247
7248/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007249/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007250/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007251/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007252/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007253/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007254/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007255static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7256 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007257 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007258 return S.Context.DependentTy;
7259 if (OrigOp->getType() == S.Context.OverloadTy)
7260 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00007261 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7262 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00007263 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7264 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7265 << OrigOp->getSourceRange();
7266 return QualType();
7267 }
John McCall8d08b9b2010-08-27 09:08:28 +00007268
John McCall2979fe02011-04-12 00:42:48 +00007269 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007270
John McCall8d08b9b2010-08-27 09:08:28 +00007271 // Make sure to ignore parentheses in subsequent checks
7272 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007273
John McCall4bc41ae2010-11-18 19:01:18 +00007274 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007275 // Implement C99-only parts of addressof rules.
7276 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007277 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007278 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7279 // (assuming the deref expression is valid).
7280 return uOp->getSubExpr()->getType();
7281 }
7282 // Technically, there should be a check for array subscript
7283 // expressions here, but the result of one is always an lvalue anyway.
7284 }
John McCallf3a88602011-02-03 08:15:49 +00007285 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007286 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007287
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007288 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007289 bool sfinae = S.isSFINAEContext();
7290 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7291 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007292 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007293 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007294 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007295 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007296 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007297 } else if (lval == Expr::LV_MemberFunction) {
7298 // If it's an instance method, make a member pointer.
7299 // The expression must have exactly the form &A::foo.
7300
7301 // If the underlying expression isn't a decl ref, give up.
7302 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007303 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007304 << OrigOp->getSourceRange();
7305 return QualType();
7306 }
7307 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7308 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7309
7310 // The id-expression was parenthesized.
7311 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007312 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007313 << OrigOp->getSourceRange();
7314
7315 // The method was named without a qualifier.
7316 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007317 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007318 << op->getSourceRange();
7319 }
7320
John McCall4bc41ae2010-11-18 19:01:18 +00007321 return S.Context.getMemberPointerType(op->getType(),
7322 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007323 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007324 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007325 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007326 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007327 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007328 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007329 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007330 return QualType();
7331 }
John McCall086a4642010-11-24 05:12:34 +00007332 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007333 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00007334 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00007335 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00007336 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007337 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007338 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00007339 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00007340 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007341 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007342 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007343 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00007344 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00007345 << "property expression" << op->getSourceRange();
7346 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007347 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007348 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007349 // with the register storage-class specifier.
7350 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007351 // in C++ it is not error to take address of a register
7352 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007353 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007354 !S.getLangOptions().CPlusPlus) {
7355 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00007356 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007357 return QualType();
7358 }
John McCalld14a8642009-11-21 08:51:07 +00007359 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007360 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007361 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007362 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007363 // Could be a pointer to member, though, if there is an explicit
7364 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007365 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007366 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007367 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007368 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007369 S.Diag(OpLoc,
7370 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007371 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007372 return QualType();
7373 }
Mike Stump11289f42009-09-09 15:08:12 +00007374
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007375 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7376 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007377 return S.Context.getMemberPointerType(op->getType(),
7378 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007379 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007380 }
Anders Carlsson5b535762009-05-16 21:43:42 +00007381 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00007382 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007383 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007384
Eli Friedmance7f9002009-05-16 23:27:50 +00007385 if (lval == Expr::LV_IncompleteVoidType) {
7386 // Taking the address of a void variable is technically illegal, but we
7387 // allow it in cases which are otherwise valid.
7388 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007389 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007390 }
7391
Steve Naroff47500512007-04-19 23:00:49 +00007392 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007393 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007394 return S.Context.getObjCObjectPointerType(op->getType());
7395 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007396}
7397
Chris Lattner9156f1b2010-07-05 19:17:26 +00007398/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007399static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7400 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007401 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007402 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007403
John Wiegley01296292011-04-08 18:41:53 +00007404 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7405 if (ConvResult.isInvalid())
7406 return QualType();
7407 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007408 QualType OpTy = Op->getType();
7409 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007410
7411 if (isa<CXXReinterpretCastExpr>(Op)) {
7412 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7413 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7414 Op->getSourceRange());
7415 }
7416
Chris Lattner9156f1b2010-07-05 19:17:26 +00007417 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7418 // is an incomplete type or void. It would be possible to warn about
7419 // dereferencing a void pointer, but it's completely well-defined, and such a
7420 // warning is unlikely to catch any mistakes.
7421 if (const PointerType *PT = OpTy->getAs<PointerType>())
7422 Result = PT->getPointeeType();
7423 else if (const ObjCObjectPointerType *OPT =
7424 OpTy->getAs<ObjCObjectPointerType>())
7425 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007426 else {
John McCall3aef3d82011-04-10 19:13:55 +00007427 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007428 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007429 if (PR.take() != Op)
7430 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007431 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007432
Chris Lattner9156f1b2010-07-05 19:17:26 +00007433 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007434 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007435 << OpTy << Op->getSourceRange();
7436 return QualType();
7437 }
John McCall4bc41ae2010-11-18 19:01:18 +00007438
7439 // Dereferences are usually l-values...
7440 VK = VK_LValue;
7441
7442 // ...except that certain expressions are never l-values in C.
Douglas Gregor5476205b2011-06-23 00:49:38 +00007443 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007444 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007445
7446 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007447}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007448
John McCalle3027922010-08-25 11:45:40 +00007449static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007450 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007451 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007452 switch (Kind) {
7453 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007454 case tok::periodstar: Opc = BO_PtrMemD; break;
7455 case tok::arrowstar: Opc = BO_PtrMemI; break;
7456 case tok::star: Opc = BO_Mul; break;
7457 case tok::slash: Opc = BO_Div; break;
7458 case tok::percent: Opc = BO_Rem; break;
7459 case tok::plus: Opc = BO_Add; break;
7460 case tok::minus: Opc = BO_Sub; break;
7461 case tok::lessless: Opc = BO_Shl; break;
7462 case tok::greatergreater: Opc = BO_Shr; break;
7463 case tok::lessequal: Opc = BO_LE; break;
7464 case tok::less: Opc = BO_LT; break;
7465 case tok::greaterequal: Opc = BO_GE; break;
7466 case tok::greater: Opc = BO_GT; break;
7467 case tok::exclaimequal: Opc = BO_NE; break;
7468 case tok::equalequal: Opc = BO_EQ; break;
7469 case tok::amp: Opc = BO_And; break;
7470 case tok::caret: Opc = BO_Xor; break;
7471 case tok::pipe: Opc = BO_Or; break;
7472 case tok::ampamp: Opc = BO_LAnd; break;
7473 case tok::pipepipe: Opc = BO_LOr; break;
7474 case tok::equal: Opc = BO_Assign; break;
7475 case tok::starequal: Opc = BO_MulAssign; break;
7476 case tok::slashequal: Opc = BO_DivAssign; break;
7477 case tok::percentequal: Opc = BO_RemAssign; break;
7478 case tok::plusequal: Opc = BO_AddAssign; break;
7479 case tok::minusequal: Opc = BO_SubAssign; break;
7480 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7481 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7482 case tok::ampequal: Opc = BO_AndAssign; break;
7483 case tok::caretequal: Opc = BO_XorAssign; break;
7484 case tok::pipeequal: Opc = BO_OrAssign; break;
7485 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007486 }
7487 return Opc;
7488}
7489
John McCalle3027922010-08-25 11:45:40 +00007490static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007491 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007492 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007493 switch (Kind) {
7494 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007495 case tok::plusplus: Opc = UO_PreInc; break;
7496 case tok::minusminus: Opc = UO_PreDec; break;
7497 case tok::amp: Opc = UO_AddrOf; break;
7498 case tok::star: Opc = UO_Deref; break;
7499 case tok::plus: Opc = UO_Plus; break;
7500 case tok::minus: Opc = UO_Minus; break;
7501 case tok::tilde: Opc = UO_Not; break;
7502 case tok::exclaim: Opc = UO_LNot; break;
7503 case tok::kw___real: Opc = UO_Real; break;
7504 case tok::kw___imag: Opc = UO_Imag; break;
7505 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007506 }
7507 return Opc;
7508}
7509
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007510/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7511/// This warning is only emitted for builtin assignment operations. It is also
7512/// suppressed in the event of macro expansions.
7513static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7514 SourceLocation OpLoc) {
7515 if (!S.ActiveTemplateInstantiations.empty())
7516 return;
7517 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7518 return;
7519 lhs = lhs->IgnoreParenImpCasts();
7520 rhs = rhs->IgnoreParenImpCasts();
7521 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7522 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7523 if (!LeftDeclRef || !RightDeclRef ||
7524 LeftDeclRef->getLocation().isMacroID() ||
7525 RightDeclRef->getLocation().isMacroID())
7526 return;
7527 const ValueDecl *LeftDecl =
7528 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7529 const ValueDecl *RightDecl =
7530 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7531 if (LeftDecl != RightDecl)
7532 return;
7533 if (LeftDecl->getType().isVolatileQualified())
7534 return;
7535 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7536 if (RefTy->getPointeeType().isVolatileQualified())
7537 return;
7538
7539 S.Diag(OpLoc, diag::warn_self_assignment)
7540 << LeftDeclRef->getType()
7541 << lhs->getSourceRange() << rhs->getSourceRange();
7542}
7543
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007544/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7545/// operator @p Opc at location @c TokLoc. This routine only supports
7546/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007547ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007548 BinaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00007549 Expr *lhsExpr, Expr *rhsExpr) {
7550 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007551 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007552 // The following two variables are used for compound assignment operators
7553 QualType CompLHSTy; // Type of LHS after promotions for computation
7554 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007555 ExprValueKind VK = VK_RValue;
7556 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007557
Douglas Gregor1beec452011-03-12 01:48:56 +00007558 // Check if a 'foo<int>' involved in a binary op, identifies a single
7559 // function unambiguously (i.e. an lvalue ala 13.4)
7560 // But since an assignment can trigger target based overload, exclude it in
7561 // our blind search. i.e:
7562 // template<class T> void f(); template<class T, class U> void f(U);
7563 // f<int> == 0; // resolve f<int> blindly
7564 // void (*p)(int); p = f<int>; // resolve f<int> using target
7565 if (Opc != BO_Assign) {
John McCall3aef3d82011-04-10 19:13:55 +00007566 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall31996342011-04-07 08:22:57 +00007567 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007568 lhs = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00007569
John McCall3aef3d82011-04-10 19:13:55 +00007570 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall31996342011-04-07 08:22:57 +00007571 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007572 rhs = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00007573 }
7574
Eli Friedman8e6f5a62011-06-17 20:52:22 +00007575 // The canonical way to check for a GNU null is with isNullPointerConstant,
7576 // but we use a bit of a hack here for speed; this is a relatively
7577 // hot path, and isNullPointerConstant is slow.
7578 bool LeftNull = isa<GNUNullExpr>(lhs.get()->IgnoreParenImpCasts());
7579 bool RightNull = isa<GNUNullExpr>(rhs.get()->IgnoreParenImpCasts());
Richard Trieu701fb362011-06-16 21:36:56 +00007580
7581 // Detect when a NULL constant is used improperly in an expression. These
7582 // are mainly cases where the null pointer is used as an integer instead
7583 // of a pointer.
7584 if (LeftNull || RightNull) {
Chandler Carruth4f04b432011-06-20 07:38:51 +00007585 // Avoid analyzing cases where the result will either be invalid (and
7586 // diagnosed as such) or entirely valid and not something to warn about.
7587 QualType LeftType = lhs.get()->getType();
7588 QualType RightType = rhs.get()->getType();
7589 if (!LeftType->isBlockPointerType() && !LeftType->isMemberPointerType() &&
7590 !LeftType->isFunctionType() &&
7591 !RightType->isBlockPointerType() &&
7592 !RightType->isMemberPointerType() &&
7593 !RightType->isFunctionType()) {
7594 if (Opc == BO_Mul || Opc == BO_Div || Opc == BO_Rem || Opc == BO_Add ||
7595 Opc == BO_Sub || Opc == BO_Shl || Opc == BO_Shr || Opc == BO_And ||
7596 Opc == BO_Xor || Opc == BO_Or || Opc == BO_MulAssign ||
7597 Opc == BO_DivAssign || Opc == BO_AddAssign || Opc == BO_SubAssign ||
7598 Opc == BO_RemAssign || Opc == BO_ShlAssign || Opc == BO_ShrAssign ||
7599 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign) {
7600 // These are the operations that would not make sense with a null pointer
Richard Trieucfc491d2011-08-02 04:35:43 +00007601 // pointer no matter what the other expression is.
Chandler Carruthe1db1cf2011-06-19 09:05:14 +00007602 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
Chandler Carruth4f04b432011-06-20 07:38:51 +00007603 << (LeftNull ? lhs.get()->getSourceRange() : SourceRange())
7604 << (RightNull ? rhs.get()->getSourceRange() : SourceRange());
7605 } else if (Opc == BO_LE || Opc == BO_LT || Opc == BO_GE || Opc == BO_GT ||
7606 Opc == BO_EQ || Opc == BO_NE) {
7607 // These are the operations that would not make sense with a null pointer
7608 // if the other expression the other expression is not a pointer.
7609 if (LeftNull != RightNull &&
7610 !LeftType->isAnyPointerType() &&
7611 !LeftType->canDecayToPointerType() &&
7612 !RightType->isAnyPointerType() &&
7613 !RightType->canDecayToPointerType()) {
7614 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
7615 << (LeftNull ? lhs.get()->getSourceRange()
7616 : rhs.get()->getSourceRange());
7617 }
Richard Trieu701fb362011-06-16 21:36:56 +00007618 }
7619 }
7620 }
7621
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007622 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007623 case BO_Assign:
John Wiegley01296292011-04-08 18:41:53 +00007624 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007625 if (getLangOptions().CPlusPlus &&
John Wiegley01296292011-04-08 18:41:53 +00007626 lhs.get()->getObjectKind() != OK_ObjCProperty) {
7627 VK = lhs.get()->getValueKind();
7628 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007629 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007630 if (!ResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00007631 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007632 break;
John McCalle3027922010-08-25 11:45:40 +00007633 case BO_PtrMemD:
7634 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00007635 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007636 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007637 break;
John McCalle3027922010-08-25 11:45:40 +00007638 case BO_Mul:
7639 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007640 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007641 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007642 break;
John McCalle3027922010-08-25 11:45:40 +00007643 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007644 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7645 break;
John McCalle3027922010-08-25 11:45:40 +00007646 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007647 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7648 break;
John McCalle3027922010-08-25 11:45:40 +00007649 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007650 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7651 break;
John McCalle3027922010-08-25 11:45:40 +00007652 case BO_Shl:
7653 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007654 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007655 break;
John McCalle3027922010-08-25 11:45:40 +00007656 case BO_LE:
7657 case BO_LT:
7658 case BO_GE:
7659 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007660 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007661 break;
John McCalle3027922010-08-25 11:45:40 +00007662 case BO_EQ:
7663 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007664 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007665 break;
John McCalle3027922010-08-25 11:45:40 +00007666 case BO_And:
7667 case BO_Xor:
7668 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007669 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7670 break;
John McCalle3027922010-08-25 11:45:40 +00007671 case BO_LAnd:
7672 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00007673 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007674 break;
John McCalle3027922010-08-25 11:45:40 +00007675 case BO_MulAssign:
7676 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007677 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007678 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007679 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007680 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7681 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007682 break;
John McCalle3027922010-08-25 11:45:40 +00007683 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007684 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7685 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007686 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7687 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007688 break;
John McCalle3027922010-08-25 11:45:40 +00007689 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007690 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007691 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7692 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007693 break;
John McCalle3027922010-08-25 11:45:40 +00007694 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007695 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007696 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7697 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007698 break;
John McCalle3027922010-08-25 11:45:40 +00007699 case BO_ShlAssign:
7700 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007701 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007702 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007703 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7704 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007705 break;
John McCalle3027922010-08-25 11:45:40 +00007706 case BO_AndAssign:
7707 case BO_XorAssign:
7708 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007709 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7710 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007711 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7712 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007713 break;
John McCalle3027922010-08-25 11:45:40 +00007714 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00007715 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00007716 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
7717 VK = rhs.get()->getValueKind();
7718 OK = rhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007719 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007720 break;
7721 }
John Wiegley01296292011-04-08 18:41:53 +00007722 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007723 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007724 if (CompResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00007725 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
7726 ResultTy, VK, OK, OpLoc));
Richard Trieucfc491d2011-08-02 04:35:43 +00007727 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() !=
7728 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007729 VK = VK_LValue;
John Wiegley01296292011-04-08 18:41:53 +00007730 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007731 }
John Wiegley01296292011-04-08 18:41:53 +00007732 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
7733 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00007734 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007735}
7736
Sebastian Redl44615072009-10-27 12:10:02 +00007737/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7738/// operators are mixed in a way that suggests that the programmer forgot that
7739/// comparison operators have higher precedence. The most typical example of
7740/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007741static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007742 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00007743 typedef BinaryOperator BinOp;
7744 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7745 rhsopc = static_cast<BinOp::Opcode>(-1);
7746 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007747 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00007748 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007749 rhsopc = BO->getOpcode();
7750
7751 // Subs are not binary operators.
7752 if (lhsopc == -1 && rhsopc == -1)
7753 return;
7754
7755 // Bitwise operations are sometimes used as eager logical ops.
7756 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00007757 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7758 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007759 return;
7760
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007761 if (BinOp::isComparisonOp(lhsopc)) {
7762 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7763 << SourceRange(lhs->getLocStart(), OpLoc)
7764 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc);
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007765 SuggestParentheses(Self, OpLoc,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007766 Self.PDiag(diag::note_precedence_bitwise_silence)
7767 << BinOp::getOpcodeStr(lhsopc),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007768 lhs->getSourceRange());
7769 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00007770 Self.PDiag(diag::note_precedence_bitwise_first)
7771 << BinOp::getOpcodeStr(Opc),
7772 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007773 } else if (BinOp::isComparisonOp(rhsopc)) {
7774 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7775 << SourceRange(OpLoc, rhs->getLocEnd())
7776 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc);
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007777 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00007778 Self.PDiag(diag::note_precedence_bitwise_silence)
7779 << BinOp::getOpcodeStr(rhsopc),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007780 rhs->getSourceRange());
7781 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007782 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007783 << BinOp::getOpcodeStr(Opc),
Douglas Gregorbb9a5e62011-06-22 18:41:08 +00007784 SourceRange(lhs->getLocStart(),
7785 cast<BinOp>(rhs)->getLHS()->getLocStart()));
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007786 }
Sebastian Redl43028242009-10-26 15:24:15 +00007787}
7788
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007789/// \brief It accepts a '&' expr that is inside a '|' one.
7790/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7791/// in parentheses.
7792static void
7793EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7794 BinaryOperator *Bop) {
7795 assert(Bop->getOpcode() == BO_And);
7796 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7797 << Bop->getSourceRange() << OpLoc;
7798 SuggestParentheses(Self, Bop->getOperatorLoc(),
7799 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7800 Bop->getSourceRange());
7801}
7802
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007803/// \brief It accepts a '&&' expr that is inside a '||' one.
7804/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7805/// in parentheses.
7806static void
7807EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007808 BinaryOperator *Bop) {
7809 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007810 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7811 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007812 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007813 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007814 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007815}
7816
7817/// \brief Returns true if the given expression can be evaluated as a constant
7818/// 'true'.
7819static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7820 bool Res;
7821 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7822}
7823
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007824/// \brief Returns true if the given expression can be evaluated as a constant
7825/// 'false'.
7826static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7827 bool Res;
7828 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7829}
7830
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007831/// \brief Look for '&&' in the left hand of a '||' expr.
7832static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007833 Expr *OrLHS, Expr *OrRHS) {
7834 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007835 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007836 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7837 if (EvaluatesAsFalse(S, OrRHS))
7838 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007839 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7840 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7841 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7842 } else if (Bop->getOpcode() == BO_LOr) {
7843 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7844 // If it's "a || b && 1 || c" we didn't warn earlier for
7845 // "a || b && 1", but warn now.
7846 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7847 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7848 }
7849 }
7850 }
7851}
7852
7853/// \brief Look for '&&' in the right hand of a '||' expr.
7854static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007855 Expr *OrLHS, Expr *OrRHS) {
7856 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007857 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007858 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7859 if (EvaluatesAsFalse(S, OrLHS))
7860 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007861 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7862 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7863 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007864 }
7865 }
7866}
7867
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007868/// \brief Look for '&' in the left or right hand of a '|' expr.
7869static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7870 Expr *OrArg) {
7871 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7872 if (Bop->getOpcode() == BO_And)
7873 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7874 }
7875}
7876
Sebastian Redl43028242009-10-26 15:24:15 +00007877/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007878/// precedence.
John McCalle3027922010-08-25 11:45:40 +00007879static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007880 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007881 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00007882 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007883 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7884
7885 // Diagnose "arg1 & arg2 | arg3"
7886 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7887 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, lhs);
7888 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, rhs);
7889 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007890
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007891 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7892 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00007893 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007894 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7895 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007896 }
Sebastian Redl43028242009-10-26 15:24:15 +00007897}
7898
Steve Naroff218bc2b2007-05-04 21:54:46 +00007899// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007900ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00007901 tok::TokenKind Kind,
7902 Expr *lhs, Expr *rhs) {
7903 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00007904 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
7905 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00007906
Sebastian Redl43028242009-10-26 15:24:15 +00007907 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7908 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
7909
Douglas Gregor5287f092009-11-05 00:51:44 +00007910 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
7911}
7912
John McCalldadc5752010-08-24 06:29:42 +00007913ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007914 BinaryOperatorKind Opc,
7915 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00007916 if (getLangOptions().CPlusPlus) {
7917 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007918
John McCall622114c2010-12-06 05:26:58 +00007919 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
7920 UseBuiltinOperator = false;
7921 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
7922 UseBuiltinOperator = true;
7923 } else {
7924 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
7925 !rhs->getType()->isOverloadableType();
7926 }
7927
7928 if (!UseBuiltinOperator) {
7929 // Find all of the overloaded operators visible from this
7930 // point. We perform both an operator-name lookup from the local
7931 // scope and an argument-dependent lookup based on the types of
7932 // the arguments.
7933 UnresolvedSet<16> Functions;
7934 OverloadedOperatorKind OverOp
7935 = BinaryOperator::getOverloadedOperator(Opc);
7936 if (S && OverOp != OO_None)
7937 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
7938 Functions);
7939
7940 // Build the (potentially-overloaded, potentially-dependent)
7941 // binary operation.
7942 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
7943 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00007944 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007945
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007946 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00007947 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00007948}
7949
John McCalldadc5752010-08-24 06:29:42 +00007950ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007951 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00007952 Expr *InputExpr) {
7953 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00007954 ExprValueKind VK = VK_RValue;
7955 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00007956 QualType resultType;
7957 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007958 case UO_PreInc:
7959 case UO_PreDec:
7960 case UO_PostInc:
7961 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00007962 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007963 Opc == UO_PreInc ||
7964 Opc == UO_PostInc,
7965 Opc == UO_PreInc ||
7966 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00007967 break;
John McCalle3027922010-08-25 11:45:40 +00007968 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00007969 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007970 break;
John McCall31996342011-04-07 08:22:57 +00007971 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00007972 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00007973 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007974 Input = move(resolved);
7975 Input = DefaultFunctionArrayLvalueConversion(Input.take());
7976 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007977 break;
John McCall31996342011-04-07 08:22:57 +00007978 }
John McCalle3027922010-08-25 11:45:40 +00007979 case UO_Plus:
7980 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00007981 Input = UsualUnaryConversions(Input.take());
7982 if (Input.isInvalid()) return ExprError();
7983 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007984 if (resultType->isDependentType())
7985 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00007986 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
7987 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00007988 break;
7989 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
7990 resultType->isEnumeralType())
7991 break;
7992 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00007993 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00007994 resultType->isPointerType())
7995 break;
John McCall36226622010-10-12 02:09:17 +00007996 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007997 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00007998 if (Input.isInvalid()) return ExprError();
7999 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008000 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008001
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008002 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008003 << resultType << Input.get()->getSourceRange());
8004
John McCalle3027922010-08-25 11:45:40 +00008005 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008006 Input = UsualUnaryConversions(Input.take());
8007 if (Input.isInvalid()) return ExprError();
8008 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008009 if (resultType->isDependentType())
8010 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008011 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8012 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8013 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008014 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008015 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008016 else if (resultType->hasIntegerRepresentation())
8017 break;
8018 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008019 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008020 if (Input.isInvalid()) return ExprError();
8021 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008022 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008023 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008024 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008025 }
Steve Naroff35d85152007-05-07 00:24:15 +00008026 break;
John Wiegley01296292011-04-08 18:41:53 +00008027
John McCalle3027922010-08-25 11:45:40 +00008028 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008029 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008030 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8031 if (Input.isInvalid()) return ExprError();
8032 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008033 if (resultType->isDependentType())
8034 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008035 if (resultType->isScalarType()) {
8036 // C99 6.5.3.3p1: ok, fallthrough;
8037 if (Context.getLangOptions().CPlusPlus) {
8038 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8039 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008040 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8041 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008042 }
John McCall36226622010-10-12 02:09:17 +00008043 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008044 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008045 if (Input.isInvalid()) return ExprError();
8046 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008047 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008048 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008049 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008050 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008051
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008052 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008053 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008054 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008055 break;
John McCalle3027922010-08-25 11:45:40 +00008056 case UO_Real:
8057 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008058 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008059 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00008060 if (Input.isInvalid()) return ExprError();
8061 if (Input.get()->getValueKind() != VK_RValue &&
8062 Input.get()->getObjectKind() == OK_Ordinary)
8063 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008064 break;
John McCalle3027922010-08-25 11:45:40 +00008065 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008066 resultType = Input.get()->getType();
8067 VK = Input.get()->getValueKind();
8068 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008069 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008070 }
John Wiegley01296292011-04-08 18:41:53 +00008071 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008072 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008073
John Wiegley01296292011-04-08 18:41:53 +00008074 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008075 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008076}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008077
John McCalldadc5752010-08-24 06:29:42 +00008078ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008079 UnaryOperatorKind Opc,
8080 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008081 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008082 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008083 // Find all of the overloaded operators visible from this
8084 // point. We perform both an operator-name lookup from the local
8085 // scope and an argument-dependent lookup based on the types of
8086 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008087 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008088 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008089 if (S && OverOp != OO_None)
8090 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8091 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008092
John McCallb268a282010-08-23 23:25:46 +00008093 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008094 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008095
John McCallb268a282010-08-23 23:25:46 +00008096 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008097}
8098
Douglas Gregor5287f092009-11-05 00:51:44 +00008099// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008100ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008101 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008102 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008103}
8104
Steve Naroff66356bd2007-09-16 14:56:35 +00008105/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008106ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008107 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008108 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008109 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008110 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008111 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008112}
8113
John McCall31168b02011-06-15 23:02:42 +00008114/// Given the last statement in a statement-expression, check whether
8115/// the result is a producing expression (like a call to an
8116/// ns_returns_retained function) and, if so, rebuild it to hoist the
8117/// release out of the full-expression. Otherwise, return null.
8118/// Cannot fail.
8119static Expr *maybeRebuildARCConsumingStmt(Stmt *s) {
8120 // Should always be wrapped with one of these.
8121 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(s);
8122 if (!cleanups) return 0;
8123
8124 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
8125 if (!cast || cast->getCastKind() != CK_ObjCConsumeObject)
8126 return 0;
8127
8128 // Splice out the cast. This shouldn't modify any interesting
8129 // features of the statement.
8130 Expr *producer = cast->getSubExpr();
8131 assert(producer->getType() == cast->getType());
8132 assert(producer->getValueKind() == cast->getValueKind());
8133 cleanups->setSubExpr(producer);
8134 return cleanups;
8135}
8136
John McCalldadc5752010-08-24 06:29:42 +00008137ExprResult
John McCallb268a282010-08-23 23:25:46 +00008138Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008139 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008140 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8141 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8142
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008143 bool isFileScope
8144 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008145 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008146 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008147
Chris Lattner366727f2007-07-24 16:58:17 +00008148 // FIXME: there are a variety of strange constraints to enforce here, for
8149 // example, it is not possible to goto into a stmt expression apparently.
8150 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008151
Chris Lattner366727f2007-07-24 16:58:17 +00008152 // If there are sub stmts in the compound stmt, take the type of the last one
8153 // as the type of the stmtexpr.
8154 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008155 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008156 if (!Compound->body_empty()) {
8157 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008158 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008159 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008160 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8161 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008162 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008163 }
John McCall31168b02011-06-15 23:02:42 +00008164
John Wiegley01296292011-04-08 18:41:53 +00008165 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008166 // Do function/array conversion on the last expression, but not
8167 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008168 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8169 if (LastExpr.isInvalid())
8170 return ExprError();
8171 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008172
John Wiegley01296292011-04-08 18:41:53 +00008173 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008174 // In ARC, if the final expression ends in a consume, splice
8175 // the consume out and bind it later. In the alternate case
8176 // (when dealing with a retainable type), the result
8177 // initialization will create a produce. In both cases the
8178 // result will be +1, and we'll need to balance that out with
8179 // a bind.
8180 if (Expr *rebuiltLastStmt
8181 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8182 LastExpr = rebuiltLastStmt;
8183 } else {
8184 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008185 InitializedEntity::InitializeResult(LPLoc,
8186 Ty,
8187 false),
8188 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008189 LastExpr);
8190 }
8191
John Wiegley01296292011-04-08 18:41:53 +00008192 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008193 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008194 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008195 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008196 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008197 else
John Wiegley01296292011-04-08 18:41:53 +00008198 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008199 StmtExprMayBindToTemp = true;
8200 }
8201 }
8202 }
Chris Lattner944d3062008-07-26 19:51:01 +00008203 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008204
Eli Friedmanba961a92009-03-23 00:24:07 +00008205 // FIXME: Check that expression type is complete/non-abstract; statement
8206 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008207 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8208 if (StmtExprMayBindToTemp)
8209 return MaybeBindToTemporary(ResStmtExpr);
8210 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008211}
Steve Naroff78864672007-08-01 22:05:33 +00008212
John McCalldadc5752010-08-24 06:29:42 +00008213ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008214 TypeSourceInfo *TInfo,
8215 OffsetOfComponent *CompPtr,
8216 unsigned NumComponents,
8217 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008218 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008219 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008220 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008221
Chris Lattnerf17bd422007-08-30 17:45:32 +00008222 // We must have at least one component that refers to the type, and the first
8223 // one is known to be a field designator. Verify that the ArgTy represents
8224 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008225 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008226 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8227 << ArgTy << TypeRange);
8228
8229 // Type must be complete per C99 7.17p3 because a declaring a variable
8230 // with an incomplete type would be ill-formed.
8231 if (!Dependent
8232 && RequireCompleteType(BuiltinLoc, ArgTy,
8233 PDiag(diag::err_offsetof_incomplete_type)
8234 << TypeRange))
8235 return ExprError();
8236
Chris Lattner78502cf2007-08-31 21:49:13 +00008237 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8238 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008239 // FIXME: This diagnostic isn't actually visible because the location is in
8240 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008241 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008242 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8243 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008244
8245 bool DidWarnAboutNonPOD = false;
8246 QualType CurrentType = ArgTy;
8247 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008248 SmallVector<OffsetOfNode, 4> Comps;
8249 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008250 for (unsigned i = 0; i != NumComponents; ++i) {
8251 const OffsetOfComponent &OC = CompPtr[i];
8252 if (OC.isBrackets) {
8253 // Offset of an array sub-field. TODO: Should we allow vector elements?
8254 if (!CurrentType->isDependentType()) {
8255 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8256 if(!AT)
8257 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8258 << CurrentType);
8259 CurrentType = AT->getElementType();
8260 } else
8261 CurrentType = Context.DependentTy;
8262
8263 // The expression must be an integral expression.
8264 // FIXME: An integral constant expression?
8265 Expr *Idx = static_cast<Expr*>(OC.U.E);
8266 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8267 !Idx->getType()->isIntegerType())
8268 return ExprError(Diag(Idx->getLocStart(),
8269 diag::err_typecheck_subscript_not_integer)
8270 << Idx->getSourceRange());
8271
8272 // Record this array index.
8273 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8274 Exprs.push_back(Idx);
8275 continue;
8276 }
8277
8278 // Offset of a field.
8279 if (CurrentType->isDependentType()) {
8280 // We have the offset of a field, but we can't look into the dependent
8281 // type. Just record the identifier of the field.
8282 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8283 CurrentType = Context.DependentTy;
8284 continue;
8285 }
8286
8287 // We need to have a complete type to look into.
8288 if (RequireCompleteType(OC.LocStart, CurrentType,
8289 diag::err_offsetof_incomplete_type))
8290 return ExprError();
8291
8292 // Look for the designated field.
8293 const RecordType *RC = CurrentType->getAs<RecordType>();
8294 if (!RC)
8295 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8296 << CurrentType);
8297 RecordDecl *RD = RC->getDecl();
8298
8299 // C++ [lib.support.types]p5:
8300 // The macro offsetof accepts a restricted set of type arguments in this
8301 // International Standard. type shall be a POD structure or a POD union
8302 // (clause 9).
8303 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8304 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008305 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008306 PDiag(diag::warn_offsetof_non_pod_type)
8307 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8308 << CurrentType))
8309 DidWarnAboutNonPOD = true;
8310 }
8311
8312 // Look for the field.
8313 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8314 LookupQualifiedName(R, RD);
8315 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008316 IndirectFieldDecl *IndirectMemberDecl = 0;
8317 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008318 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008319 MemberDecl = IndirectMemberDecl->getAnonField();
8320 }
8321
Douglas Gregor882211c2010-04-28 22:16:22 +00008322 if (!MemberDecl)
8323 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8324 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8325 OC.LocEnd));
8326
Douglas Gregor10982ea2010-04-28 22:36:06 +00008327 // C99 7.17p3:
8328 // (If the specified member is a bit-field, the behavior is undefined.)
8329 //
8330 // We diagnose this as an error.
8331 if (MemberDecl->getBitWidth()) {
8332 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8333 << MemberDecl->getDeclName()
8334 << SourceRange(BuiltinLoc, RParenLoc);
8335 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8336 return ExprError();
8337 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008338
8339 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008340 if (IndirectMemberDecl)
8341 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008342
Douglas Gregord1702062010-04-29 00:18:15 +00008343 // If the member was found in a base class, introduce OffsetOfNodes for
8344 // the base class indirections.
8345 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8346 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008347 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008348 CXXBasePath &Path = Paths.front();
8349 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8350 B != BEnd; ++B)
8351 Comps.push_back(OffsetOfNode(B->Base));
8352 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008353
Francois Pichet783dd6e2010-11-21 06:08:52 +00008354 if (IndirectMemberDecl) {
8355 for (IndirectFieldDecl::chain_iterator FI =
8356 IndirectMemberDecl->chain_begin(),
8357 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8358 assert(isa<FieldDecl>(*FI));
8359 Comps.push_back(OffsetOfNode(OC.LocStart,
8360 cast<FieldDecl>(*FI), OC.LocEnd));
8361 }
8362 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008363 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008364
Douglas Gregor882211c2010-04-28 22:16:22 +00008365 CurrentType = MemberDecl->getType().getNonReferenceType();
8366 }
8367
8368 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8369 TInfo, Comps.data(), Comps.size(),
8370 Exprs.data(), Exprs.size(), RParenLoc));
8371}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008372
John McCalldadc5752010-08-24 06:29:42 +00008373ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008374 SourceLocation BuiltinLoc,
8375 SourceLocation TypeLoc,
8376 ParsedType argty,
8377 OffsetOfComponent *CompPtr,
8378 unsigned NumComponents,
8379 SourceLocation RPLoc) {
8380
Douglas Gregor882211c2010-04-28 22:16:22 +00008381 TypeSourceInfo *ArgTInfo;
8382 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8383 if (ArgTy.isNull())
8384 return ExprError();
8385
Eli Friedman06dcfd92010-08-05 10:15:45 +00008386 if (!ArgTInfo)
8387 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8388
8389 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8390 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008391}
8392
8393
John McCalldadc5752010-08-24 06:29:42 +00008394ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008395 Expr *CondExpr,
8396 Expr *LHSExpr, Expr *RHSExpr,
8397 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008398 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8399
John McCall7decc9e2010-11-18 06:31:45 +00008400 ExprValueKind VK = VK_RValue;
8401 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008402 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008403 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008404 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008405 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008406 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008407 } else {
8408 // The conditional expression is required to be a constant expression.
8409 llvm::APSInt condEval(32);
8410 SourceLocation ExpLoc;
8411 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008412 return ExprError(Diag(ExpLoc,
8413 diag::err_typecheck_choose_expr_requires_constant)
8414 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008415
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008416 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008417 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8418
8419 resType = ActiveExpr->getType();
8420 ValueDependent = ActiveExpr->isValueDependent();
8421 VK = ActiveExpr->getValueKind();
8422 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008423 }
8424
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008425 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008426 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008427 resType->isDependentType(),
8428 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008429}
8430
Steve Naroffc540d662008-09-03 18:15:37 +00008431//===----------------------------------------------------------------------===//
8432// Clang Extensions.
8433//===----------------------------------------------------------------------===//
8434
8435/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008436void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008437 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8438 PushBlockScope(BlockScope, Block);
8439 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008440 if (BlockScope)
8441 PushDeclContext(BlockScope, Block);
8442 else
8443 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008444}
8445
Mike Stump82f071f2009-02-04 22:31:32 +00008446void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008447 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008448 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008449 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008450
John McCall8cb7bdf2010-06-04 23:28:52 +00008451 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008452 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008453
John McCall3882ace2011-01-05 12:14:39 +00008454 // GetTypeForDeclarator always produces a function type for a block
8455 // literal signature. Furthermore, it is always a FunctionProtoType
8456 // unless the function was written with a typedef.
8457 assert(T->isFunctionType() &&
8458 "GetTypeForDeclarator made a non-function block signature");
8459
8460 // Look for an explicit signature in that function type.
8461 FunctionProtoTypeLoc ExplicitSignature;
8462
8463 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8464 if (isa<FunctionProtoTypeLoc>(tmp)) {
8465 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8466
8467 // Check whether that explicit signature was synthesized by
8468 // GetTypeForDeclarator. If so, don't save that as part of the
8469 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008470 if (ExplicitSignature.getLocalRangeBegin() ==
8471 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008472 // This would be much cheaper if we stored TypeLocs instead of
8473 // TypeSourceInfos.
8474 TypeLoc Result = ExplicitSignature.getResultLoc();
8475 unsigned Size = Result.getFullDataSize();
8476 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8477 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8478
8479 ExplicitSignature = FunctionProtoTypeLoc();
8480 }
John McCalla3ccba02010-06-04 11:21:44 +00008481 }
Mike Stump11289f42009-09-09 15:08:12 +00008482
John McCall3882ace2011-01-05 12:14:39 +00008483 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8484 CurBlock->FunctionType = T;
8485
8486 const FunctionType *Fn = T->getAs<FunctionType>();
8487 QualType RetTy = Fn->getResultType();
8488 bool isVariadic =
8489 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8490
John McCall8e346702010-06-04 19:02:56 +00008491 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008492
John McCalla3ccba02010-06-04 11:21:44 +00008493 // Don't allow returning a objc interface by value.
8494 if (RetTy->isObjCObjectType()) {
8495 Diag(ParamInfo.getSourceRange().getBegin(),
8496 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8497 return;
8498 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008499
John McCalla3ccba02010-06-04 11:21:44 +00008500 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008501 // return type. TODO: what should we do with declarators like:
8502 // ^ * { ... }
8503 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008504 if (RetTy != Context.DependentTy)
8505 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008506
John McCalla3ccba02010-06-04 11:21:44 +00008507 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008508 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008509 if (ExplicitSignature) {
8510 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8511 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008512 if (Param->getIdentifier() == 0 &&
8513 !Param->isImplicit() &&
8514 !Param->isInvalidDecl() &&
8515 !getLangOptions().CPlusPlus)
8516 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008517 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008518 }
John McCalla3ccba02010-06-04 11:21:44 +00008519
8520 // Fake up parameter variables if we have a typedef, like
8521 // ^ fntype { ... }
8522 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8523 for (FunctionProtoType::arg_type_iterator
8524 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8525 ParmVarDecl *Param =
8526 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8527 ParamInfo.getSourceRange().getBegin(),
8528 *I);
John McCall8e346702010-06-04 19:02:56 +00008529 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008530 }
Steve Naroffc540d662008-09-03 18:15:37 +00008531 }
John McCalla3ccba02010-06-04 11:21:44 +00008532
John McCall8e346702010-06-04 19:02:56 +00008533 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008534 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00008535 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00008536 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8537 CurBlock->TheDecl->param_end(),
8538 /*CheckParameterNames=*/false);
8539 }
8540
John McCalla3ccba02010-06-04 11:21:44 +00008541 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008542 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008543
John McCall8e346702010-06-04 19:02:56 +00008544 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008545 Diag(ParamInfo.getAttributes()->getLoc(),
8546 diag::warn_attribute_sentinel_not_variadic) << 1;
8547 // FIXME: remove the attribute.
8548 }
8549
8550 // Put the parameter variables in scope. We can bail out immediately
8551 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008552 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008553 return;
8554
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008555 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008556 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8557 (*AI)->setOwningFunction(CurBlock->TheDecl);
8558
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008559 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008560 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008561 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008562
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008563 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008564 }
John McCallf7b2fb52010-01-22 00:28:27 +00008565 }
Steve Naroffc540d662008-09-03 18:15:37 +00008566}
8567
8568/// ActOnBlockError - If there is an error parsing a block, this callback
8569/// is invoked to pop the information about the block from the action impl.
8570void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008571 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008572 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008573 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008574}
8575
8576/// ActOnBlockStmtExpr - This is called when the body of a block statement
8577/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008578ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008579 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008580 // If blocks are disabled, emit an error.
8581 if (!LangOpts.Blocks)
8582 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008583
Douglas Gregor9a28e842010-03-01 23:15:13 +00008584 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008585
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008586 PopDeclContext();
8587
Steve Naroffc540d662008-09-03 18:15:37 +00008588 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008589 if (!BSI->ReturnType.isNull())
8590 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008591
Mike Stump3bf1ab42009-07-28 22:04:01 +00008592 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008593 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008594
John McCallc63de662011-02-02 13:00:07 +00008595 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008596 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8597 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00008598
John McCall8e346702010-06-04 19:02:56 +00008599 // If the user wrote a function type in some form, try to use that.
8600 if (!BSI->FunctionType.isNull()) {
8601 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8602
8603 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8604 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8605
8606 // Turn protoless block types into nullary block types.
8607 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008608 FunctionProtoType::ExtProtoInfo EPI;
8609 EPI.ExtInfo = Ext;
8610 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008611
8612 // Otherwise, if we don't need to change anything about the function type,
8613 // preserve its sugar structure.
8614 } else if (FTy->getResultType() == RetTy &&
8615 (!NoReturn || FTy->getNoReturnAttr())) {
8616 BlockTy = BSI->FunctionType;
8617
8618 // Otherwise, make the minimal modifications to the function type.
8619 } else {
8620 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008621 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8622 EPI.TypeQuals = 0; // FIXME: silently?
8623 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008624 BlockTy = Context.getFunctionType(RetTy,
8625 FPT->arg_type_begin(),
8626 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008627 EPI);
John McCall8e346702010-06-04 19:02:56 +00008628 }
8629
8630 // If we don't have a function type, just build one from nothing.
8631 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008632 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00008633 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008634 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008635 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008636
John McCall8e346702010-06-04 19:02:56 +00008637 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8638 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008639 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008640
Chris Lattner45542ea2009-04-19 05:28:12 +00008641 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00008642 if (getCurFunction()->NeedsScopeChecking() &&
8643 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008644 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008645
Chris Lattner60f84492011-02-17 23:58:47 +00008646 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008647
Fariborz Jahanian256d39d2011-07-11 18:04:54 +00008648 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8649 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8650 const VarDecl *variable = ci->getVariable();
8651 QualType T = variable->getType();
8652 QualType::DestructionKind destructKind = T.isDestructedType();
8653 if (destructKind != QualType::DK_none)
8654 getCurFunction()->setHasBranchProtectedScope();
8655 }
8656
Benjamin Kramera4fb8362011-07-12 14:11:05 +00008657 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8658 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8659 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8660
Douglas Gregor9a28e842010-03-01 23:15:13 +00008661 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008662}
8663
John McCalldadc5752010-08-24 06:29:42 +00008664ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00008665 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008666 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008667 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00008668 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00008669 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008670}
8671
John McCalldadc5752010-08-24 06:29:42 +00008672ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008673 Expr *E, TypeSourceInfo *TInfo,
8674 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008675 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008676
Eli Friedman121ba0c2008-08-09 23:32:40 +00008677 // Get the va_list type
8678 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008679 if (VaListType->isArrayType()) {
8680 // Deal with implicit array decay; for example, on x86-64,
8681 // va_list is an array, but it's supposed to decay to
8682 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008683 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008684 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00008685 ExprResult Result = UsualUnaryConversions(E);
8686 if (Result.isInvalid())
8687 return ExprError();
8688 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00008689 } else {
8690 // Otherwise, the va_list argument must be an l-value because
8691 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008692 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008693 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008694 return ExprError();
8695 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008696
Douglas Gregorad3150c2009-05-19 23:10:31 +00008697 if (!E->isTypeDependent() &&
8698 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008699 return ExprError(Diag(E->getLocStart(),
8700 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008701 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008702 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008703
David Majnemerc75d1a12011-06-14 05:17:32 +00008704 if (!TInfo->getType()->isDependentType()) {
8705 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8706 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8707 << TInfo->getTypeLoc().getSourceRange()))
8708 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00008709
David Majnemerc75d1a12011-06-14 05:17:32 +00008710 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8711 TInfo->getType(),
8712 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8713 << TInfo->getTypeLoc().getSourceRange()))
8714 return ExprError();
8715
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008716 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00008717 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008718 TInfo->getType()->isObjCLifetimeType()
8719 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8720 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00008721 << TInfo->getType()
8722 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008723 }
Eli Friedman6290ae42011-07-11 21:45:59 +00008724
8725 // Check for va_arg where arguments of the given type will be promoted
8726 // (i.e. this va_arg is guaranteed to have undefined behavior).
8727 QualType PromoteType;
8728 if (TInfo->getType()->isPromotableIntegerType()) {
8729 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8730 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8731 PromoteType = QualType();
8732 }
8733 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8734 PromoteType = Context.DoubleTy;
8735 if (!PromoteType.isNull())
8736 Diag(TInfo->getTypeLoc().getBeginLoc(),
8737 diag::warn_second_parameter_to_va_arg_never_compatible)
8738 << TInfo->getType()
8739 << PromoteType
8740 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00008741 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008742
Abramo Bagnara27db2392010-08-10 10:06:15 +00008743 QualType T = TInfo->getType().getNonLValueExprType(Context);
8744 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008745}
8746
John McCalldadc5752010-08-24 06:29:42 +00008747ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008748 // The type of __null will be int or long, depending on the size of
8749 // pointers on the target.
8750 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008751 unsigned pw = Context.Target.getPointerWidth(0);
8752 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008753 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008754 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008755 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008756 else if (pw == Context.Target.getLongLongWidth())
8757 Ty = Context.LongLongTy;
8758 else {
8759 assert(!"I don't know size of pointer!");
8760 Ty = Context.IntTy;
8761 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00008762
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008763 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008764}
8765
Alexis Huntc46382e2010-04-28 23:02:27 +00008766static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008767 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008768 if (!SemaRef.getLangOptions().ObjC1)
8769 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008770
Anders Carlssonace5d072009-11-10 04:46:30 +00008771 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8772 if (!PT)
8773 return;
8774
8775 // Check if the destination is of type 'id'.
8776 if (!PT->isObjCIdType()) {
8777 // Check if the destination is the 'NSString' interface.
8778 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8779 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8780 return;
8781 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008782
Anders Carlssonace5d072009-11-10 04:46:30 +00008783 // Strip off any parens and casts.
8784 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregorfb65e592011-07-27 05:40:30 +00008785 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00008786 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008787
Douglas Gregora771f462010-03-31 17:46:05 +00008788 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00008789}
8790
Chris Lattner9bad62c2008-01-04 18:04:52 +00008791bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8792 SourceLocation Loc,
8793 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008794 Expr *SrcExpr, AssignmentAction Action,
8795 bool *Complained) {
8796 if (Complained)
8797 *Complained = false;
8798
Chris Lattner9bad62c2008-01-04 18:04:52 +00008799 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00008800 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008801 bool isInvalid = false;
8802 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00008803 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00008804 ConversionFixItGenerator ConvHints;
8805 bool MayHaveConvFixit = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008806
Chris Lattner9bad62c2008-01-04 18:04:52 +00008807 switch (ConvTy) {
8808 default: assert(0 && "Unknown conversion type");
8809 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008810 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00008811 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00008812 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8813 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008814 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008815 case IntToPointer:
8816 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00008817 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8818 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008819 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008820 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00008821 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00008822 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00008823 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
8824 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00008825 if (Hint.isNull() && !CheckInferredResultType) {
8826 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8827 }
8828 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008829 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00008830 case IncompatiblePointerSign:
8831 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8832 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008833 case FunctionVoidPointer:
8834 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8835 break;
John McCall4fff8f62011-02-01 00:10:29 +00008836 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00008837 // Perform array-to-pointer decay if necessary.
8838 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8839
John McCall4fff8f62011-02-01 00:10:29 +00008840 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8841 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8842 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8843 DiagKind = diag::err_typecheck_incompatible_address_space;
8844 break;
John McCall31168b02011-06-15 23:02:42 +00008845
8846
8847 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008848 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00008849 break;
John McCall4fff8f62011-02-01 00:10:29 +00008850 }
8851
8852 llvm_unreachable("unknown error case for discarding qualifiers!");
8853 // fallthrough
8854 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00008855 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008856 // If the qualifiers lost were because we were applying the
8857 // (deprecated) C++ conversion from a string literal to a char*
8858 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8859 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00008860 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008861 // bit of refactoring (so that the second argument is an
8862 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00008863 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008864 // C++ semantics.
8865 if (getLangOptions().CPlusPlus &&
8866 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8867 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008868 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8869 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00008870 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00008871 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00008872 break;
Steve Naroff081c7422008-09-04 15:10:53 +00008873 case IntToBlockPointer:
8874 DiagKind = diag::err_int_to_block_pointer;
8875 break;
8876 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00008877 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00008878 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00008879 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00008880 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00008881 // it can give a more specific diagnostic.
8882 DiagKind = diag::warn_incompatible_qualified_id;
8883 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00008884 case IncompatibleVectors:
8885 DiagKind = diag::warn_incompatible_vectors;
8886 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00008887 case IncompatibleObjCWeakRef:
8888 DiagKind = diag::err_arc_weak_unavailable_assign;
8889 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008890 case Incompatible:
8891 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00008892 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8893 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008894 isInvalid = true;
8895 break;
8896 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008897
Douglas Gregorc68e1402010-04-09 00:35:39 +00008898 QualType FirstType, SecondType;
8899 switch (Action) {
8900 case AA_Assigning:
8901 case AA_Initializing:
8902 // The destination type comes first.
8903 FirstType = DstType;
8904 SecondType = SrcType;
8905 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00008906
Douglas Gregorc68e1402010-04-09 00:35:39 +00008907 case AA_Returning:
8908 case AA_Passing:
8909 case AA_Converting:
8910 case AA_Sending:
8911 case AA_Casting:
8912 // The source type comes first.
8913 FirstType = SrcType;
8914 SecondType = DstType;
8915 break;
8916 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008917
Anna Zaks3b402712011-07-28 19:51:27 +00008918 PartialDiagnostic FDiag = PDiag(DiagKind);
8919 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
8920
8921 // If we can fix the conversion, suggest the FixIts.
8922 assert(ConvHints.isNull() || Hint.isNull());
8923 if (!ConvHints.isNull()) {
8924 for (llvm::SmallVector<FixItHint, 1>::iterator
8925 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
8926 HI != HE; ++HI)
8927 FDiag << *HI;
8928 } else {
8929 FDiag << Hint;
8930 }
8931 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
8932
8933 Diag(Loc, FDiag);
8934
Douglas Gregor33823722011-06-11 01:09:30 +00008935 if (CheckInferredResultType)
8936 EmitRelatedResultTypeNote(SrcExpr);
8937
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008938 if (Complained)
8939 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008940 return isInvalid;
8941}
Anders Carlssone54e8a12008-11-30 19:50:32 +00008942
Chris Lattnerc71d08b2009-04-25 21:59:05 +00008943bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008944 llvm::APSInt ICEResult;
8945 if (E->isIntegerConstantExpr(ICEResult, Context)) {
8946 if (Result)
8947 *Result = ICEResult;
8948 return false;
8949 }
8950
Anders Carlssone54e8a12008-11-30 19:50:32 +00008951 Expr::EvalResult EvalResult;
8952
Mike Stump4e1f26a2009-02-19 03:04:26 +00008953 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00008954 EvalResult.HasSideEffects) {
8955 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
8956
8957 if (EvalResult.Diag) {
8958 // We only show the note if it's not the usual "invalid subexpression"
8959 // or if it's actually in a subexpression.
8960 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
8961 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
8962 Diag(EvalResult.DiagLoc, EvalResult.Diag);
8963 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008964
Anders Carlssone54e8a12008-11-30 19:50:32 +00008965 return true;
8966 }
8967
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008968 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
8969 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00008970
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008971 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008972 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
8973 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008974 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008975
Anders Carlssone54e8a12008-11-30 19:50:32 +00008976 if (Result)
8977 *Result = EvalResult.Val.getInt();
8978 return false;
8979}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008980
Douglas Gregorff790f12009-11-26 00:44:06 +00008981void
Mike Stump11289f42009-09-09 15:08:12 +00008982Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00008983 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00008984 ExpressionEvaluationContextRecord(NewContext,
8985 ExprTemporaries.size(),
8986 ExprNeedsCleanups));
8987 ExprNeedsCleanups = false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008988}
8989
Richard Trieucfc491d2011-08-02 04:35:43 +00008990void Sema::PopExpressionEvaluationContext() {
Douglas Gregorff790f12009-11-26 00:44:06 +00008991 // Pop the current expression evaluation context off the stack.
8992 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
8993 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00008994
Douglas Gregorfab31f42009-12-12 07:57:52 +00008995 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
8996 if (Rec.PotentiallyReferenced) {
8997 // Mark any remaining declarations in the current position of the stack
8998 // as "referenced". If they were not meant to be referenced, semantic
8999 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009000 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009001 I = Rec.PotentiallyReferenced->begin(),
9002 IEnd = Rec.PotentiallyReferenced->end();
9003 I != IEnd; ++I)
9004 MarkDeclarationReferenced(I->first, I->second);
9005 }
9006
9007 if (Rec.PotentiallyDiagnosed) {
9008 // Emit any pending diagnostics.
9009 for (PotentiallyEmittedDiagnostics::iterator
9010 I = Rec.PotentiallyDiagnosed->begin(),
9011 IEnd = Rec.PotentiallyDiagnosed->end();
9012 I != IEnd; ++I)
9013 Diag(I->first, I->second);
9014 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009015 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009016
9017 // When are coming out of an unevaluated context, clear out any
9018 // temporaries that we may have created as part of the evaluation of
9019 // the expression in that context: they aren't relevant because they
9020 // will never be constructed.
John McCall31168b02011-06-15 23:02:42 +00009021 if (Rec.Context == Unevaluated) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009022 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9023 ExprTemporaries.end());
John McCall31168b02011-06-15 23:02:42 +00009024 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9025
9026 // Otherwise, merge the contexts together.
9027 } else {
9028 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9029 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009030
9031 // Destroy the popped expression evaluation record.
9032 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009033}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009034
John McCall31168b02011-06-15 23:02:42 +00009035void Sema::DiscardCleanupsInEvaluationContext() {
9036 ExprTemporaries.erase(
9037 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
9038 ExprTemporaries.end());
9039 ExprNeedsCleanups = false;
9040}
9041
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009042/// \brief Note that the given declaration was referenced in the source code.
9043///
9044/// This routine should be invoke whenever a given declaration is referenced
9045/// in the source code, and where that reference occurred. If this declaration
9046/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9047/// C99 6.9p3), then the declaration will be marked as used.
9048///
9049/// \param Loc the location where the declaration was referenced.
9050///
9051/// \param D the declaration that has been referenced by the source code.
9052void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9053 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009054
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00009055 D->setReferenced();
9056
Douglas Gregorebada0772010-06-17 23:14:26 +00009057 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009058 return;
Mike Stump11289f42009-09-09 15:08:12 +00009059
Richard Trieucfc491d2011-08-02 04:35:43 +00009060 // Mark a parameter or variable declaration "used", regardless of whether
9061 // we're in a template or not. The reason for this is that unevaluated
9062 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9063 // (-Wunused-variables and -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009064 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009065 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009066 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009067 return;
9068 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009069
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009070 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9071 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009072
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009073 // Do not mark anything as "used" within a dependent context; wait for
9074 // an instantiation.
9075 if (CurContext->isDependentContext())
9076 return;
Mike Stump11289f42009-09-09 15:08:12 +00009077
Douglas Gregorff790f12009-11-26 00:44:06 +00009078 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009079 case Unevaluated:
9080 // We are in an expression that is not potentially evaluated; do nothing.
9081 return;
Mike Stump11289f42009-09-09 15:08:12 +00009082
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009083 case PotentiallyEvaluated:
9084 // We are in a potentially-evaluated expression, so this declaration is
9085 // "used"; handle this below.
9086 break;
Mike Stump11289f42009-09-09 15:08:12 +00009087
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009088 case PotentiallyPotentiallyEvaluated:
9089 // We are in an expression that may be potentially evaluated; queue this
9090 // declaration reference until we know whether the expression is
9091 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009092 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009093 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009094
9095 case PotentiallyEvaluatedIfUsed:
9096 // Referenced declarations will only be used if the construct in the
9097 // containing expression is used.
9098 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009099 }
Mike Stump11289f42009-09-09 15:08:12 +00009100
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009101 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009102 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Alexis Huntf92197c2011-05-12 03:51:51 +00009103 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor()) {
9104 if (Constructor->isTrivial())
Chandler Carruthc9262402010-08-23 07:55:51 +00009105 return;
9106 if (!Constructor->isUsed(false))
9107 DefineImplicitDefaultConstructor(Loc, Constructor);
Alexis Hunt22b5b132011-05-14 18:20:50 +00009108 } else if (Constructor->isDefaulted() &&
Alexis Hunt913820d2011-05-13 06:10:58 +00009109 Constructor->isCopyConstructor()) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009110 if (!Constructor->isUsed(false))
Alexis Hunt913820d2011-05-13 06:10:58 +00009111 DefineImplicitCopyConstructor(Loc, Constructor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009112 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009113
Douglas Gregor88d292c2010-05-13 16:44:06 +00009114 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009115 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Alexis Huntf91729462011-05-12 22:46:25 +00009116 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009117 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009118 if (Destructor->isVirtual())
9119 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009120 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Alexis Huntc9a55732011-05-14 05:23:28 +00009121 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009122 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009123 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00009124 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009125 } else if (MethodDecl->isVirtual())
9126 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009127 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009128 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009129 // Recursive functions should be marked when used from another function.
9130 if (CurContext == Function) return;
9131
Mike Stump11289f42009-09-09 15:08:12 +00009132 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009133 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009134 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009135 bool AlreadyInstantiated = false;
9136 if (FunctionTemplateSpecializationInfo *SpecInfo
9137 = Function->getTemplateSpecializationInfo()) {
9138 if (SpecInfo->getPointOfInstantiation().isInvalid())
9139 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009140 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009141 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009142 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009143 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009144 = Function->getMemberSpecializationInfo()) {
9145 if (MSInfo->getPointOfInstantiation().isInvalid())
9146 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009147 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009148 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009149 AlreadyInstantiated = true;
9150 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009151
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009152 if (!AlreadyInstantiated) {
9153 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9154 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9155 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9156 Loc));
9157 else
Chandler Carruth54080172010-08-25 08:44:16 +00009158 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009159 }
John McCall83779672011-02-19 02:53:41 +00009160 } else {
9161 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009162 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9163 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009164 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009165 MarkDeclarationReferenced(Loc, *i);
9166 }
John McCall83779672011-02-19 02:53:41 +00009167 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009168
John McCall83779672011-02-19 02:53:41 +00009169 // Keep track of used but undefined functions.
9170 if (!Function->isPure() && !Function->hasBody() &&
9171 Function->getLinkage() != ExternalLinkage) {
9172 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9173 if (old.isInvalid()) old = Loc;
9174 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009175
John McCall83779672011-02-19 02:53:41 +00009176 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009177 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009178 }
Mike Stump11289f42009-09-09 15:08:12 +00009179
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009180 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009181 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009182 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009183 Var->getInstantiatedFromStaticDataMember()) {
9184 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9185 assert(MSInfo && "Missing member specialization information?");
9186 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9187 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9188 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redl2ac2c722011-04-29 08:19:30 +00009189 // This is a modification of an existing AST node. Notify listeners.
9190 if (ASTMutationListener *L = getASTMutationListener())
9191 L->StaticDataMemberInstantiated(Var);
Chandler Carruth54080172010-08-25 08:44:16 +00009192 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009193 }
9194 }
Mike Stump11289f42009-09-09 15:08:12 +00009195
John McCall15dd4042011-02-21 19:25:48 +00009196 // Keep track of used but undefined variables. We make a hole in
9197 // the warning for static const data members with in-line
9198 // initializers.
John McCall83779672011-02-19 02:53:41 +00009199 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009200 && Var->getLinkage() != ExternalLinkage
9201 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009202 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9203 if (old.isInvalid()) old = Loc;
9204 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009205
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009206 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009207 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009208 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009209}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009210
Douglas Gregor5597ab42010-05-07 23:12:07 +00009211namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009212 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009213 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009214 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009215 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9216 Sema &S;
9217 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009218
Douglas Gregor5597ab42010-05-07 23:12:07 +00009219 public:
9220 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009221
Douglas Gregor5597ab42010-05-07 23:12:07 +00009222 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009223
9224 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9225 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009226 };
9227}
9228
Chandler Carruthaf80f662010-06-09 08:17:30 +00009229bool MarkReferencedDecls::TraverseTemplateArgument(
9230 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009231 if (Arg.getKind() == TemplateArgument::Declaration) {
9232 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9233 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009234
9235 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009236}
9237
Chandler Carruthaf80f662010-06-09 08:17:30 +00009238bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009239 if (ClassTemplateSpecializationDecl *Spec
9240 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9241 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009242 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009243 }
9244
Chandler Carruthc65667c2010-06-10 10:31:57 +00009245 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009246}
9247
9248void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9249 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009250 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009251}
9252
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009253namespace {
9254 /// \brief Helper class that marks all of the declarations referenced by
9255 /// potentially-evaluated subexpressions as "referenced".
9256 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9257 Sema &S;
9258
9259 public:
9260 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9261
9262 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9263
9264 void VisitDeclRefExpr(DeclRefExpr *E) {
9265 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9266 }
9267
9268 void VisitMemberExpr(MemberExpr *E) {
9269 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009270 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009271 }
9272
9273 void VisitCXXNewExpr(CXXNewExpr *E) {
9274 if (E->getConstructor())
9275 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9276 if (E->getOperatorNew())
9277 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9278 if (E->getOperatorDelete())
9279 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009280 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009281 }
9282
9283 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9284 if (E->getOperatorDelete())
9285 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009286 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9287 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9288 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9289 S.MarkDeclarationReferenced(E->getLocStart(),
9290 S.LookupDestructor(Record));
9291 }
9292
Douglas Gregor32b3de52010-09-11 23:32:50 +00009293 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009294 }
9295
9296 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9297 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009298 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009299 }
9300
9301 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9302 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9303 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009304
9305 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9306 Visit(E->getExpr());
9307 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009308 };
9309}
9310
9311/// \brief Mark any declarations that appear within this expression or any
9312/// potentially-evaluated subexpressions as "referenced".
9313void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9314 EvaluatedExprMarker(*this).Visit(E);
9315}
9316
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009317/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9318/// of the program being compiled.
9319///
9320/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009321/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009322/// possibility that the code will actually be executable. Code in sizeof()
9323/// expressions, code used only during overload resolution, etc., are not
9324/// potentially evaluated. This routine will suppress such diagnostics or,
9325/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009326/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009327/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009328///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009329/// This routine should be used for all diagnostics that describe the run-time
9330/// behavior of a program, such as passing a non-POD value through an ellipsis.
9331/// Failure to do so will likely result in spurious diagnostics or failures
9332/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +00009333bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009334 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +00009335 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009336 case Unevaluated:
9337 // The argument will never be evaluated, so don't complain.
9338 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009339
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009340 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009341 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +00009342 if (stmt && getCurFunctionOrMethodDecl()) {
9343 FunctionScopes.back()->PossiblyUnreachableDiags.
9344 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9345 }
9346 else
9347 Diag(Loc, PD);
9348
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009349 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009350
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009351 case PotentiallyPotentiallyEvaluated:
9352 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9353 break;
9354 }
9355
9356 return false;
9357}
9358
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009359bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9360 CallExpr *CE, FunctionDecl *FD) {
9361 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9362 return false;
9363
9364 PartialDiagnostic Note =
9365 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9366 << FD->getDeclName() : PDiag();
9367 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009368
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009369 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009370 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009371 PDiag(diag::err_call_function_incomplete_return)
9372 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009373 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009374 << CE->getSourceRange(),
9375 std::make_pair(NoteLoc, Note)))
9376 return true;
9377
9378 return false;
9379}
9380
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009381// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009382// will prevent this condition from triggering, which is what we want.
9383void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9384 SourceLocation Loc;
9385
John McCall0506e4a2009-11-11 02:41:58 +00009386 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009387 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009388
John McCalld5707ab2009-10-12 21:59:07 +00009389 if (isa<BinaryOperator>(E)) {
9390 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009391 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009392 return;
9393
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009394 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9395
John McCallb0e419e2009-11-12 00:06:05 +00009396 // Greylist some idioms by putting them into a warning subcategory.
9397 if (ObjCMessageExpr *ME
9398 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9399 Selector Sel = ME->getSelector();
9400
John McCallb0e419e2009-11-12 00:06:05 +00009401 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009402 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009403 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9404
9405 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009406 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009407 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9408 }
John McCall0506e4a2009-11-11 02:41:58 +00009409
John McCalld5707ab2009-10-12 21:59:07 +00009410 Loc = Op->getOperatorLoc();
9411 } else if (isa<CXXOperatorCallExpr>(E)) {
9412 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009413 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009414 return;
9415
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009416 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009417 Loc = Op->getOperatorLoc();
9418 } else {
9419 // Not an assignment.
9420 return;
9421 }
9422
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009423 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009424
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009425 SourceLocation Open = E->getSourceRange().getBegin();
9426 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9427 Diag(Loc, diag::note_condition_assign_silence)
9428 << FixItHint::CreateInsertion(Open, "(")
9429 << FixItHint::CreateInsertion(Close, ")");
9430
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009431 if (IsOrAssign)
9432 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9433 << FixItHint::CreateReplacement(Loc, "!=");
9434 else
9435 Diag(Loc, diag::note_condition_assign_to_comparison)
9436 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00009437}
9438
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009439/// \brief Redundant parentheses over an equality comparison can indicate
9440/// that the user intended an assignment used as condition.
9441void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009442 // Don't warn if the parens came from a macro.
9443 SourceLocation parenLoc = parenE->getLocStart();
9444 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9445 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009446 // Don't warn for dependent expressions.
9447 if (parenE->isTypeDependent())
9448 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009449
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009450 Expr *E = parenE->IgnoreParens();
9451
9452 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009453 if (opE->getOpcode() == BO_EQ &&
9454 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9455 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009456 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009457
Ted Kremenekae022092011-02-02 02:20:30 +00009458 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +00009459 Diag(Loc, diag::note_equality_comparison_silence)
9460 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9461 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009462 Diag(Loc, diag::note_equality_comparison_to_assign)
9463 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009464 }
9465}
9466
John Wiegley01296292011-04-08 18:41:53 +00009467ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +00009468 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009469 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9470 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009471
John McCall0009fcc2011-04-26 20:42:42 +00009472 ExprResult result = CheckPlaceholderExpr(E);
9473 if (result.isInvalid()) return ExprError();
9474 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009475
John McCall0009fcc2011-04-26 20:42:42 +00009476 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +00009477 if (getLangOptions().CPlusPlus)
9478 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9479
John Wiegley01296292011-04-08 18:41:53 +00009480 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9481 if (ERes.isInvalid())
9482 return ExprError();
9483 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +00009484
9485 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +00009486 if (!T->isScalarType()) { // C99 6.8.4.1p1
9487 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9488 << T << E->getSourceRange();
9489 return ExprError();
9490 }
John McCalld5707ab2009-10-12 21:59:07 +00009491 }
9492
John Wiegley01296292011-04-08 18:41:53 +00009493 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +00009494}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009495
John McCalldadc5752010-08-24 06:29:42 +00009496ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9497 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00009498 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009499 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009500
9501 return CheckBooleanCondition(Sub, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +00009502}
John McCall36e7fe32010-10-12 00:20:44 +00009503
John McCall31996342011-04-07 08:22:57 +00009504namespace {
John McCall2979fe02011-04-12 00:42:48 +00009505 /// A visitor for rebuilding a call to an __unknown_any expression
9506 /// to have an appropriate type.
9507 struct RebuildUnknownAnyFunction
9508 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9509
9510 Sema &S;
9511
9512 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9513
9514 ExprResult VisitStmt(Stmt *S) {
9515 llvm_unreachable("unexpected statement!");
9516 return ExprError();
9517 }
9518
9519 ExprResult VisitExpr(Expr *expr) {
9520 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
9521 << expr->getSourceRange();
9522 return ExprError();
9523 }
9524
9525 /// Rebuild an expression which simply semantically wraps another
9526 /// expression which it shares the type and value kind of.
9527 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9528 ExprResult subResult = Visit(expr->getSubExpr());
9529 if (subResult.isInvalid()) return ExprError();
9530
9531 Expr *subExpr = subResult.take();
9532 expr->setSubExpr(subExpr);
9533 expr->setType(subExpr->getType());
9534 expr->setValueKind(subExpr->getValueKind());
9535 assert(expr->getObjectKind() == OK_Ordinary);
9536 return expr;
9537 }
9538
9539 ExprResult VisitParenExpr(ParenExpr *paren) {
9540 return rebuildSugarExpr(paren);
9541 }
9542
9543 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9544 return rebuildSugarExpr(op);
9545 }
9546
9547 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9548 ExprResult subResult = Visit(op->getSubExpr());
9549 if (subResult.isInvalid()) return ExprError();
9550
9551 Expr *subExpr = subResult.take();
9552 op->setSubExpr(subExpr);
9553 op->setType(S.Context.getPointerType(subExpr->getType()));
9554 assert(op->getValueKind() == VK_RValue);
9555 assert(op->getObjectKind() == OK_Ordinary);
9556 return op;
9557 }
9558
9559 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
9560 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
9561
9562 expr->setType(decl->getType());
9563
9564 assert(expr->getValueKind() == VK_RValue);
9565 if (S.getLangOptions().CPlusPlus &&
9566 !(isa<CXXMethodDecl>(decl) &&
9567 cast<CXXMethodDecl>(decl)->isInstance()))
9568 expr->setValueKind(VK_LValue);
9569
9570 return expr;
9571 }
9572
9573 ExprResult VisitMemberExpr(MemberExpr *mem) {
9574 return resolveDecl(mem, mem->getMemberDecl());
9575 }
9576
9577 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
9578 return resolveDecl(ref, ref->getDecl());
9579 }
9580 };
9581}
9582
9583/// Given a function expression of unknown-any type, try to rebuild it
9584/// to have a function type.
9585static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
9586 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
9587 if (result.isInvalid()) return ExprError();
9588 return S.DefaultFunctionArrayConversion(result.take());
9589}
9590
9591namespace {
John McCall2d2e8702011-04-11 07:02:50 +00009592 /// A visitor for rebuilding an expression of type __unknown_anytype
9593 /// into one which resolves the type directly on the referring
9594 /// expression. Strict preservation of the original source
9595 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +00009596 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +00009597 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +00009598
9599 Sema &S;
9600
9601 /// The current destination type.
9602 QualType DestType;
9603
9604 RebuildUnknownAnyExpr(Sema &S, QualType castType)
9605 : S(S), DestType(castType) {}
9606
John McCall39439732011-04-09 22:50:59 +00009607 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +00009608 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +00009609 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009610 }
9611
John McCall2d2e8702011-04-11 07:02:50 +00009612 ExprResult VisitExpr(Expr *expr) {
9613 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9614 << expr->getSourceRange();
9615 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009616 }
9617
John McCall2d2e8702011-04-11 07:02:50 +00009618 ExprResult VisitCallExpr(CallExpr *call);
9619 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
9620
John McCall39439732011-04-09 22:50:59 +00009621 /// Rebuild an expression which simply semantically wraps another
9622 /// expression which it shares the type and value kind of.
9623 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9624 ExprResult subResult = Visit(expr->getSubExpr());
John McCall2979fe02011-04-12 00:42:48 +00009625 if (subResult.isInvalid()) return ExprError();
John McCall39439732011-04-09 22:50:59 +00009626 Expr *subExpr = subResult.take();
9627 expr->setSubExpr(subExpr);
9628 expr->setType(subExpr->getType());
9629 expr->setValueKind(subExpr->getValueKind());
9630 assert(expr->getObjectKind() == OK_Ordinary);
9631 return expr;
9632 }
John McCall31996342011-04-07 08:22:57 +00009633
John McCall39439732011-04-09 22:50:59 +00009634 ExprResult VisitParenExpr(ParenExpr *paren) {
9635 return rebuildSugarExpr(paren);
9636 }
9637
9638 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9639 return rebuildSugarExpr(op);
9640 }
9641
John McCall2979fe02011-04-12 00:42:48 +00009642 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9643 const PointerType *ptr = DestType->getAs<PointerType>();
9644 if (!ptr) {
9645 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
9646 << op->getSourceRange();
9647 return ExprError();
9648 }
9649 assert(op->getValueKind() == VK_RValue);
9650 assert(op->getObjectKind() == OK_Ordinary);
9651 op->setType(DestType);
9652
9653 // Build the sub-expression as if it were an object of the pointee type.
9654 DestType = ptr->getPointeeType();
9655 ExprResult subResult = Visit(op->getSubExpr());
9656 if (subResult.isInvalid()) return ExprError();
9657 op->setSubExpr(subResult.take());
9658 return op;
9659 }
9660
John McCall2d2e8702011-04-11 07:02:50 +00009661 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCall39439732011-04-09 22:50:59 +00009662
John McCall2979fe02011-04-12 00:42:48 +00009663 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCall39439732011-04-09 22:50:59 +00009664
John McCall2979fe02011-04-12 00:42:48 +00009665 ExprResult VisitMemberExpr(MemberExpr *mem) {
9666 return resolveDecl(mem, mem->getMemberDecl());
9667 }
John McCall39439732011-04-09 22:50:59 +00009668
9669 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall2d2e8702011-04-11 07:02:50 +00009670 return resolveDecl(ref, ref->getDecl());
John McCall31996342011-04-07 08:22:57 +00009671 }
9672 };
9673}
9674
John McCall2d2e8702011-04-11 07:02:50 +00009675/// Rebuilds a call expression which yielded __unknown_anytype.
9676ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
9677 Expr *callee = call->getCallee();
9678
9679 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +00009680 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +00009681 FK_FunctionPointer,
9682 FK_BlockPointer
9683 };
9684
9685 FnKind kind;
9686 QualType type = callee->getType();
John McCall4adb38c2011-04-27 00:36:17 +00009687 if (type == S.Context.BoundMemberTy) {
9688 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
9689 kind = FK_MemberFunction;
9690 type = Expr::findBoundMemberType(callee);
John McCall2d2e8702011-04-11 07:02:50 +00009691 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
9692 type = ptr->getPointeeType();
9693 kind = FK_FunctionPointer;
9694 } else {
9695 type = type->castAs<BlockPointerType>()->getPointeeType();
9696 kind = FK_BlockPointer;
9697 }
9698 const FunctionType *fnType = type->castAs<FunctionType>();
9699
9700 // Verify that this is a legal result type of a function.
9701 if (DestType->isArrayType() || DestType->isFunctionType()) {
9702 unsigned diagID = diag::err_func_returning_array_function;
9703 if (kind == FK_BlockPointer)
9704 diagID = diag::err_block_returning_array_function;
9705
9706 S.Diag(call->getExprLoc(), diagID)
9707 << DestType->isFunctionType() << DestType;
9708 return ExprError();
9709 }
9710
9711 // Otherwise, go ahead and set DestType as the call's result.
9712 call->setType(DestType.getNonLValueExprType(S.Context));
9713 call->setValueKind(Expr::getValueKindForType(DestType));
9714 assert(call->getObjectKind() == OK_Ordinary);
9715
9716 // Rebuild the function type, replacing the result type with DestType.
9717 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
9718 DestType = S.Context.getFunctionType(DestType,
9719 proto->arg_type_begin(),
9720 proto->getNumArgs(),
9721 proto->getExtProtoInfo());
9722 else
9723 DestType = S.Context.getFunctionNoProtoType(DestType,
9724 fnType->getExtInfo());
9725
9726 // Rebuild the appropriate pointer-to-function type.
9727 switch (kind) {
John McCall4adb38c2011-04-27 00:36:17 +00009728 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +00009729 // Nothing to do.
9730 break;
9731
9732 case FK_FunctionPointer:
9733 DestType = S.Context.getPointerType(DestType);
9734 break;
9735
9736 case FK_BlockPointer:
9737 DestType = S.Context.getBlockPointerType(DestType);
9738 break;
9739 }
9740
9741 // Finally, we can recurse.
9742 ExprResult calleeResult = Visit(callee);
9743 if (!calleeResult.isUsable()) return ExprError();
9744 call->setCallee(calleeResult.take());
9745
9746 // Bind a temporary if necessary.
9747 return S.MaybeBindToTemporary(call);
9748}
9749
9750ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall2979fe02011-04-12 00:42:48 +00009751 // Verify that this is a legal result type of a call.
9752 if (DestType->isArrayType() || DestType->isFunctionType()) {
9753 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
9754 << DestType->isFunctionType() << DestType;
9755 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009756 }
9757
John McCall3f4138c2011-07-13 17:56:40 +00009758 // Rewrite the method result type if available.
9759 if (ObjCMethodDecl *method = msg->getMethodDecl()) {
9760 assert(method->getResultType() == S.Context.UnknownAnyTy);
9761 method->setResultType(DestType);
9762 }
John McCall2979fe02011-04-12 00:42:48 +00009763
John McCall2d2e8702011-04-11 07:02:50 +00009764 // Change the type of the message.
John McCall2979fe02011-04-12 00:42:48 +00009765 msg->setType(DestType.getNonReferenceType());
9766 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +00009767
John McCall2979fe02011-04-12 00:42:48 +00009768 return S.MaybeBindToTemporary(msg);
John McCall2d2e8702011-04-11 07:02:50 +00009769}
9770
9771ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall2979fe02011-04-12 00:42:48 +00009772 // The only case we should ever see here is a function-to-pointer decay.
John McCall2d2e8702011-04-11 07:02:50 +00009773 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall2d2e8702011-04-11 07:02:50 +00009774 assert(ice->getValueKind() == VK_RValue);
9775 assert(ice->getObjectKind() == OK_Ordinary);
9776
John McCall2979fe02011-04-12 00:42:48 +00009777 ice->setType(DestType);
9778
John McCall2d2e8702011-04-11 07:02:50 +00009779 // Rebuild the sub-expression as the pointee (function) type.
9780 DestType = DestType->castAs<PointerType>()->getPointeeType();
9781
9782 ExprResult result = Visit(ice->getSubExpr());
9783 if (!result.isUsable()) return ExprError();
9784
9785 ice->setSubExpr(result.take());
9786 return S.Owned(ice);
9787}
9788
John McCall2979fe02011-04-12 00:42:48 +00009789ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall2d2e8702011-04-11 07:02:50 +00009790 ExprValueKind valueKind = VK_LValue;
John McCall2d2e8702011-04-11 07:02:50 +00009791 QualType type = DestType;
9792
9793 // We know how to make this work for certain kinds of decls:
9794
9795 // - functions
John McCall2979fe02011-04-12 00:42:48 +00009796 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCall2d2e8702011-04-11 07:02:50 +00009797 // This is true because FunctionDecls must always have function
9798 // type, so we can't be resolving the entire thing at once.
9799 assert(type->isFunctionType());
9800
John McCall4adb38c2011-04-27 00:36:17 +00009801 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
9802 if (method->isInstance()) {
9803 valueKind = VK_RValue;
9804 type = S.Context.BoundMemberTy;
9805 }
9806
John McCall2d2e8702011-04-11 07:02:50 +00009807 // Function references aren't l-values in C.
9808 if (!S.getLangOptions().CPlusPlus)
9809 valueKind = VK_RValue;
9810
9811 // - variables
9812 } else if (isa<VarDecl>(decl)) {
John McCall2979fe02011-04-12 00:42:48 +00009813 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
9814 type = refTy->getPointeeType();
John McCall2d2e8702011-04-11 07:02:50 +00009815 } else if (type->isFunctionType()) {
John McCall2979fe02011-04-12 00:42:48 +00009816 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
9817 << decl << expr->getSourceRange();
9818 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009819 }
9820
9821 // - nothing else
9822 } else {
9823 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
9824 << decl << expr->getSourceRange();
9825 return ExprError();
9826 }
9827
John McCall2979fe02011-04-12 00:42:48 +00009828 decl->setType(DestType);
9829 expr->setType(type);
9830 expr->setValueKind(valueKind);
9831 return S.Owned(expr);
John McCall2d2e8702011-04-11 07:02:50 +00009832}
9833
John McCall31996342011-04-07 08:22:57 +00009834/// Check a cast of an unknown-any type. We intentionally only
9835/// trigger this for C-style casts.
John Wiegley01296292011-04-08 18:41:53 +00009836ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
9837 Expr *castExpr, CastKind &castKind,
9838 ExprValueKind &VK, CXXCastPath &path) {
John McCall31996342011-04-07 08:22:57 +00009839 // Rewrite the casted expression from scratch.
John McCall39439732011-04-09 22:50:59 +00009840 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
9841 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +00009842
John McCall39439732011-04-09 22:50:59 +00009843 castExpr = result.take();
9844 VK = castExpr->getValueKind();
9845 castKind = CK_NoOp;
9846
9847 return castExpr;
John McCall31996342011-04-07 08:22:57 +00009848}
9849
9850static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
9851 Expr *orig = e;
John McCall2d2e8702011-04-11 07:02:50 +00009852 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +00009853 while (true) {
9854 e = e->IgnoreParenImpCasts();
John McCall2d2e8702011-04-11 07:02:50 +00009855 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall31996342011-04-07 08:22:57 +00009856 e = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +00009857 diagID = diag::err_uncasted_call_of_unknown_any;
9858 } else {
John McCall31996342011-04-07 08:22:57 +00009859 break;
John McCall2d2e8702011-04-11 07:02:50 +00009860 }
John McCall31996342011-04-07 08:22:57 +00009861 }
9862
John McCall2d2e8702011-04-11 07:02:50 +00009863 SourceLocation loc;
9864 NamedDecl *d;
9865 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9866 loc = ref->getLocation();
9867 d = ref->getDecl();
9868 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
9869 loc = mem->getMemberLoc();
9870 d = mem->getMemberDecl();
9871 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
9872 diagID = diag::err_uncasted_call_of_unknown_any;
9873 loc = msg->getSelectorLoc();
9874 d = msg->getMethodDecl();
9875 assert(d && "unknown method returning __unknown_any?");
9876 } else {
9877 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9878 << e->getSourceRange();
9879 return ExprError();
9880 }
9881
9882 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +00009883
9884 // Never recoverable.
9885 return ExprError();
9886}
9887
John McCall36e7fe32010-10-12 00:20:44 +00009888/// Check for operands with placeholder types and complain if found.
9889/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +00009890ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +00009891 // Placeholder types are always *exactly* the appropriate builtin type.
9892 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +00009893
John McCall31996342011-04-07 08:22:57 +00009894 // Overloaded expressions.
9895 if (type == Context.OverloadTy)
9896 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009897 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +00009898 QualType(),
9899 diag::err_ovl_unresolvable);
9900
John McCall0009fcc2011-04-26 20:42:42 +00009901 // Bound member functions.
9902 if (type == Context.BoundMemberTy) {
9903 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9904 << E->getSourceRange();
9905 return ExprError();
9906 }
9907
John McCall31996342011-04-07 08:22:57 +00009908 // Expressions of unknown type.
9909 if (type == Context.UnknownAnyTy)
9910 return diagnoseUnknownAnyExpr(*this, E);
9911
9912 assert(!type->isPlaceholderType());
9913 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +00009914}
Richard Trieu2c850c02011-04-21 21:44:26 +00009915
9916bool Sema::CheckCaseExpression(Expr *expr) {
9917 if (expr->isTypeDependent())
9918 return true;
9919 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
9920 return expr->getType()->isIntegralOrEnumerationType();
9921 return false;
9922}