blob: f55a6babd8cfa063506987c255b6ee81e59f7e9f [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);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000325
John McCall27584242010-12-06 20:48:59 +0000326 QualType T = E->getType();
327 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000328
John McCall27584242010-12-06 20:48:59 +0000329 // Create a load out of an ObjCProperty l-value, if necessary.
330 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +0000331 ExprResult Res = ConvertPropertyForRValue(E);
332 if (Res.isInvalid())
333 return Owned(E);
334 E = Res.take();
John McCall27584242010-12-06 20:48:59 +0000335 if (!E->isGLValue())
John Wiegley01296292011-04-08 18:41:53 +0000336 return Owned(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000337 }
John McCall27584242010-12-06 20:48:59 +0000338
339 // We don't want to throw lvalue-to-rvalue casts on top of
340 // expressions of certain types in C++.
341 if (getLangOptions().CPlusPlus &&
342 (E->getType() == Context.OverloadTy ||
343 T->isDependentType() ||
344 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000345 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000346
347 // The C standard is actually really unclear on this point, and
348 // DR106 tells us what the result should be but not why. It's
349 // generally best to say that void types just doesn't undergo
350 // lvalue-to-rvalue at all. Note that expressions of unqualified
351 // 'void' type are never l-values, but qualified void can be.
352 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000353 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000354
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000355 CheckForNullPointerDereference(*this, E);
356
John McCall27584242010-12-06 20:48:59 +0000357 // C++ [conv.lval]p1:
358 // [...] If T is a non-class type, the type of the prvalue is the
359 // cv-unqualified version of T. Otherwise, the type of the
360 // rvalue is T.
361 //
362 // C99 6.3.2.1p2:
363 // If the lvalue has qualified type, the value has the unqualified
364 // version of the type of the lvalue; otherwise, the value has the
365 // type of the lvalue.
366 if (T.hasQualifiers())
367 T = T.getUnqualifiedType();
Ted Kremenek64699be2011-02-16 01:57:07 +0000368
John Wiegley01296292011-04-08 18:41:53 +0000369 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
370 E, 0, VK_RValue));
John McCall27584242010-12-06 20:48:59 +0000371}
372
John Wiegley01296292011-04-08 18:41:53 +0000373ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
374 ExprResult Res = DefaultFunctionArrayConversion(E);
375 if (Res.isInvalid())
376 return ExprError();
377 Res = DefaultLvalueConversion(Res.take());
378 if (Res.isInvalid())
379 return ExprError();
380 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000381}
382
383
Chris Lattner513165e2008-07-25 21:10:04 +0000384/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000385/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000386/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000387/// apply if the array is an argument to the sizeof or address (&) operators.
388/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000389ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000390 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000391 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
392 if (Res.isInvalid())
393 return Owned(E);
394 E = Res.take();
John McCallf3735e02010-12-01 04:43:34 +0000395
396 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000397 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000398
399 // Try to perform integral promotions if the object has a theoretically
400 // promotable type.
401 if (Ty->isIntegralOrUnscopedEnumerationType()) {
402 // C99 6.3.1.1p2:
403 //
404 // The following may be used in an expression wherever an int or
405 // unsigned int may be used:
406 // - an object or expression with an integer type whose integer
407 // conversion rank is less than or equal to the rank of int
408 // and unsigned int.
409 // - A bit-field of type _Bool, int, signed int, or unsigned int.
410 //
411 // If an int can represent all values of the original type, the
412 // value is converted to an int; otherwise, it is converted to an
413 // unsigned int. These are called the integer promotions. All
414 // other types are unchanged by the integer promotions.
415
416 QualType PTy = Context.isPromotableBitField(E);
417 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000418 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
419 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000420 }
421 if (Ty->isPromotableIntegerType()) {
422 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000423 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
424 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000425 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000426 }
John Wiegley01296292011-04-08 18:41:53 +0000427 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000428}
429
Chris Lattner2ce500f2008-07-25 22:25:12 +0000430/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000431/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000432/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000433ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
434 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000435 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000436
John Wiegley01296292011-04-08 18:41:53 +0000437 ExprResult Res = UsualUnaryConversions(E);
438 if (Res.isInvalid())
439 return Owned(E);
440 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000441
Chris Lattner2ce500f2008-07-25 22:25:12 +0000442 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000443 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000444 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
445
446 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000447}
448
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000449/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
450/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000451/// interfaces passed by value.
452ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000453 FunctionDecl *FDecl) {
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000454 ExprResult ExprRes = CheckPlaceholderExpr(E);
455 if (ExprRes.isInvalid())
456 return ExprError();
457
458 ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000459 if (ExprRes.isInvalid())
460 return ExprError();
461 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000462
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000463 // __builtin_va_start takes the second argument as a "varargs" argument, but
464 // it doesn't actually do anything with it. It doesn't need to be non-pod
465 // etc.
466 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
John Wiegley01296292011-04-08 18:41:53 +0000467 return Owned(E);
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000468
Douglas Gregor347e0f22011-05-21 19:26:31 +0000469 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000470 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000471 DiagRuntimeBehavior(E->getLocStart(), 0,
472 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
473 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000474 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000475
John McCall31168b02011-06-15 23:02:42 +0000476 if (!E->getType().isPODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000477 // C++0x [expr.call]p7:
478 // Passing a potentially-evaluated argument of class type (Clause 9)
479 // having a non-trivial copy constructor, a non-trivial move constructor,
480 // or a non-trivial destructor, with no corresponding parameter,
481 // is conditionally-supported with implementation-defined semantics.
482 bool TrivialEnough = false;
483 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
484 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
485 if (Record->hasTrivialCopyConstructor() &&
486 Record->hasTrivialMoveConstructor() &&
487 Record->hasTrivialDestructor())
488 TrivialEnough = true;
489 }
490 }
John McCall31168b02011-06-15 23:02:42 +0000491
492 if (!TrivialEnough &&
493 getLangOptions().ObjCAutoRefCount &&
494 E->getType()->isObjCLifetimeType())
495 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000496
497 if (TrivialEnough) {
498 // Nothing to diagnose. This is okay.
499 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000500 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor253cadf2011-05-21 16:27:21 +0000501 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000502 << CT)) {
503 // Turn this into a trap.
504 CXXScopeSpec SS;
505 UnqualifiedId Name;
506 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
507 E->getLocStart());
508 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
509 if (TrapFn.isInvalid())
510 return ExprError();
511
512 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
513 MultiExprArg(), E->getLocEnd());
514 if (Call.isInvalid())
515 return ExprError();
516
517 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
518 Call.get(), E);
519 if (Comma.isInvalid())
520 return ExprError();
521
522 E = Comma.get();
523 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000524 }
525
John Wiegley01296292011-04-08 18:41:53 +0000526 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000527}
528
Chris Lattner513165e2008-07-25 21:10:04 +0000529/// UsualArithmeticConversions - Performs various conversions that are common to
530/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000531/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000532/// responsible for emitting appropriate error diagnostics.
533/// FIXME: verify the conversion rules for "complex int" are consistent with
534/// GCC.
Richard Trieucfc491d2011-08-02 04:35:43 +0000535QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr,
536 ExprResult &rhsExpr,
Chris Lattner513165e2008-07-25 21:10:04 +0000537 bool isCompAssign) {
John Wiegley01296292011-04-08 18:41:53 +0000538 if (!isCompAssign) {
539 lhsExpr = UsualUnaryConversions(lhsExpr.take());
540 if (lhsExpr.isInvalid())
541 return QualType();
542 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000543
John Wiegley01296292011-04-08 18:41:53 +0000544 rhsExpr = UsualUnaryConversions(rhsExpr.take());
545 if (rhsExpr.isInvalid())
546 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000547
Mike Stump11289f42009-09-09 15:08:12 +0000548 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000549 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000550 QualType lhs =
John Wiegley01296292011-04-08 18:41:53 +0000551 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000552 QualType rhs =
John Wiegley01296292011-04-08 18:41:53 +0000553 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000554
555 // If both types are identical, no conversion is needed.
556 if (lhs == rhs)
557 return lhs;
558
559 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
560 // The caller can deal with this (e.g. pointer + int).
561 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
562 return lhs;
563
John McCalld005ac92010-11-13 08:17:45 +0000564 // Apply unary and bitfield promotions to the LHS's type.
565 QualType lhs_unpromoted = lhs;
566 if (lhs->isPromotableIntegerType())
567 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley01296292011-04-08 18:41:53 +0000568 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000569 if (!LHSBitfieldPromoteTy.isNull())
570 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000571 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000572 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000573
John McCalld005ac92010-11-13 08:17:45 +0000574 // If both types are identical, no conversion is needed.
575 if (lhs == rhs)
576 return lhs;
577
578 // At this point, we have two different arithmetic types.
579
580 // Handle complex types first (C99 6.3.1.8p1).
581 bool LHSComplexFloat = lhs->isComplexType();
582 bool RHSComplexFloat = rhs->isComplexType();
583 if (LHSComplexFloat || RHSComplexFloat) {
584 // if we have an integer operand, the result is the complex type.
585
John McCallc5e62b42010-11-13 09:02:35 +0000586 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
587 if (rhs->isIntegerType()) {
588 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000589 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
Richard Trieucfc491d2011-08-02 04:35:43 +0000590 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
591 CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000592 } else {
593 assert(rhs->isComplexIntegerType());
Richard Trieucfc491d2011-08-02 04:35:43 +0000594 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
595 CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000596 }
John McCalld005ac92010-11-13 08:17:45 +0000597 return lhs;
598 }
599
John McCallc5e62b42010-11-13 09:02:35 +0000600 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
601 if (!isCompAssign) {
602 // int -> float -> _Complex float
603 if (lhs->isIntegerType()) {
604 QualType fp = cast<ComplexType>(rhs)->getElementType();
Richard Trieucfc491d2011-08-02 04:35:43 +0000605 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp,
606 CK_IntegralToFloating);
607 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
608 CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000609 } else {
610 assert(lhs->isComplexIntegerType());
Richard Trieucfc491d2011-08-02 04:35:43 +0000611 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
612 CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000613 }
614 }
John McCalld005ac92010-11-13 08:17:45 +0000615 return rhs;
616 }
617
618 // This handles complex/complex, complex/float, or float/complex.
619 // When both operands are complex, the shorter operand is converted to the
620 // type of the longer, and that is the type of the result. This corresponds
621 // to what is done when combining two real floating-point operands.
622 // The fun begins when size promotion occur across type domains.
623 // From H&S 6.3.4: When one operand is complex and the other is a real
624 // floating-point type, the less precise type is converted, within it's
625 // real or complex domain, to the precision of the other type. For example,
626 // when combining a "long double" with a "double _Complex", the
627 // "double _Complex" is promoted to "long double _Complex".
628 int order = Context.getFloatingTypeOrder(lhs, rhs);
629
630 // If both are complex, just cast to the more precise type.
631 if (LHSComplexFloat && RHSComplexFloat) {
632 if (order > 0) {
633 // _Complex float -> _Complex double
Richard Trieucfc491d2011-08-02 04:35:43 +0000634 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
635 CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000636 return lhs;
637
638 } else if (order < 0) {
639 // _Complex float -> _Complex double
640 if (!isCompAssign)
Richard Trieucfc491d2011-08-02 04:35:43 +0000641 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
642 CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000643 return rhs;
644 }
645 return lhs;
646 }
647
648 // If just the LHS is complex, the RHS needs to be converted,
649 // and the LHS might need to be promoted.
650 if (LHSComplexFloat) {
651 if (order > 0) { // LHS is wider
652 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000653 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000654 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
Richard Trieucfc491d2011-08-02 04:35:43 +0000655 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs,
656 CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000657 return lhs;
658 }
659
660 // RHS is at least as wide. Find its corresponding complex type.
661 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
662
663 // double -> _Complex double
Richard Trieucfc491d2011-08-02 04:35:43 +0000664 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
665 CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000666
667 // _Complex float -> _Complex double
668 if (!isCompAssign && order < 0)
Richard Trieucfc491d2011-08-02 04:35:43 +0000669 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
670 CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000671
672 return result;
673 }
674
675 // Just the RHS is complex, so the LHS needs to be converted
676 // and the RHS might need to be promoted.
677 assert(RHSComplexFloat);
678
679 if (order < 0) { // RHS is wider
680 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000681 if (!isCompAssign) {
Argyrios Kyrtzidise84389b2011-01-18 18:49:33 +0000682 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000683 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
Richard Trieucfc491d2011-08-02 04:35:43 +0000684 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
685 CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000686 }
John McCalld005ac92010-11-13 08:17:45 +0000687 return rhs;
688 }
689
690 // LHS is at least as wide. Find its corresponding complex type.
691 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
692
693 // double -> _Complex double
694 if (!isCompAssign)
Richard Trieucfc491d2011-08-02 04:35:43 +0000695 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
696 CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000697
698 // _Complex float -> _Complex double
699 if (order > 0)
Richard Trieucfc491d2011-08-02 04:35:43 +0000700 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
701 CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000702
703 return result;
704 }
705
706 // Now handle "real" floating types (i.e. float, double, long double).
707 bool LHSFloat = lhs->isRealFloatingType();
708 bool RHSFloat = rhs->isRealFloatingType();
709 if (LHSFloat || RHSFloat) {
710 // If we have two real floating types, convert the smaller operand
711 // to the bigger result.
712 if (LHSFloat && RHSFloat) {
713 int order = Context.getFloatingTypeOrder(lhs, rhs);
714 if (order > 0) {
John Wiegley01296292011-04-08 18:41:53 +0000715 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000716 return lhs;
717 }
718
719 assert(order < 0 && "illegal float comparison");
720 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000721 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000722 return rhs;
723 }
724
725 // If we have an integer operand, the result is the real floating type.
726 if (LHSFloat) {
727 if (rhs->isIntegerType()) {
728 // Convert rhs to the lhs floating point type.
John Wiegley01296292011-04-08 18:41:53 +0000729 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000730 return lhs;
731 }
732
733 // Convert both sides to the appropriate complex float.
734 assert(rhs->isComplexIntegerType());
735 QualType result = Context.getComplexType(lhs);
736
737 // _Complex int -> _Complex float
Richard Trieucfc491d2011-08-02 04:35:43 +0000738 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
739 CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000740
741 // float -> _Complex float
742 if (!isCompAssign)
Richard Trieucfc491d2011-08-02 04:35:43 +0000743 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
744 CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000745
746 return result;
747 }
748
749 assert(RHSFloat);
750 if (lhs->isIntegerType()) {
751 // Convert lhs to the rhs floating point type.
752 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000753 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000754 return rhs;
755 }
756
757 // Convert both sides to the appropriate complex float.
758 assert(lhs->isComplexIntegerType());
759 QualType result = Context.getComplexType(rhs);
760
761 // _Complex int -> _Complex float
762 if (!isCompAssign)
Richard Trieucfc491d2011-08-02 04:35:43 +0000763 lhsExpr = ImpCastExprToType(lhsExpr.take(), result,
764 CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000765
766 // float -> _Complex float
Richard Trieucfc491d2011-08-02 04:35:43 +0000767 rhsExpr = ImpCastExprToType(rhsExpr.take(), result,
768 CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000769
770 return result;
771 }
772
773 // Handle GCC complex int extension.
774 // FIXME: if the operands are (int, _Complex long), we currently
775 // don't promote the complex. Also, signedness?
776 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
777 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
778 if (lhsComplexInt && rhsComplexInt) {
779 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
780 rhsComplexInt->getElementType());
781 assert(order && "inequal types with equal element ordering");
782 if (order > 0) {
783 // _Complex int -> _Complex long
John Wiegley01296292011-04-08 18:41:53 +0000784 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000785 return lhs;
786 }
787
788 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000789 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000790 return rhs;
791 } else if (lhsComplexInt) {
792 // int -> _Complex int
John Wiegley01296292011-04-08 18:41:53 +0000793 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000794 return lhs;
795 } else if (rhsComplexInt) {
796 // int -> _Complex int
797 if (!isCompAssign)
Richard Trieucfc491d2011-08-02 04:35:43 +0000798 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs,
799 CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000800 return rhs;
801 }
802
803 // Finally, we have two differing integer types.
804 // The rules for this case are in C99 6.3.1.8
805 int compare = Context.getIntegerTypeOrder(lhs, rhs);
806 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
807 rhsSigned = rhs->hasSignedIntegerRepresentation();
808 if (lhsSigned == rhsSigned) {
809 // Same signedness; use the higher-ranked type
810 if (compare >= 0) {
John Wiegley01296292011-04-08 18:41:53 +0000811 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000812 return lhs;
813 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000814 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000815 return rhs;
816 } else if (compare != (lhsSigned ? 1 : -1)) {
817 // The unsigned type has greater than or equal rank to the
818 // signed type, so use the unsigned type
819 if (rhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000820 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000821 return lhs;
822 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000823 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000824 return rhs;
825 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
826 // The two types are different widths; if we are here, that
827 // means the signed type is larger than the unsigned type, so
828 // use the signed type.
829 if (lhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000830 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000831 return lhs;
832 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000833 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000834 return rhs;
835 } else {
836 // The signed type is higher-ranked than the unsigned type,
837 // but isn't actually any bigger (like unsigned int and long
838 // on most 32-bit systems). Use the unsigned type corresponding
839 // to the signed type.
840 QualType result =
841 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley01296292011-04-08 18:41:53 +0000842 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000843 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000844 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000845 return result;
846 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000847}
848
Chris Lattner513165e2008-07-25 21:10:04 +0000849//===----------------------------------------------------------------------===//
850// Semantic Analysis for various Expression Types
851//===----------------------------------------------------------------------===//
852
853
Peter Collingbourne91147592011-04-15 00:35:48 +0000854ExprResult
855Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
856 SourceLocation DefaultLoc,
857 SourceLocation RParenLoc,
858 Expr *ControllingExpr,
859 MultiTypeArg types,
860 MultiExprArg exprs) {
861 unsigned NumAssocs = types.size();
862 assert(NumAssocs == exprs.size());
863
864 ParsedType *ParsedTypes = types.release();
865 Expr **Exprs = exprs.release();
866
867 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
868 for (unsigned i = 0; i < NumAssocs; ++i) {
869 if (ParsedTypes[i])
870 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
871 else
872 Types[i] = 0;
873 }
874
875 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
876 ControllingExpr, Types, Exprs,
877 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000878 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000879 return ER;
880}
881
882ExprResult
883Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
884 SourceLocation DefaultLoc,
885 SourceLocation RParenLoc,
886 Expr *ControllingExpr,
887 TypeSourceInfo **Types,
888 Expr **Exprs,
889 unsigned NumAssocs) {
890 bool TypeErrorFound = false,
891 IsResultDependent = ControllingExpr->isTypeDependent(),
892 ContainsUnexpandedParameterPack
893 = ControllingExpr->containsUnexpandedParameterPack();
894
895 for (unsigned i = 0; i < NumAssocs; ++i) {
896 if (Exprs[i]->containsUnexpandedParameterPack())
897 ContainsUnexpandedParameterPack = true;
898
899 if (Types[i]) {
900 if (Types[i]->getType()->containsUnexpandedParameterPack())
901 ContainsUnexpandedParameterPack = true;
902
903 if (Types[i]->getType()->isDependentType()) {
904 IsResultDependent = true;
905 } else {
906 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
907 // complete object type other than a variably modified type."
908 unsigned D = 0;
909 if (Types[i]->getType()->isIncompleteType())
910 D = diag::err_assoc_type_incomplete;
911 else if (!Types[i]->getType()->isObjectType())
912 D = diag::err_assoc_type_nonobject;
913 else if (Types[i]->getType()->isVariablyModifiedType())
914 D = diag::err_assoc_type_variably_modified;
915
916 if (D != 0) {
917 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
918 << Types[i]->getTypeLoc().getSourceRange()
919 << Types[i]->getType();
920 TypeErrorFound = true;
921 }
922
923 // C1X 6.5.1.1p2 "No two generic associations in the same generic
924 // selection shall specify compatible types."
925 for (unsigned j = i+1; j < NumAssocs; ++j)
926 if (Types[j] && !Types[j]->getType()->isDependentType() &&
927 Context.typesAreCompatible(Types[i]->getType(),
928 Types[j]->getType())) {
929 Diag(Types[j]->getTypeLoc().getBeginLoc(),
930 diag::err_assoc_compatible_types)
931 << Types[j]->getTypeLoc().getSourceRange()
932 << Types[j]->getType()
933 << Types[i]->getType();
934 Diag(Types[i]->getTypeLoc().getBeginLoc(),
935 diag::note_compat_assoc)
936 << Types[i]->getTypeLoc().getSourceRange()
937 << Types[i]->getType();
938 TypeErrorFound = true;
939 }
940 }
941 }
942 }
943 if (TypeErrorFound)
944 return ExprError();
945
946 // If we determined that the generic selection is result-dependent, don't
947 // try to compute the result expression.
948 if (IsResultDependent)
949 return Owned(new (Context) GenericSelectionExpr(
950 Context, KeyLoc, ControllingExpr,
951 Types, Exprs, NumAssocs, DefaultLoc,
952 RParenLoc, ContainsUnexpandedParameterPack));
953
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000954 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +0000955 unsigned DefaultIndex = -1U;
956 for (unsigned i = 0; i < NumAssocs; ++i) {
957 if (!Types[i])
958 DefaultIndex = i;
959 else if (Context.typesAreCompatible(ControllingExpr->getType(),
960 Types[i]->getType()))
961 CompatIndices.push_back(i);
962 }
963
964 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
965 // type compatible with at most one of the types named in its generic
966 // association list."
967 if (CompatIndices.size() > 1) {
968 // We strip parens here because the controlling expression is typically
969 // parenthesized in macro definitions.
970 ControllingExpr = ControllingExpr->IgnoreParens();
971 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
972 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
973 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000974 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +0000975 E = CompatIndices.end(); I != E; ++I) {
976 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
977 diag::note_compat_assoc)
978 << Types[*I]->getTypeLoc().getSourceRange()
979 << Types[*I]->getType();
980 }
981 return ExprError();
982 }
983
984 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
985 // its controlling expression shall have type compatible with exactly one of
986 // the types named in its generic association list."
987 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
988 // We strip parens here because the controlling expression is typically
989 // parenthesized in macro definitions.
990 ControllingExpr = ControllingExpr->IgnoreParens();
991 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
992 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
993 return ExprError();
994 }
995
996 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
997 // type name that is compatible with the type of the controlling expression,
998 // then the result expression of the generic selection is the expression
999 // in that generic association. Otherwise, the result expression of the
1000 // generic selection is the expression in the default generic association."
1001 unsigned ResultIndex =
1002 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1003
1004 return Owned(new (Context) GenericSelectionExpr(
1005 Context, KeyLoc, ControllingExpr,
1006 Types, Exprs, NumAssocs, DefaultLoc,
1007 RParenLoc, ContainsUnexpandedParameterPack,
1008 ResultIndex));
1009}
1010
Steve Naroff83895f72007-09-16 03:34:24 +00001011/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001012/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1013/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1014/// multiple tokens. However, the common case is that StringToks points to one
1015/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001016///
John McCalldadc5752010-08-24 06:29:42 +00001017ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +00001018Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001019 assert(NumStringToks && "Must have at least one string!");
1020
Chris Lattner8a24e582009-01-16 18:51:42 +00001021 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001022 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001023 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001024
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001025 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001026 for (unsigned i = 0; i != NumStringToks; ++i)
1027 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001028
Chris Lattner36fc8792008-02-11 00:02:17 +00001029 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001030 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001031 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001032 else if (Literal.isUTF16())
1033 StrTy = Context.Char16Ty;
1034 else if (Literal.isUTF32())
1035 StrTy = Context.Char32Ty;
Anders Carlsson6b06e182011-04-06 18:42:48 +00001036 else if (Literal.Pascal)
1037 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001038
Douglas Gregorfb65e592011-07-27 05:40:30 +00001039 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1040 if (Literal.isWide())
1041 Kind = StringLiteral::Wide;
1042 else if (Literal.isUTF8())
1043 Kind = StringLiteral::UTF8;
1044 else if (Literal.isUTF16())
1045 Kind = StringLiteral::UTF16;
1046 else if (Literal.isUTF32())
1047 Kind = StringLiteral::UTF32;
1048
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001049 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +00001050 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001051 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001052
Chris Lattner36fc8792008-02-11 00:02:17 +00001053 // Get an array type for the string, according to C99 6.4.5. This includes
1054 // the nul terminator character as well as the string length for pascal
1055 // strings.
1056 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001057 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001058 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001059
Chris Lattner5b183d82006-11-10 05:03:26 +00001060 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +00001061 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001062 Kind, Literal.Pascal, StrTy,
Alexis Hunt3b791862010-08-30 17:47:05 +00001063 &StringTokLocs[0],
1064 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +00001065}
1066
John McCallc63de662011-02-02 13:00:07 +00001067enum CaptureResult {
1068 /// No capture is required.
1069 CR_NoCapture,
1070
1071 /// A capture is required.
1072 CR_Capture,
1073
John McCall351762c2011-02-07 10:33:21 +00001074 /// A by-ref capture is required.
1075 CR_CaptureByRef,
1076
John McCallc63de662011-02-02 13:00:07 +00001077 /// An error occurred when trying to capture the given variable.
1078 CR_Error
1079};
1080
1081/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +00001082///
John McCallc63de662011-02-02 13:00:07 +00001083/// \param var - the variable referenced
1084/// \param DC - the context which we couldn't capture through
1085static CaptureResult
John McCall351762c2011-02-07 10:33:21 +00001086diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001087 VarDecl *var, DeclContext *DC) {
1088 switch (S.ExprEvalContexts.back().Context) {
1089 case Sema::Unevaluated:
1090 // The argument will never be evaluated, so don't complain.
1091 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +00001092
John McCallc63de662011-02-02 13:00:07 +00001093 case Sema::PotentiallyEvaluated:
1094 case Sema::PotentiallyEvaluatedIfUsed:
1095 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +00001096
John McCallc63de662011-02-02 13:00:07 +00001097 case Sema::PotentiallyPotentiallyEvaluated:
1098 // FIXME: delay these!
1099 break;
Chris Lattner497d7b02009-04-21 22:26:47 +00001100 }
Mike Stump11289f42009-09-09 15:08:12 +00001101
John McCallc63de662011-02-02 13:00:07 +00001102 // Don't diagnose about capture if we're not actually in code right
1103 // now; in general, there are more appropriate places that will
1104 // diagnose this.
1105 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1106
John McCall92d627e2011-03-22 23:15:50 +00001107 // Certain madnesses can happen with parameter declarations, which
1108 // we want to ignore.
1109 if (isa<ParmVarDecl>(var)) {
1110 // - If the parameter still belongs to the translation unit, then
1111 // we're actually just using one parameter in the declaration of
1112 // the next. This is useful in e.g. VLAs.
1113 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1114 return CR_NoCapture;
1115
1116 // - This particular madness can happen in ill-formed default
1117 // arguments; claim it's okay and let downstream code handle it.
1118 if (S.CurContext == var->getDeclContext()->getParent())
1119 return CR_NoCapture;
1120 }
John McCallc63de662011-02-02 13:00:07 +00001121
1122 DeclarationName functionName;
1123 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1124 functionName = fn->getDeclName();
1125 // FIXME: variable from enclosing block that we couldn't capture from!
1126
1127 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1128 << var->getIdentifier() << functionName;
1129 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1130 << var->getIdentifier();
1131
1132 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +00001133}
1134
John McCall351762c2011-02-07 10:33:21 +00001135/// There is a well-formed capture at a particular scope level;
1136/// propagate it through all the nested blocks.
1137static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1138 const BlockDecl::Capture &capture) {
1139 VarDecl *var = capture.getVariable();
1140
1141 // Update all the inner blocks with the capture information.
1142 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1143 i != e; ++i) {
1144 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1145 innerBlock->Captures.push_back(
1146 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1147 /*nested*/ true, capture.getCopyExpr()));
1148 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1149 }
1150
1151 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1152}
1153
1154/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +00001155/// given value in the current context requires a variable capture.
1156///
1157/// This also keeps the captures set in the BlockScopeInfo records
1158/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +00001159static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001160 ValueDecl *value) {
1161 // Only variables ever require capture.
1162 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +00001163 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +00001164
1165 // Fast path: variables from the current context never require capture.
1166 DeclContext *DC = S.CurContext;
1167 if (var->getDeclContext() == DC) return CR_NoCapture;
1168
1169 // Only variables with local storage require capture.
1170 // FIXME: What about 'const' variables in C++?
1171 if (!var->hasLocalStorage()) return CR_NoCapture;
1172
1173 // Otherwise, we need to capture.
1174
1175 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +00001176 do {
1177 // Only blocks (and eventually C++0x closures) can capture; other
1178 // scopes don't work.
1179 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +00001180 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +00001181
1182 BlockScopeInfo *blockScope =
1183 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1184 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1185
John McCall351762c2011-02-07 10:33:21 +00001186 // Check whether we've already captured it in this block. If so,
1187 // we're done.
1188 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1189 return propagateCapture(S, functionScopesIndex,
1190 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +00001191
1192 functionScopesIndex--;
1193 DC = cast<BlockDecl>(DC)->getDeclContext();
1194 } while (var->getDeclContext() != DC);
1195
John McCall351762c2011-02-07 10:33:21 +00001196 // Okay, we descended all the way to the block that defines the variable.
1197 // Actually try to capture it.
1198 QualType type = var->getType();
1199
1200 // Prohibit variably-modified types.
1201 if (type->isVariablyModifiedType()) {
1202 S.Diag(loc, diag::err_ref_vm_type);
1203 S.Diag(var->getLocation(), diag::note_declared_at);
1204 return CR_Error;
1205 }
1206
1207 // Prohibit arrays, even in __block variables, but not references to
1208 // them.
1209 if (type->isArrayType()) {
1210 S.Diag(loc, diag::err_ref_array_type);
1211 S.Diag(var->getLocation(), diag::note_declared_at);
1212 return CR_Error;
1213 }
1214
1215 S.MarkDeclarationReferenced(loc, var);
1216
1217 // The BlocksAttr indicates the variable is bound by-reference.
1218 bool byRef = var->hasAttr<BlocksAttr>();
1219
1220 // Build a copy expression.
1221 Expr *copyExpr = 0;
John McCalla85af562011-04-28 02:15:35 +00001222 const RecordType *rtype;
1223 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1224 (rtype = type->getAs<RecordType>())) {
1225
1226 // The capture logic needs the destructor, so make sure we mark it.
1227 // Usually this is unnecessary because most local variables have
1228 // their destructors marked at declaration time, but parameters are
1229 // an exception because it's technically only the call site that
1230 // actually requires the destructor.
1231 if (isa<ParmVarDecl>(var))
1232 S.FinalizeVarWithDestructor(var, rtype);
1233
John McCall351762c2011-02-07 10:33:21 +00001234 // According to the blocks spec, the capture of a variable from
1235 // the stack requires a const copy constructor. This is not true
1236 // of the copy/move done to move a __block variable to the heap.
1237 type.addConst();
1238
1239 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1240 ExprResult result =
1241 S.PerformCopyInitialization(
1242 InitializedEntity::InitializeBlock(var->getLocation(),
1243 type, false),
1244 loc, S.Owned(declRef));
1245
1246 // Build a full-expression copy expression if initialization
1247 // succeeded and used a non-trivial constructor. Recover from
1248 // errors by pretending that the copy isn't necessary.
1249 if (!result.isInvalid() &&
1250 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1251 result = S.MaybeCreateExprWithCleanups(result);
1252 copyExpr = result.take();
1253 }
1254 }
1255
1256 // We're currently at the declarer; go back to the closure.
1257 functionScopesIndex++;
1258 BlockScopeInfo *blockScope =
1259 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1260
1261 // Build a valid capture in this scope.
1262 blockScope->Captures.push_back(
1263 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1264 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1265
1266 // Propagate that to inner captures if necessary.
1267 return propagateCapture(S, functionScopesIndex,
1268 blockScope->Captures.back());
1269}
1270
1271static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1272 const DeclarationNameInfo &NameInfo,
1273 bool byRef) {
1274 assert(isa<VarDecl>(vd) && "capturing non-variable");
1275
1276 VarDecl *var = cast<VarDecl>(vd);
1277 assert(var->hasLocalStorage() && "capturing non-local");
1278 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1279
1280 QualType exprType = var->getType().getNonReferenceType();
1281
1282 BlockDeclRefExpr *BDRE;
1283 if (!byRef) {
1284 // The variable will be bound by copy; make it const within the
1285 // closure, but record that this was done in the expression.
1286 bool constAdded = !exprType.isConstQualified();
1287 exprType.addConst();
1288
1289 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1290 NameInfo.getLoc(), false,
1291 constAdded);
1292 } else {
1293 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1294 NameInfo.getLoc(), true);
1295 }
1296
1297 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001298}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001299
John McCalldadc5752010-08-24 06:29:42 +00001300ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001301Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001302 SourceLocation Loc,
1303 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001304 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001305 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001306}
1307
John McCallf4cd4f92011-02-09 01:13:10 +00001308/// BuildDeclRefExpr - Build an expression that references a
1309/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001310ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001311Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001312 const DeclarationNameInfo &NameInfo,
1313 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001314 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001315
John McCall086a4642010-11-24 05:12:34 +00001316 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001317 SS? SS->getWithLocInContext(Context)
1318 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001319 D, NameInfo, Ty, VK);
1320
1321 // Just in case we're building an illegal pointer-to-member.
1322 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1323 E->setObjectKind(OK_BitField);
1324
1325 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001326}
1327
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001328/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001329/// possibly a list of template arguments.
1330///
1331/// If this produces template arguments, it is permitted to call
1332/// DecomposeTemplateName.
1333///
1334/// This actually loses a lot of source location information for
1335/// non-standard name kinds; we should consider preserving that in
1336/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001337void
1338Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1339 TemplateArgumentListInfo &Buffer,
1340 DeclarationNameInfo &NameInfo,
1341 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001342 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1343 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1344 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1345
Douglas Gregor5476205b2011-06-23 00:49:38 +00001346 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001347 Id.TemplateId->getTemplateArgs(),
1348 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001349 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001350 TemplateArgsPtr.release();
1351
John McCall3e56fd42010-08-23 07:28:44 +00001352 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001353 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001354 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001355 TemplateArgs = &Buffer;
1356 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001357 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001358 TemplateArgs = 0;
1359 }
1360}
1361
John McCalld681c392009-12-16 08:11:27 +00001362/// Diagnose an empty lookup.
1363///
1364/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001365bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001366 CorrectTypoContext CTC,
1367 TemplateArgumentListInfo *ExplicitTemplateArgs,
1368 Expr **Args, unsigned NumArgs) {
John McCalld681c392009-12-16 08:11:27 +00001369 DeclarationName Name = R.getLookupName();
1370
John McCalld681c392009-12-16 08:11:27 +00001371 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001372 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001373 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1374 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001375 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001376 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001377 diagnostic_suggest = diag::err_undeclared_use_suggest;
1378 }
John McCalld681c392009-12-16 08:11:27 +00001379
Douglas Gregor598b08f2009-12-31 05:20:13 +00001380 // If the original lookup was an unqualified lookup, fake an
1381 // unqualified lookup. This is useful when (for example) the
1382 // original lookup would not have found something because it was a
1383 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001384 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001385 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001386 if (isa<CXXRecordDecl>(DC)) {
1387 LookupQualifiedName(R, DC);
1388
1389 if (!R.empty()) {
1390 // Don't give errors about ambiguities in this lookup.
1391 R.suppressDiagnostics();
1392
1393 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1394 bool isInstance = CurMethod &&
1395 CurMethod->isInstance() &&
1396 DC == CurMethod->getParent();
1397
1398 // Give a code modification hint to insert 'this->'.
1399 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1400 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001401 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001402 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1403 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001404 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001405 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001406 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001407 Diag(R.getNameLoc(), diagnostic) << Name
1408 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1409 QualType DepThisType = DepMethod->getThisType(Context);
1410 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1411 R.getNameLoc(), DepThisType, false);
1412 TemplateArgumentListInfo TList;
1413 if (ULE->hasExplicitTemplateArgs())
1414 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001415
Douglas Gregore16af532011-02-28 18:50:33 +00001416 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001417 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001418 CXXDependentScopeMemberExpr *DepExpr =
1419 CXXDependentScopeMemberExpr::Create(
1420 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001421 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyfe712382010-08-20 20:54:15 +00001422 R.getLookupNameInfo(), &TList);
1423 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001424 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001425 // FIXME: we should be able to handle this case too. It is correct
1426 // to add this-> here. This is a workaround for PR7947.
1427 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001428 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001429 } else {
John McCalld681c392009-12-16 08:11:27 +00001430 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001431 }
John McCalld681c392009-12-16 08:11:27 +00001432
1433 // Do we really want to note all of these?
1434 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1435 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1436
1437 // Tell the callee to try to recover.
1438 return false;
1439 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001440
1441 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001442 }
1443 }
1444
Douglas Gregor598b08f2009-12-31 05:20:13 +00001445 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001446 TypoCorrection Corrected;
1447 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1448 S, &SS, NULL, false, CTC))) {
1449 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1450 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1451 R.setLookupName(Corrected.getCorrection());
1452
Hans Wennborg38198de2011-07-12 08:45:31 +00001453 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001454 if (Corrected.isOverloaded()) {
1455 OverloadCandidateSet OCS(R.getNameLoc());
1456 OverloadCandidateSet::iterator Best;
1457 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1458 CDEnd = Corrected.end();
1459 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001460 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001461 dyn_cast<FunctionTemplateDecl>(*CD))
1462 AddTemplateOverloadCandidate(
1463 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1464 Args, NumArgs, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001465 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1466 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1467 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
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 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003400
3401 // Check for array bounds violations for each argument to the call. This
3402 // check only triggers warnings when the argument isn't a more complex Expr
3403 // with its own checking, such as a BinaryOperator.
3404 CheckArrayAccess(Arg);
3405
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003406 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003407 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003408
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003409 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003410 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003411
3412 // Assume that extern "C" functions with variadic arguments that
3413 // return __unknown_anytype aren't *really* variadic.
3414 if (Proto->getResultType() == Context.UnknownAnyTy &&
3415 FDecl && FDecl->isExternC()) {
3416 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3417 ExprResult arg;
3418 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3419 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3420 else
3421 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3422 Invalid |= arg.isInvalid();
3423 AllArgs.push_back(arg.take());
3424 }
3425
3426 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3427 } else {
3428 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003429 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3430 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003431 Invalid |= Arg.isInvalid();
3432 AllArgs.push_back(Arg.take());
3433 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003434 }
3435 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003436 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003437}
3438
John McCall2979fe02011-04-12 00:42:48 +00003439/// Given a function expression of unknown-any type, try to rebuild it
3440/// to have a function type.
3441static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3442
Steve Naroff83895f72007-09-16 03:34:24 +00003443/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003444/// This provides the location of the left/right parens and a list of comma
3445/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003446ExprResult
John McCallb268a282010-08-23 23:25:46 +00003447Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003448 MultiExprArg args, SourceLocation RParenLoc,
3449 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003450 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003451
3452 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003453 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003454 if (Result.isInvalid()) return ExprError();
3455 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003456
John McCallb268a282010-08-23 23:25:46 +00003457 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003458
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003459 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003460 // If this is a pseudo-destructor expression, build the call immediately.
3461 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3462 if (NumArgs > 0) {
3463 // Pseudo-destructor calls should not have any arguments.
3464 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003465 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003466 SourceRange(Args[0]->getLocStart(),
3467 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003468
Douglas Gregorad8a3362009-09-04 17:36:40 +00003469 NumArgs = 0;
3470 }
Mike Stump11289f42009-09-09 15:08:12 +00003471
Douglas Gregorad8a3362009-09-04 17:36:40 +00003472 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003473 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003474 }
Mike Stump11289f42009-09-09 15:08:12 +00003475
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003476 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003477 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003478 // FIXME: Will need to cache the results of name lookup (including ADL) in
3479 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003480 bool Dependent = false;
3481 if (Fn->isTypeDependent())
3482 Dependent = true;
3483 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3484 Dependent = true;
3485
Peter Collingbourne41f85462011-02-09 21:07:24 +00003486 if (Dependent) {
3487 if (ExecConfig) {
3488 return Owned(new (Context) CUDAKernelCallExpr(
3489 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3490 Context.DependentTy, VK_RValue, RParenLoc));
3491 } else {
3492 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3493 Context.DependentTy, VK_RValue,
3494 RParenLoc));
3495 }
3496 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003497
3498 // Determine whether this is a call to an object (C++ [over.call.object]).
3499 if (Fn->getType()->isRecordType())
3500 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003501 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003502
John McCall2979fe02011-04-12 00:42:48 +00003503 if (Fn->getType() == Context.UnknownAnyTy) {
3504 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3505 if (result.isInvalid()) return ExprError();
3506 Fn = result.take();
3507 }
3508
John McCall0009fcc2011-04-26 20:42:42 +00003509 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003510 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003511 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003512 }
John McCall0009fcc2011-04-26 20:42:42 +00003513 }
John McCall10eae182009-11-30 22:42:35 +00003514
John McCall0009fcc2011-04-26 20:42:42 +00003515 // Check for overloaded calls. This can happen even in C due to extensions.
3516 if (Fn->getType() == Context.OverloadTy) {
3517 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3518
3519 // We aren't supposed to apply this logic if there's an '&' involved.
3520 if (!find.IsAddressOfOperand) {
3521 OverloadExpr *ovl = find.Expression;
3522 if (isa<UnresolvedLookupExpr>(ovl)) {
3523 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3524 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3525 RParenLoc, ExecConfig);
3526 } else {
John McCall2d74de92009-12-01 22:10:20 +00003527 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003528 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003529 }
3530 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003531 }
3532
Douglas Gregore254f902009-02-04 00:32:51 +00003533 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003534
Eli Friedmane14b1992009-12-26 03:35:45 +00003535 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003536
John McCall57500772009-12-16 12:17:52 +00003537 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003538 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3539 if (UnOp->getOpcode() == UO_AddrOf)
3540 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3541
John McCall57500772009-12-16 12:17:52 +00003542 if (isa<DeclRefExpr>(NakedFn))
3543 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003544 else if (isa<MemberExpr>(NakedFn))
3545 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003546
Peter Collingbourne41f85462011-02-09 21:07:24 +00003547 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3548 ExecConfig);
3549}
3550
3551ExprResult
3552Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3553 MultiExprArg execConfig, SourceLocation GGGLoc) {
3554 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3555 if (!ConfigDecl)
3556 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3557 << "cudaConfigureCall");
3558 QualType ConfigQTy = ConfigDecl->getType();
3559
3560 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3561 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3562
3563 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00003564}
3565
Tanya Lattner55808c12011-06-04 00:47:47 +00003566/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3567///
3568/// __builtin_astype( value, dst type )
3569///
3570ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty,
3571 SourceLocation BuiltinLoc,
3572 SourceLocation RParenLoc) {
3573 ExprValueKind VK = VK_RValue;
3574 ExprObjectKind OK = OK_Ordinary;
3575 QualType DstTy = GetTypeFromParser(destty);
3576 QualType SrcTy = expr->getType();
3577 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3578 return ExprError(Diag(BuiltinLoc,
3579 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003580 << DstTy
3581 << SrcTy
Tanya Lattner55808c12011-06-04 00:47:47 +00003582 << expr->getSourceRange());
Richard Trieucfc491d2011-08-02 04:35:43 +00003583 return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc,
3584 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003585}
3586
John McCall57500772009-12-16 12:17:52 +00003587/// BuildResolvedCallExpr - Build a call to a resolved expression,
3588/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003589/// unary-convert to an expression of function-pointer or
3590/// block-pointer type.
3591///
3592/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003593ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003594Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3595 SourceLocation LParenLoc,
3596 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003597 SourceLocation RParenLoc,
3598 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00003599 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3600
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003601 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003602 ExprResult Result = UsualUnaryConversions(Fn);
3603 if (Result.isInvalid())
3604 return ExprError();
3605 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003606
Chris Lattner08464942007-12-28 05:29:59 +00003607 // Make the call expr early, before semantic checks. This guarantees cleanup
3608 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003609 CallExpr *TheCall;
3610 if (Config) {
3611 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3612 cast<CallExpr>(Config),
3613 Args, NumArgs,
3614 Context.BoolTy,
3615 VK_RValue,
3616 RParenLoc);
3617 } else {
3618 TheCall = new (Context) CallExpr(Context, Fn,
3619 Args, NumArgs,
3620 Context.BoolTy,
3621 VK_RValue,
3622 RParenLoc);
3623 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003624
John McCallbebede42011-02-26 05:39:39 +00003625 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3626
3627 // Bail out early if calling a builtin with custom typechecking.
3628 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3629 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3630
John McCall31996342011-04-07 08:22:57 +00003631 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003632 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003633 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003634 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3635 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003636 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003637 if (FuncT == 0)
3638 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3639 << Fn->getType() << Fn->getSourceRange());
3640 } else if (const BlockPointerType *BPT =
3641 Fn->getType()->getAs<BlockPointerType>()) {
3642 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3643 } else {
John McCall31996342011-04-07 08:22:57 +00003644 // Handle calls to expressions of unknown-any type.
3645 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003646 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003647 if (rewrite.isInvalid()) return ExprError();
3648 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003649 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003650 goto retry;
3651 }
3652
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003653 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3654 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003655 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003656
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003657 if (getLangOptions().CUDA) {
3658 if (Config) {
3659 // CUDA: Kernel calls must be to global functions
3660 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3661 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3662 << FDecl->getName() << Fn->getSourceRange());
3663
3664 // CUDA: Kernel function must have 'void' return type
3665 if (!FuncT->getResultType()->isVoidType())
3666 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3667 << Fn->getType() << Fn->getSourceRange());
3668 }
3669 }
3670
Eli Friedman3164fb12009-03-22 22:00:50 +00003671 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003672 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00003673 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003674 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003675 return ExprError();
3676
Chris Lattner08464942007-12-28 05:29:59 +00003677 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003678 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003679 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003680
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003681 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003682 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003683 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003684 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003685 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003686 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003687
Douglas Gregord8e97de2009-04-02 15:37:10 +00003688 if (FDecl) {
3689 // Check if we have too few/too many template arguments, based
3690 // on our knowledge of the function definition.
3691 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003692 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003693 const FunctionProtoType *Proto
3694 = Def->getType()->getAs<FunctionProtoType>();
3695 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003696 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3697 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003698 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003699
3700 // If the function we're calling isn't a function prototype, but we have
3701 // a function prototype from a prior declaratiom, use that prototype.
3702 if (!FDecl->hasPrototype())
3703 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003704 }
3705
Steve Naroff0b661582007-08-28 23:30:39 +00003706 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003707 for (unsigned i = 0; i != NumArgs; i++) {
3708 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003709
3710 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003711 InitializedEntity Entity
3712 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003713 Proto->getArgType(i),
3714 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003715 ExprResult ArgE = PerformCopyInitialization(Entity,
3716 SourceLocation(),
3717 Owned(Arg));
3718 if (ArgE.isInvalid())
3719 return true;
3720
3721 Arg = ArgE.takeAs<Expr>();
3722
3723 } else {
John Wiegley01296292011-04-08 18:41:53 +00003724 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3725
3726 if (ArgE.isInvalid())
3727 return true;
3728
3729 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003730 }
3731
Douglas Gregor83025412010-10-26 05:45:40 +00003732 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3733 Arg->getType(),
3734 PDiag(diag::err_call_incomplete_argument)
3735 << Arg->getSourceRange()))
3736 return ExprError();
3737
Chris Lattner08464942007-12-28 05:29:59 +00003738 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003739 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003740 }
Chris Lattner08464942007-12-28 05:29:59 +00003741
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003742 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3743 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003744 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3745 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003746
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003747 // Check for sentinels
3748 if (NDecl)
3749 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003750
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003751 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003752 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003753 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003754 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003755
John McCallbebede42011-02-26 05:39:39 +00003756 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003757 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003758 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003759 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003760 return ExprError();
3761 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003762
John McCallb268a282010-08-23 23:25:46 +00003763 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003764}
3765
John McCalldadc5752010-08-24 06:29:42 +00003766ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003767Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003768 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003769 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003770 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003771 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003772
3773 TypeSourceInfo *TInfo;
3774 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3775 if (!TInfo)
3776 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3777
John McCallb268a282010-08-23 23:25:46 +00003778 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003779}
3780
John McCalldadc5752010-08-24 06:29:42 +00003781ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003782Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00003783 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003784 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003785
Eli Friedman37a186d2008-05-20 05:22:08 +00003786 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003787 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3788 PDiag(diag::err_illegal_decl_array_incomplete_type)
3789 << SourceRange(LParenLoc,
3790 literalExpr->getSourceRange().getEnd())))
3791 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00003792 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003793 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3794 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003795 } else if (!literalType->isDependentType() &&
3796 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003797 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003798 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003799 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003800 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003801
Douglas Gregor85dabae2009-12-16 01:38:02 +00003802 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003803 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003804 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00003805 = InitializationKind::CreateCStyleCast(LParenLoc,
3806 SourceRange(LParenLoc, RParenLoc));
Eli Friedmana553d4a2009-12-22 02:35:53 +00003807 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003808 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00003809 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003810 &literalType);
3811 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003812 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00003813 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003814
Chris Lattner79413952008-12-04 23:50:19 +00003815 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003816 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003817 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003818 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003819 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003820
John McCall7decc9e2010-11-18 06:31:45 +00003821 // In C, compound literals are l-values for some reason.
3822 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3823
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00003824 return MaybeBindToTemporary(
3825 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
3826 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003827}
3828
John McCalldadc5752010-08-24 06:29:42 +00003829ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00003830Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003831 SourceLocation RBraceLoc) {
3832 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00003833 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00003834
Steve Naroff30d242c2007-09-15 18:49:24 +00003835 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003836 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003837
Ted Kremenekac034612010-04-13 23:39:13 +00003838 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3839 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003840 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003841 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003842}
3843
John McCalld7646252010-11-14 08:17:51 +00003844/// Prepares for a scalar cast, performing all the necessary stages
3845/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00003846static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00003847 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3848 // Also, callers should have filtered out the invalid cases with
3849 // pointers. Everything else should be possible.
3850
John Wiegley01296292011-04-08 18:41:53 +00003851 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00003852 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00003853 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00003854
John McCall8cb679e2010-11-15 09:13:47 +00003855 switch (SrcTy->getScalarTypeKind()) {
3856 case Type::STK_MemberPointer:
3857 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00003858
John McCall8cb679e2010-11-15 09:13:47 +00003859 case Type::STK_Pointer:
3860 switch (DestTy->getScalarTypeKind()) {
3861 case Type::STK_Pointer:
3862 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00003863 CK_AnyPointerToObjCPointerCast :
3864 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00003865 case Type::STK_Bool:
3866 return CK_PointerToBoolean;
3867 case Type::STK_Integral:
3868 return CK_PointerToIntegral;
3869 case Type::STK_Floating:
3870 case Type::STK_FloatingComplex:
3871 case Type::STK_IntegralComplex:
3872 case Type::STK_MemberPointer:
3873 llvm_unreachable("illegal cast from pointer");
3874 }
3875 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003876
John McCall8cb679e2010-11-15 09:13:47 +00003877 case Type::STK_Bool: // casting from bool is like casting from an integer
3878 case Type::STK_Integral:
3879 switch (DestTy->getScalarTypeKind()) {
3880 case Type::STK_Pointer:
Richard Trieucfc491d2011-08-02 04:35:43 +00003881 if (Src.get()->isNullPointerConstant(S.Context,
3882 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00003883 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00003884 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00003885 case Type::STK_Bool:
3886 return CK_IntegralToBoolean;
3887 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00003888 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00003889 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003890 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003891 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003892 Src = S.ImpCastExprToType(Src.take(),
3893 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003894 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00003895 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003896 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003897 Src = S.ImpCastExprToType(Src.take(),
3898 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003899 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00003900 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003901 case Type::STK_MemberPointer:
3902 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003903 }
3904 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003905
John McCall8cb679e2010-11-15 09:13:47 +00003906 case Type::STK_Floating:
3907 switch (DestTy->getScalarTypeKind()) {
3908 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003909 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00003910 case Type::STK_Bool:
3911 return CK_FloatingToBoolean;
3912 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00003913 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003914 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003915 Src = S.ImpCastExprToType(Src.take(),
3916 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003917 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00003918 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003919 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003920 Src = S.ImpCastExprToType(Src.take(),
3921 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003922 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00003923 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003924 case Type::STK_Pointer:
3925 llvm_unreachable("valid float->pointer cast?");
3926 case Type::STK_MemberPointer:
3927 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003928 }
3929 break;
3930
John McCall8cb679e2010-11-15 09:13:47 +00003931 case Type::STK_FloatingComplex:
3932 switch (DestTy->getScalarTypeKind()) {
3933 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003934 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00003935 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003936 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00003937 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003938 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003939 if (S.Context.hasSameType(ET, DestTy))
3940 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003941 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003942 return CK_FloatingCast;
3943 }
John McCall8cb679e2010-11-15 09:13:47 +00003944 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003945 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003946 case Type::STK_Integral:
Richard Trieucfc491d2011-08-02 04:35:43 +00003947 Src = S.ImpCastExprToType(Src.take(),
3948 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003949 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003950 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003951 case Type::STK_Pointer:
3952 llvm_unreachable("valid complex float->pointer cast?");
3953 case Type::STK_MemberPointer:
3954 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003955 }
3956 break;
3957
John McCall8cb679e2010-11-15 09:13:47 +00003958 case Type::STK_IntegralComplex:
3959 switch (DestTy->getScalarTypeKind()) {
3960 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003961 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003962 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003963 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00003964 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003965 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003966 if (S.Context.hasSameType(ET, DestTy))
3967 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003968 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003969 return CK_IntegralCast;
3970 }
John McCall8cb679e2010-11-15 09:13:47 +00003971 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003972 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003973 case Type::STK_Floating:
Richard Trieucfc491d2011-08-02 04:35:43 +00003974 Src = S.ImpCastExprToType(Src.take(),
3975 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003976 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003977 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003978 case Type::STK_Pointer:
3979 llvm_unreachable("valid complex int->pointer cast?");
3980 case Type::STK_MemberPointer:
3981 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003982 }
3983 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00003984 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003985
John McCalld7646252010-11-14 08:17:51 +00003986 llvm_unreachable("Unhandled scalar cast");
3987 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00003988}
3989
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003990/// CheckCastTypes - Check type constraints for casting between types.
John McCall31168b02011-06-15 23:02:42 +00003991ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyR,
3992 QualType castType, Expr *castExpr,
3993 CastKind& Kind, ExprValueKind &VK,
John Wiegley01296292011-04-08 18:41:53 +00003994 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall31996342011-04-07 08:22:57 +00003995 if (castExpr->getType() == Context.UnknownAnyTy)
3996 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
3997
Sebastian Redl9f831db2009-07-25 15:41:38 +00003998 if (getLangOptions().CPlusPlus)
John McCall31168b02011-06-15 23:02:42 +00003999 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Douglas Gregor15417cf2010-11-03 00:35:38 +00004000 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00004001 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00004002 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00004003
John McCall3aef3d82011-04-10 19:13:55 +00004004 assert(!castExpr->getType()->isPlaceholderType());
4005
John McCall7decc9e2010-11-18 06:31:45 +00004006 // We only support r-value casts in C.
4007 VK = VK_RValue;
4008
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004009 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4010 // type needs to be scalar.
4011 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00004012 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley01296292011-04-08 18:41:53 +00004013 ExprResult castExprRes = IgnoredValueConversions(castExpr);
4014 if (castExprRes.isInvalid())
4015 return ExprError();
4016 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00004017
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004018 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00004019 Kind = CK_ToVoid;
John Wiegley01296292011-04-08 18:41:53 +00004020 return Owned(castExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00004021 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004022
John Wiegley01296292011-04-08 18:41:53 +00004023 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
4024 if (castExprRes.isInvalid())
4025 return ExprError();
4026 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00004027
Eli Friedmane98194d2010-07-17 20:43:49 +00004028 if (RequireCompleteType(TyR.getBegin(), castType,
4029 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00004030 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00004031
Anders Carlssonef918ac2009-10-16 02:35:04 +00004032 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004033 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004034 (castType->isStructureType() || castType->isUnionType())) {
4035 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00004036 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004037 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4038 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004039 Kind = CK_NoOp;
John Wiegley01296292011-04-08 18:41:53 +00004040 return Owned(castExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00004041 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004042
Anders Carlsson525b76b2009-10-16 02:48:28 +00004043 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004044 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004045 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004046 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004047 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004048 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004049 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00004050 castExpr->getType()) &&
4051 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004052 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4053 << castExpr->getSourceRange();
4054 break;
4055 }
4056 }
John Wiegley01296292011-04-08 18:41:53 +00004057 if (Field == FieldEnd) {
4058 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004059 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004060 return ExprError();
4061 }
John McCalle3027922010-08-25 11:45:40 +00004062 Kind = CK_ToUnion;
John Wiegley01296292011-04-08 18:41:53 +00004063 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004064 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004065
Anders Carlsson525b76b2009-10-16 02:48:28 +00004066 // Reject any other conversions to non-scalar types.
John Wiegley01296292011-04-08 18:41:53 +00004067 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlsson525b76b2009-10-16 02:48:28 +00004068 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004069 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004070 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004071
John McCalld7646252010-11-14 08:17:51 +00004072 // The type we're casting to is known to be a scalar or vector.
4073
4074 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004075 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00004076 !castExpr->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004077 Diag(castExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004078 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004079 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004080 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004081 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004082
4083 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00004084 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004085
Anton Yartsev28ccef72011-03-27 09:32:40 +00004086 if (castType->isVectorType()) {
4087 if (castType->getAs<VectorType>()->getVectorKind() ==
4088 VectorType::AltiVecVector &&
4089 (castExpr->getType()->isIntegerType() ||
4090 castExpr->getType()->isFloatingType())) {
4091 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004092 return Owned(castExpr);
4093 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
4094 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00004095 } else
John Wiegley01296292011-04-08 18:41:53 +00004096 return Owned(castExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00004097 }
John Wiegley01296292011-04-08 18:41:53 +00004098 if (castExpr->getType()->isVectorType()) {
4099 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
4100 return ExprError();
4101 else
4102 return Owned(castExpr);
4103 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00004104
John McCalld7646252010-11-14 08:17:51 +00004105 // The source and target types are both scalars, i.e.
4106 // - arithmetic types (fundamental, enum, and complex)
4107 // - all kinds of pointers
4108 // Note that member pointers were filtered out with C++, above.
4109
John Wiegley01296292011-04-08 18:41:53 +00004110 if (isa<ObjCSelectorExpr>(castExpr)) {
4111 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
4112 return ExprError();
4113 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004114
John McCalld7646252010-11-14 08:17:51 +00004115 // If either type is a pointer, the other type has to be either an
4116 // integer or a pointer.
John McCall31168b02011-06-15 23:02:42 +00004117 QualType castExprType = castExpr->getType();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004118 if (!castType->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00004119 if (!castExprType->isIntegralType(Context) &&
John Wiegley01296292011-04-08 18:41:53 +00004120 castExprType->isArithmeticType()) {
4121 Diag(castExpr->getLocStart(),
4122 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004123 << castExprType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004124 return ExprError();
4125 }
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004126 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley01296292011-04-08 18:41:53 +00004127 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
4128 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00004129 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004130 return ExprError();
4131 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004132 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004133
John McCall31168b02011-06-15 23:02:42 +00004134 if (getLangOptions().ObjCAutoRefCount) {
4135 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
4136 CheckObjCARCConversion(SourceRange(CastStartLoc, castExpr->getLocEnd()),
4137 castType, castExpr, CCK_CStyleCast);
4138
4139 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
4140 if (const PointerType *ExprPtr = castExprType->getAs<PointerType>()) {
4141 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4142 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4143 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4144 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4145 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
4146 Diag(castExpr->getLocStart(),
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004147 diag::err_typecheck_incompatible_ownership)
John McCall31168b02011-06-15 23:02:42 +00004148 << castExprType << castType << AA_Casting
4149 << castExpr->getSourceRange();
4150
4151 return ExprError();
4152 }
4153 }
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004154 }
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004155 else if (!CheckObjCARCUnavailableWeakConversion(castType, castExprType)) {
4156 Diag(castExpr->getLocStart(),
Fariborz Jahanianf2913402011-07-08 17:41:42 +00004157 diag::err_arc_convesion_of_weak_unavailable) << 1
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004158 << castExprType << castType
4159 << castExpr->getSourceRange();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004160 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00004161 }
4162 }
4163
John Wiegley01296292011-04-08 18:41:53 +00004164 castExprRes = Owned(castExpr);
4165 Kind = PrepareScalarCast(*this, castExprRes, castType);
4166 if (castExprRes.isInvalid())
4167 return ExprError();
4168 castExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00004169
John McCalld7646252010-11-14 08:17:51 +00004170 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00004171 CheckCastAlign(castExpr, castType, TyR);
4172
John Wiegley01296292011-04-08 18:41:53 +00004173 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004174}
4175
Anders Carlsson525b76b2009-10-16 02:48:28 +00004176bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004177 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004178 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004179
Anders Carlssonde71adf2007-11-27 05:51:55 +00004180 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004181 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004182 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004183 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004184 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004185 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004186 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004187 } else
4188 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004189 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004190 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004191
John McCalle3027922010-08-25 11:45:40 +00004192 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004193 return false;
4194}
4195
John Wiegley01296292011-04-08 18:41:53 +00004196ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4197 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004198 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004199
Anders Carlsson43d70f82009-10-16 05:23:41 +00004200 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004201
Nate Begemanc8961a42009-06-27 22:05:55 +00004202 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4203 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00004204 if (SrcTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004205 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
4206 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004207 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004208 return ExprError();
4209 }
John McCalle3027922010-08-25 11:45:40 +00004210 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004211 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004212 }
4213
Nate Begemanbd956c42009-06-28 02:36:38 +00004214 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004215 // conversion will take place first from scalar to elt type, and then
4216 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004217 if (SrcTy->isPointerType())
4218 return Diag(R.getBegin(),
4219 diag::err_invalid_conversion_between_vector_and_scalar)
4220 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004221
4222 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004223 ExprResult CastExprRes = Owned(CastExpr);
4224 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4225 if (CastExprRes.isInvalid())
4226 return ExprError();
4227 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004228
John McCalle3027922010-08-25 11:45:40 +00004229 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004230 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004231}
4232
John McCalldadc5752010-08-24 06:29:42 +00004233ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004234Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4235 Declarator &D, ParsedType &Ty,
John McCallb268a282010-08-23 23:25:46 +00004236 SourceLocation RParenLoc, Expr *castExpr) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004237 assert(!D.isInvalidType() && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004238 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004239
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004240 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, castExpr->getType());
4241 if (D.isInvalidType())
4242 return ExprError();
4243
4244 if (getLangOptions().CPlusPlus) {
4245 // Check that there are no default arguments (C++ only).
4246 CheckExtraCXXDefaultArguments(D);
4247 }
4248
4249 QualType castType = castTInfo->getType();
4250 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004251
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004252 bool isVectorLiteral = false;
4253
4254 // Check for an altivec or OpenCL literal,
4255 // i.e. all the elements are integer constants.
4256 ParenExpr *PE = dyn_cast<ParenExpr>(castExpr);
4257 ParenListExpr *PLE = dyn_cast<ParenListExpr>(castExpr);
4258 if (getLangOptions().AltiVec && castType->isVectorType() && (PE || PLE)) {
4259 if (PLE && PLE->getNumExprs() == 0) {
4260 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4261 return ExprError();
4262 }
4263 if (PE || PLE->getNumExprs() == 1) {
4264 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4265 if (!E->getType()->isVectorType())
4266 isVectorLiteral = true;
4267 }
4268 else
4269 isVectorLiteral = true;
4270 }
4271
4272 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4273 // then handle it as such.
4274 if (isVectorLiteral)
4275 return BuildVectorLiteral(LParenLoc, RParenLoc, castExpr, castTInfo);
4276
Nate Begeman5ec4b312009-08-10 23:49:36 +00004277 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004278 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4279 // sequence of BinOp comma operators.
4280 if (isa<ParenListExpr>(castExpr)) {
4281 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, castExpr);
4282 if (Result.isInvalid()) return ExprError();
4283 castExpr = Result.take();
4284 }
John McCallebe54742010-01-15 18:56:44 +00004285
John McCallb268a282010-08-23 23:25:46 +00004286 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00004287}
4288
John McCalldadc5752010-08-24 06:29:42 +00004289ExprResult
John McCallebe54742010-01-15 18:56:44 +00004290Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00004291 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00004292 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00004293 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00004294 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00004295 ExprResult CastResult =
John McCall31168b02011-06-15 23:02:42 +00004296 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
4297 castExpr, Kind, VK, BasePath);
John Wiegley01296292011-04-08 18:41:53 +00004298 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004299 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004300 castExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00004301
Richard Trieucfc491d2011-08-02 04:35:43 +00004302 return Owned(CStyleCastExpr::Create(
4303 Context, Ty->getType().getNonLValueExprType(Context), VK, Kind, castExpr,
4304 &BasePath, Ty, LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004305}
4306
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004307ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4308 SourceLocation RParenLoc, Expr *E,
4309 TypeSourceInfo *TInfo) {
4310 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4311 "Expected paren or paren list expression");
4312
4313 Expr **exprs;
4314 unsigned numExprs;
4315 Expr *subExpr;
4316 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4317 exprs = PE->getExprs();
4318 numExprs = PE->getNumExprs();
4319 } else {
4320 subExpr = cast<ParenExpr>(E)->getSubExpr();
4321 exprs = &subExpr;
4322 numExprs = 1;
4323 }
4324
4325 QualType Ty = TInfo->getType();
4326 assert(Ty->isVectorType() && "Expected vector type");
4327
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004328 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004329 const VectorType *VTy = Ty->getAs<VectorType>();
4330 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4331
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004332 // '(...)' form of vector initialization in AltiVec: the number of
4333 // initializers must be one or must match the size of the vector.
4334 // If a single value is specified in the initializer then it will be
4335 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004336 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004337 // The number of initializers must be one or must match the size of the
4338 // vector. If a single value is specified in the initializer then it will
4339 // be replicated to all the components of the vector
4340 if (numExprs == 1) {
4341 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4342 ExprResult Literal = Owned(exprs[0]);
4343 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4344 PrepareScalarCast(*this, Literal, ElemTy));
4345 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4346 }
4347 else if (numExprs < numElems) {
4348 Diag(E->getExprLoc(),
4349 diag::err_incorrect_number_of_vector_initializers);
4350 return ExprError();
4351 }
4352 else
4353 for (unsigned i = 0, e = numExprs; i != e; ++i)
4354 initExprs.push_back(exprs[i]);
4355 }
Tanya Lattner83559382011-07-15 23:07:01 +00004356 else {
4357 // For OpenCL, when the number of initializers is a single value,
4358 // it will be replicated to all components of the vector.
4359 if (getLangOptions().OpenCL &&
4360 VTy->getVectorKind() == VectorType::GenericVector &&
4361 numExprs == 1) {
4362 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4363 ExprResult Literal = Owned(exprs[0]);
4364 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4365 PrepareScalarCast(*this, Literal, ElemTy));
4366 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4367 }
4368
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004369 for (unsigned i = 0, e = numExprs; i != e; ++i)
4370 initExprs.push_back(exprs[i]);
Tanya Lattner83559382011-07-15 23:07:01 +00004371 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004372 // FIXME: This means that pretty-printing the final AST will produce curly
4373 // braces instead of the original commas.
4374 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4375 &initExprs[0],
4376 initExprs.size(), RParenLoc);
4377 initE->setType(Ty);
4378 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4379}
4380
Nate Begeman5ec4b312009-08-10 23:49:36 +00004381/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4382/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004383ExprResult
John McCallb268a282010-08-23 23:25:46 +00004384Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004385 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4386 if (!E)
4387 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00004388
John McCalldadc5752010-08-24 06:29:42 +00004389 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004390
Nate Begeman5ec4b312009-08-10 23:49:36 +00004391 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004392 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4393 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004394
John McCallb268a282010-08-23 23:25:46 +00004395 if (Result.isInvalid()) return ExprError();
4396
4397 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004398}
4399
John McCalldadc5752010-08-24 06:29:42 +00004400ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00004401 SourceLocation R,
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004402 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004403 unsigned nexprs = Val.size();
4404 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004405 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4406 Expr *expr;
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004407 if (nexprs == 1)
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004408 expr = new (Context) ParenExpr(L, R, exprs[0]);
4409 else
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004410 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4411 exprs[nexprs-1]->getType());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004412 return Owned(expr);
4413}
4414
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004415/// \brief Emit a specialized diagnostic when one expression is a null pointer
4416/// constant and the other is not a pointer.
4417bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
4418 SourceLocation QuestionLoc) {
4419 Expr *NullExpr = LHS;
4420 Expr *NonPointerExpr = RHS;
4421 Expr::NullPointerConstantKind NullKind =
4422 NullExpr->isNullPointerConstant(Context,
4423 Expr::NPC_ValueDependentIsNotNull);
4424
4425 if (NullKind == Expr::NPCK_NotNull) {
4426 NullExpr = RHS;
4427 NonPointerExpr = LHS;
4428 NullKind =
4429 NullExpr->isNullPointerConstant(Context,
4430 Expr::NPC_ValueDependentIsNotNull);
4431 }
4432
4433 if (NullKind == Expr::NPCK_NotNull)
4434 return false;
4435
4436 if (NullKind == Expr::NPCK_ZeroInteger) {
4437 // In this case, check to make sure that we got here from a "NULL"
4438 // string in the source code.
4439 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004440 SourceLocation loc = NullExpr->getExprLoc();
4441 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004442 return false;
4443 }
4444
4445 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4446 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4447 << NonPointerExpr->getType() << DiagType
4448 << NonPointerExpr->getSourceRange();
4449 return true;
4450}
4451
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004452/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4453/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004454/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004455QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4456 ExprResult &RHS, ExprValueKind &VK,
4457 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004458 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004459
John McCall3aef3d82011-04-10 19:13:55 +00004460 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00004461 if (!lhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004462 LHS = move(lhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004463
John McCall3aef3d82011-04-10 19:13:55 +00004464 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00004465 if (!rhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004466 RHS = move(rhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004467
Sebastian Redl1a99f442009-04-16 17:51:27 +00004468 // C++ is sufficiently different to merit its own checker.
4469 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004470 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004471
4472 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004473 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004474
John Wiegley01296292011-04-08 18:41:53 +00004475 Cond = UsualUnaryConversions(Cond.take());
4476 if (Cond.isInvalid())
4477 return QualType();
4478 LHS = UsualUnaryConversions(LHS.take());
4479 if (LHS.isInvalid())
4480 return QualType();
4481 RHS = UsualUnaryConversions(RHS.take());
4482 if (RHS.isInvalid())
4483 return QualType();
4484
4485 QualType CondTy = Cond.get()->getType();
4486 QualType LHSTy = LHS.get()->getType();
4487 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004488
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004489 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004490 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00004491 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4492 // Throw an error if its not either.
4493 if (getLangOptions().OpenCL) {
4494 if (!CondTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00004495 Diag(Cond.get()->getLocStart(),
Nate Begemanabb5a732010-09-20 22:41:17 +00004496 diag::err_typecheck_cond_expect_scalar_or_vector)
4497 << CondTy;
4498 return QualType();
4499 }
4500 }
4501 else {
John Wiegley01296292011-04-08 18:41:53 +00004502 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004503 << CondTy;
4504 return QualType();
4505 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004506 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004507
Chris Lattnere2949f42008-01-06 22:42:25 +00004508 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004509 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004510 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004511
Nate Begemanabb5a732010-09-20 22:41:17 +00004512 // OpenCL: If the condition is a vector, and both operands are scalar,
4513 // attempt to implicity convert them to the vector type to act like the
4514 // built in select.
4515 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
4516 // Both operands should be of scalar type.
4517 if (!LHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00004518 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004519 << CondTy;
4520 return QualType();
4521 }
4522 if (!RHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00004523 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00004524 << CondTy;
4525 return QualType();
4526 }
4527 // Implicity convert these scalars to the type of the condition.
John Wiegley01296292011-04-08 18:41:53 +00004528 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4529 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begemanabb5a732010-09-20 22:41:17 +00004530 }
4531
Chris Lattnere2949f42008-01-06 22:42:25 +00004532 // If both operands have arithmetic type, do the usual arithmetic conversions
4533 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004534 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4535 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004536 if (LHS.isInvalid() || RHS.isInvalid())
4537 return QualType();
4538 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004539 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004540
Chris Lattnere2949f42008-01-06 22:42:25 +00004541 // If both operands are the same structure or union type, the result is that
4542 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004543 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4544 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004545 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004546 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004547 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004548 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004549 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004550 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004551
Chris Lattnere2949f42008-01-06 22:42:25 +00004552 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004553 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004554 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4555 if (!LHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00004556 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4557 << RHS.get()->getSourceRange();
Chris Lattner432cff52009-02-18 04:28:32 +00004558 if (!RHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00004559 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
4560 << LHS.get()->getSourceRange();
4561 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
4562 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00004563 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00004564 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00004565 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4566 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00004567 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Richard Trieucfc491d2011-08-02 04:35:43 +00004568 RHS.get()->isNullPointerConstant(Context,
4569 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004570 // promote the null to a pointer.
John Wiegley01296292011-04-08 18:41:53 +00004571 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004572 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004573 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004574 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Richard Trieucfc491d2011-08-02 04:35:43 +00004575 LHS.get()->isNullPointerConstant(Context,
4576 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00004577 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00004578 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00004579 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004580
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004581 // All objective-c pointer type analysis is done here.
4582 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4583 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004584 if (LHS.isInvalid() || RHS.isInvalid())
4585 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004586 if (!compositeType.isNull())
4587 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004588
4589
Steve Naroff05efa972009-07-01 14:36:47 +00004590 // Handle block pointer types.
4591 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4592 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4593 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4594 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004595 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4596 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004597 return destType;
4598 }
4599 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004600 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4601 << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004602 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00004603 }
Steve Naroff05efa972009-07-01 14:36:47 +00004604 // We have 2 block pointer types.
4605 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4606 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00004607 return LHSTy;
4608 }
Steve Naroff05efa972009-07-01 14:36:47 +00004609 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004610 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4611 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004612
Steve Naroff05efa972009-07-01 14:36:47 +00004613 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4614 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00004615 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00004616 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4617 << RHS.get()->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00004618 // In this situation, we assume void* type. No especially good
4619 // reason, but this is what gcc does, and we do have to pick
4620 // to get a consistent AST.
4621 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004622 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4623 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00004624 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004625 }
Steve Naroff05efa972009-07-01 14:36:47 +00004626 // The block pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004627 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4628 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00004629 return LHSTy;
4630 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004631
Steve Naroff05efa972009-07-01 14:36:47 +00004632 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4633 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4634 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004635 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4636 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00004637
4638 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4639 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4640 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00004641 QualType destPointee
4642 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004643 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004644 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004645 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004646 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004647 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004648 return destType;
4649 }
4650 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004651 QualType destPointee
4652 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004653 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004654 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004655 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004656 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004657 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004658 return destType;
4659 }
4660
4661 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4662 // Two identical pointer types are always compatible.
4663 return LHSTy;
4664 }
4665 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4666 rhptee.getUnqualifiedType())) {
4667 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00004668 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4669 << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00004670 // In this situation, we assume void* type. No especially good
4671 // reason, but this is what gcc does, and we do have to pick
4672 // to get a consistent AST.
4673 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00004674 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4675 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004676 return incompatTy;
4677 }
4678 // The pointer types are compatible.
4679 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4680 // differently qualified versions of compatible types, the result type is
4681 // a pointer to an appropriately qualified version of the *composite*
4682 // type.
4683 // FIXME: Need to calculate the composite type.
4684 // FIXME: Need to add qualifiers
John Wiegley01296292011-04-08 18:41:53 +00004685 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4686 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004687 return LHSTy;
4688 }
Mike Stump11289f42009-09-09 15:08:12 +00004689
John McCalle84af4e2010-11-13 01:35:44 +00004690 // GCC compatibility: soften pointer/integer mismatch. Note that
4691 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00004692 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4693 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
Richard Trieucfc491d2011-08-02 04:35:43 +00004694 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4695 << RHS.get()->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004696 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004697 return RHSTy;
4698 }
4699 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4700 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
Richard Trieucfc491d2011-08-02 04:35:43 +00004701 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4702 << RHS.get()->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004703 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004704 return LHSTy;
4705 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00004706
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004707 // Emit a better diagnostic if one of the expressions is a null pointer
4708 // constant and the other is not a pointer type. In this case, the user most
4709 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004710 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004711 return QualType();
4712
Chris Lattnere2949f42008-01-06 22:42:25 +00004713 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004714 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004715 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4716 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004717 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004718}
4719
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004720/// FindCompositeObjCPointerType - Helper method to find composite type of
4721/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004722QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00004723 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004724 QualType LHSTy = LHS.get()->getType();
4725 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004726
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004727 // Handle things like Class and struct objc_class*. Here we case the result
4728 // to the pseudo-builtin, because that will be implicitly cast back to the
4729 // redefinition type if an attempt is made to access its fields.
4730 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00004731 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004732 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004733 return LHSTy;
4734 }
4735 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00004736 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004737 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004738 return RHSTy;
4739 }
4740 // And the same for struct objc_object* / id
4741 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00004742 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004743 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004744 return LHSTy;
4745 }
4746 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00004747 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004748 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004749 return RHSTy;
4750 }
4751 // And the same for struct objc_selector* / SEL
4752 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00004753 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004754 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004755 return LHSTy;
4756 }
4757 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00004758 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00004759 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004760 return RHSTy;
4761 }
4762 // Check constraints for Objective-C object pointers types.
4763 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004764
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004765 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4766 // Two identical object pointer types are always compatible.
4767 return LHSTy;
4768 }
4769 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4770 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4771 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004772
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004773 // If both operands are interfaces and either operand can be
4774 // assigned to the other, use that type as the composite
4775 // type. This allows
4776 // xxx ? (A*) a : (B*) b
4777 // where B is a subclass of A.
4778 //
4779 // Additionally, as for assignment, if either type is 'id'
4780 // allow silent coercion. Finally, if the types are
4781 // incompatible then make sure to use 'id' as the composite
4782 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004783
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004784 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4785 // It could return the composite type.
4786 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4787 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4788 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4789 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4790 } else if ((LHSTy->isObjCQualifiedIdType() ||
4791 RHSTy->isObjCQualifiedIdType()) &&
4792 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4793 // Need to handle "id<xx>" explicitly.
4794 // GCC allows qualified id and any Objective-C type to devolve to
4795 // id. Currently localizing to here until clear this should be
4796 // part of ObjCQualifiedIdTypesAreCompatible.
4797 compositeType = Context.getObjCIdType();
4798 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4799 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004800 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004801 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4802 ;
4803 else {
4804 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4805 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004806 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004807 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004808 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4809 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004810 return incompatTy;
4811 }
4812 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004813 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4814 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004815 return compositeType;
4816 }
4817 // Check Objective-C object pointer types and 'void *'
4818 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4819 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4820 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4821 QualType destPointee
4822 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4823 QualType destType = Context.getPointerType(destPointee);
4824 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004825 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004826 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004827 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004828 return destType;
4829 }
4830 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4831 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4832 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4833 QualType destPointee
4834 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4835 QualType destType = Context.getPointerType(destPointee);
4836 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004837 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004838 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004839 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004840 return destType;
4841 }
4842 return QualType();
4843}
4844
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004845/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004846/// ParenRange in parentheses.
4847static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004848 const PartialDiagnostic &Note,
4849 SourceRange ParenRange) {
4850 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4851 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4852 EndLoc.isValid()) {
4853 Self.Diag(Loc, Note)
4854 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4855 << FixItHint::CreateInsertion(EndLoc, ")");
4856 } else {
4857 // We can't display the parentheses, so just show the bare note.
4858 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004859 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004860}
4861
4862static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4863 return Opc >= BO_Mul && Opc <= BO_Shr;
4864}
4865
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004866/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4867/// expression, either using a built-in or overloaded operator,
4868/// and sets *OpCode to the opcode and *RHS to the right-hand side expression.
4869static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
4870 Expr **RHS) {
4871 E = E->IgnoreParenImpCasts();
4872 E = E->IgnoreConversionOperator();
4873 E = E->IgnoreParenImpCasts();
4874
4875 // Built-in binary operator.
4876 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4877 if (IsArithmeticOp(OP->getOpcode())) {
4878 *Opcode = OP->getOpcode();
4879 *RHS = OP->getRHS();
4880 return true;
4881 }
4882 }
4883
4884 // Overloaded operator.
4885 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4886 if (Call->getNumArgs() != 2)
4887 return false;
4888
4889 // Make sure this is really a binary operator that is safe to pass into
4890 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4891 OverloadedOperatorKind OO = Call->getOperator();
4892 if (OO < OO_Plus || OO > OO_Arrow)
4893 return false;
4894
4895 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4896 if (IsArithmeticOp(OpKind)) {
4897 *Opcode = OpKind;
4898 *RHS = Call->getArg(1);
4899 return true;
4900 }
4901 }
4902
4903 return false;
4904}
4905
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004906static bool IsLogicOp(BinaryOperatorKind Opc) {
4907 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4908}
4909
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004910/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4911/// or is a logical expression such as (x==y) which has int type, but is
4912/// commonly interpreted as boolean.
4913static bool ExprLooksBoolean(Expr *E) {
4914 E = E->IgnoreParenImpCasts();
4915
4916 if (E->getType()->isBooleanType())
4917 return true;
4918 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4919 return IsLogicOp(OP->getOpcode());
4920 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4921 return OP->getOpcode() == UO_LNot;
4922
4923 return false;
4924}
4925
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004926/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4927/// and binary operator are mixed in a way that suggests the programmer assumed
4928/// the conditional operator has higher precedence, for example:
4929/// "int x = a + someBinaryCondition ? 1 : 2".
4930static void DiagnoseConditionalPrecedence(Sema &Self,
4931 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004932 Expr *Condition,
4933 Expr *LHS,
4934 Expr *RHS) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004935 BinaryOperatorKind CondOpcode;
4936 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004937
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004938 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004939 return;
4940 if (!ExprLooksBoolean(CondRHS))
4941 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004942
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004943 // The condition is an arithmetic binary expression, with a right-
4944 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004945
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004946 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004947 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004948 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004949
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004950 SuggestParentheses(Self, OpLoc,
4951 Self.PDiag(diag::note_precedence_conditional_silence)
4952 << BinaryOperator::getOpcodeStr(CondOpcode),
4953 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00004954
4955 SuggestParentheses(Self, OpLoc,
4956 Self.PDiag(diag::note_precedence_conditional_first),
4957 SourceRange(CondRHS->getLocStart(), RHS->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004958}
4959
Steve Naroff83895f72007-09-16 03:34:24 +00004960/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004961/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00004962ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00004963 SourceLocation ColonLoc,
4964 Expr *CondExpr, Expr *LHSExpr,
4965 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00004966 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4967 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00004968 OpaqueValueExpr *opaqueValue = 0;
4969 Expr *commonExpr = 0;
4970 if (LHSExpr == 0) {
4971 commonExpr = CondExpr;
4972
4973 // We usually want to apply unary conversions *before* saving, except
4974 // in the special case of a C++ l-value conditional.
4975 if (!(getLangOptions().CPlusPlus
4976 && !commonExpr->isTypeDependent()
4977 && commonExpr->getValueKind() == RHSExpr->getValueKind()
4978 && commonExpr->isGLValue()
4979 && commonExpr->isOrdinaryOrBitFieldObject()
4980 && RHSExpr->isOrdinaryOrBitFieldObject()
4981 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004982 ExprResult commonRes = UsualUnaryConversions(commonExpr);
4983 if (commonRes.isInvalid())
4984 return ExprError();
4985 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00004986 }
4987
4988 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
4989 commonExpr->getType(),
4990 commonExpr->getValueKind(),
4991 commonExpr->getObjectKind());
4992 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00004993 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00004994
John McCall7decc9e2010-11-18 06:31:45 +00004995 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004996 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00004997 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
4998 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00004999 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005000 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5001 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005002 return ExprError();
5003
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005004 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5005 RHS.get());
5006
John McCallc07a0c72011-02-17 10:25:35 +00005007 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005008 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5009 LHS.take(), ColonLoc,
5010 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005011
5012 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005013 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005014 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5015 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005016}
5017
John McCallaba90822011-01-31 23:13:11 +00005018// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005019// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005020// routine is it effectively iqnores the qualifiers on the top level pointee.
5021// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5022// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005023static Sema::AssignConvertType
5024checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5025 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5026 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005027
Steve Naroff1f4d7272007-05-11 04:00:31 +00005028 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005029 const Type *lhptee, *rhptee;
5030 Qualifiers lhq, rhq;
5031 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5032 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005033
John McCallaba90822011-01-31 23:13:11 +00005034 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005035
5036 // C99 6.5.16.1p1: This following citation is common to constraints
5037 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5038 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005039 Qualifiers lq;
5040
John McCall31168b02011-06-15 23:02:42 +00005041 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5042 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5043 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5044 // Ignore lifetime for further calculation.
5045 lhq.removeObjCLifetime();
5046 rhq.removeObjCLifetime();
5047 }
5048
John McCall4fff8f62011-02-01 00:10:29 +00005049 if (!lhq.compatiblyIncludes(rhq)) {
5050 // Treat address-space mismatches as fatal. TODO: address subspaces
5051 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5052 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5053
John McCall31168b02011-06-15 23:02:42 +00005054 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005055 // and from void*.
John McCall31168b02011-06-15 23:02:42 +00005056 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5057 .compatiblyIncludes(
5058 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall78535952011-03-26 02:56:45 +00005059 && (lhptee->isVoidType() || rhptee->isVoidType()))
5060 ; // keep old
5061
John McCall31168b02011-06-15 23:02:42 +00005062 // Treat lifetime mismatches as fatal.
5063 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5064 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5065
John McCall4fff8f62011-02-01 00:10:29 +00005066 // For GCC compatibility, other qualifier mismatches are treated
5067 // as still compatible in C.
5068 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5069 }
Steve Naroff3f597292007-05-11 22:18:03 +00005070
Mike Stump4e1f26a2009-02-19 03:04:26 +00005071 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5072 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005073 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005074 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005075 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005076 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005077
Chris Lattner0a788432008-01-03 22:56:36 +00005078 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005079 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005080 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005081 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005082
Chris Lattner0a788432008-01-03 22:56:36 +00005083 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005084 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005085 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005086
5087 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005088 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005089 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005090 }
John McCall4fff8f62011-02-01 00:10:29 +00005091
Mike Stump4e1f26a2009-02-19 03:04:26 +00005092 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005093 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005094 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5095 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005096 // Check if the pointee types are compatible ignoring the sign.
5097 // We explicitly check for char so that we catch "char" vs
5098 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005099 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005100 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005101 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005102 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005103
Chris Lattnerec3a1562009-10-17 20:33:28 +00005104 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005105 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005106 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005107 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005108
John McCall4fff8f62011-02-01 00:10:29 +00005109 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005110 // Types are compatible ignoring the sign. Qualifier incompatibility
5111 // takes priority over sign incompatibility because the sign
5112 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005113 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005114 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005115
John McCallaba90822011-01-31 23:13:11 +00005116 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005117 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005118
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005119 // If we are a multi-level pointer, it's possible that our issue is simply
5120 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5121 // the eventual target type is the same and the pointers have the same
5122 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005123 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005124 do {
John McCall4fff8f62011-02-01 00:10:29 +00005125 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5126 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005127 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005128
John McCall4fff8f62011-02-01 00:10:29 +00005129 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005130 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005131 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005132
Eli Friedman80160bd2009-03-22 23:59:44 +00005133 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005134 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005135 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005136 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005137}
5138
John McCallaba90822011-01-31 23:13:11 +00005139/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005140/// block pointer types are compatible or whether a block and normal pointer
5141/// are compatible. It is more restrict than comparing two function pointer
5142// types.
John McCallaba90822011-01-31 23:13:11 +00005143static Sema::AssignConvertType
5144checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5145 QualType rhsType) {
5146 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5147 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5148
Steve Naroff081c7422008-09-04 15:10:53 +00005149 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005150
Steve Naroff081c7422008-09-04 15:10:53 +00005151 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00005152 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5153 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005154
John McCallaba90822011-01-31 23:13:11 +00005155 // In C++, the types have to match exactly.
5156 if (S.getLangOptions().CPlusPlus)
5157 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005158
John McCallaba90822011-01-31 23:13:11 +00005159 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005160
Steve Naroff081c7422008-09-04 15:10:53 +00005161 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005162 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5163 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005164
John McCallaba90822011-01-31 23:13:11 +00005165 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5166 return Sema::IncompatibleBlockPointer;
5167
Steve Naroff081c7422008-09-04 15:10:53 +00005168 return ConvTy;
5169}
5170
John McCallaba90822011-01-31 23:13:11 +00005171/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005172/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005173static Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005174checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType,
5175 QualType rhsType) {
John McCallaba90822011-01-31 23:13:11 +00005176 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5177 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5178
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005179 if (lhsType->isObjCBuiltinType()) {
5180 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005181 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5182 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005183 return Sema::IncompatiblePointer;
5184 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005185 }
5186 if (rhsType->isObjCBuiltinType()) {
5187 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00005188 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5189 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005190 return Sema::IncompatiblePointer;
5191 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005192 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005193 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005194 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005195 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005196 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005197
John McCallaba90822011-01-31 23:13:11 +00005198 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5199 return Sema::CompatiblePointerDiscardsQualifiers;
5200
5201 if (S.Context.typesAreCompatible(lhsType, rhsType))
5202 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005203 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005204 return Sema::IncompatibleObjCQualifiedId;
5205 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005206}
5207
John McCall29600e12010-11-16 02:32:08 +00005208Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005209Sema::CheckAssignmentConstraints(SourceLocation Loc,
5210 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00005211 // Fake up an opaque expression. We don't actually care about what
5212 // cast operations are required, so if CheckAssignmentConstraints
5213 // adds casts to this they'll be wasted, but fortunately that doesn't
5214 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00005215 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00005216 ExprResult rhsPtr = &rhs;
John McCall29600e12010-11-16 02:32:08 +00005217 CastKind K = CK_Invalid;
5218
5219 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5220}
5221
Mike Stump4e1f26a2009-02-19 03:04:26 +00005222/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5223/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005224/// pointers. Here are some objectionable examples that GCC considers warnings:
5225///
5226/// int a, *pint;
5227/// short *pshort;
5228/// struct foo *pfoo;
5229///
5230/// pint = pshort; // warning: assignment from incompatible pointer type
5231/// a = pint; // warning: assignment makes integer from pointer without a cast
5232/// pint = a; // warning: assignment makes pointer from integer without a cast
5233/// pint = pfoo; // warning: assignment from incompatible pointer type
5234///
5235/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005236/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005237///
John McCall8cb679e2010-11-15 09:13:47 +00005238/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005239Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005240Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCall8cb679e2010-11-15 09:13:47 +00005241 CastKind &Kind) {
John Wiegley01296292011-04-08 18:41:53 +00005242 QualType rhsType = rhs.get()->getType();
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005243 QualType origLhsType = lhsType;
John McCall29600e12010-11-16 02:32:08 +00005244
Chris Lattnera52c2f22008-01-04 23:18:45 +00005245 // Get canonical types. We're not formatting these types, just comparing
5246 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00005247 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5248 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005249
John McCalle5255932011-01-31 22:28:28 +00005250 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00005251 if (lhsType == rhsType) {
5252 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005253 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005254 }
5255
Douglas Gregor6b754842008-10-28 00:22:11 +00005256 // If the left-hand side is a reference type, then we are in a
5257 // (rare!) case where we've allowed the use of references in C,
5258 // e.g., as a parameter type in a built-in function. In this case,
5259 // just make sure that the type referenced is compatible with the
5260 // right-hand side type. The caller is responsible for adjusting
5261 // lhsType so that the resulting expression does not have reference
5262 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005263 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00005264 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5265 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005266 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005267 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005268 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005269 }
John McCalle5255932011-01-31 22:28:28 +00005270
Nate Begemanbd956c42009-06-28 02:36:38 +00005271 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5272 // to the same ExtVector type.
5273 if (lhsType->isExtVectorType()) {
5274 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005275 return Incompatible;
5276 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005277 // CK_VectorSplat does T -> vector T, so first cast to the
5278 // element type.
5279 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5280 if (elType != rhsType) {
5281 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley01296292011-04-08 18:41:53 +00005282 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005283 }
5284 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005285 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005286 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005287 }
Mike Stump11289f42009-09-09 15:08:12 +00005288
John McCalle5255932011-01-31 22:28:28 +00005289 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00005290 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005291 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005292 // Allow assignments of an AltiVec vector type to an equivalent GCC
5293 // vector type and vice versa
5294 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5295 Kind = CK_BitCast;
5296 return Compatible;
5297 }
5298
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005299 // If we are allowing lax vector conversions, and LHS and RHS are both
5300 // vectors, the total size only needs to be the same. This is a bitcast;
5301 // no bits are changed but the result type is different.
5302 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00005303 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00005304 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005305 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005306 }
Chris Lattner881a2122008-01-04 23:32:24 +00005307 }
5308 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005309 }
Eli Friedman3360d892008-05-30 18:07:22 +00005310
John McCalle5255932011-01-31 22:28:28 +00005311 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00005312 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00005313 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00005314 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005315 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005316 }
Eli Friedman3360d892008-05-30 18:07:22 +00005317
John McCalle5255932011-01-31 22:28:28 +00005318 // Conversions to normal pointers.
5319 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5320 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00005321 if (isa<PointerType>(rhsType)) {
5322 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00005323 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00005324 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005325
John McCalle5255932011-01-31 22:28:28 +00005326 // int -> T*
5327 if (rhsType->isIntegerType()) {
5328 Kind = CK_IntegralToPointer; // FIXME: null?
5329 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005330 }
John McCalle5255932011-01-31 22:28:28 +00005331
5332 // C pointers are not compatible with ObjC object pointers,
5333 // with two exceptions:
5334 if (isa<ObjCObjectPointerType>(rhsType)) {
5335 // - conversions to void*
5336 if (lhsPointer->getPointeeType()->isVoidType()) {
5337 Kind = CK_AnyPointerToObjCPointerCast;
5338 return Compatible;
5339 }
5340
5341 // - conversions from 'Class' to the redefinition type
5342 if (rhsType->isObjCClassType() &&
5343 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005344 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005345 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005346 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005347
John McCalle5255932011-01-31 22:28:28 +00005348 Kind = CK_BitCast;
5349 return IncompatiblePointer;
5350 }
5351
5352 // U^ -> void*
5353 if (rhsType->getAs<BlockPointerType>()) {
5354 if (lhsPointer->getPointeeType()->isVoidType()) {
5355 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005356 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005357 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005358 }
John McCalle5255932011-01-31 22:28:28 +00005359
Steve Naroff081c7422008-09-04 15:10:53 +00005360 return Incompatible;
5361 }
5362
John McCalle5255932011-01-31 22:28:28 +00005363 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00005364 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005365 // U^ -> T^
5366 if (rhsType->isBlockPointerType()) {
5367 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00005368 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00005369 }
5370
5371 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005372 if (rhsType->isIntegerType()) {
5373 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005374 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005375 }
5376
John McCalle5255932011-01-31 22:28:28 +00005377 // id -> T^
5378 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5379 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005380 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005381 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005382
John McCalle5255932011-01-31 22:28:28 +00005383 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00005384 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005385 if (RHSPT->getPointeeType()->isVoidType()) {
5386 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005387 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005388 }
John McCall8cb679e2010-11-15 09:13:47 +00005389
Chris Lattnera52c2f22008-01-04 23:18:45 +00005390 return Incompatible;
5391 }
5392
John McCalle5255932011-01-31 22:28:28 +00005393 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005394 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005395 // A* -> B*
5396 if (rhsType->isObjCObjectPointerType()) {
5397 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005398 Sema::AssignConvertType result =
5399 checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
5400 if (getLangOptions().ObjCAutoRefCount &&
5401 result == Compatible &&
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005402 !CheckObjCARCUnavailableWeakConversion(origLhsType, rhsType))
5403 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005404 return result;
John McCalle5255932011-01-31 22:28:28 +00005405 }
5406
5407 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00005408 if (rhsType->isIntegerType()) {
5409 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005410 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005411 }
5412
John McCalle5255932011-01-31 22:28:28 +00005413 // In general, C pointers are not compatible with ObjC object pointers,
5414 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00005415 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005416 // - conversions from 'void*'
5417 if (rhsType->isVoidPointerType()) {
5418 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005419 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005420 }
5421
5422 // - conversions to 'Class' from its redefinition type
5423 if (lhsType->isObjCClassType() &&
5424 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
5425 Kind = CK_BitCast;
5426 return Compatible;
5427 }
5428
5429 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00005430 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005431 }
John McCalle5255932011-01-31 22:28:28 +00005432
5433 // T^ -> A*
5434 if (rhsType->isBlockPointerType()) {
5435 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005436 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005437 }
5438
Steve Naroff7cae42b2009-07-10 23:34:53 +00005439 return Incompatible;
5440 }
John McCalle5255932011-01-31 22:28:28 +00005441
5442 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00005443 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005444 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005445 if (lhsType == Context.BoolTy) {
5446 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005447 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005448 }
Eli Friedman3360d892008-05-30 18:07:22 +00005449
John McCalle5255932011-01-31 22:28:28 +00005450 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005451 if (lhsType->isIntegerType()) {
5452 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005453 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005454 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005455
Chris Lattnera52c2f22008-01-04 23:18:45 +00005456 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005457 }
John McCalle5255932011-01-31 22:28:28 +00005458
5459 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005460 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00005461 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00005462 if (lhsType == Context.BoolTy) {
5463 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005464 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005465 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005466
John McCalle5255932011-01-31 22:28:28 +00005467 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00005468 if (lhsType->isIntegerType()) {
5469 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005470 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005471 }
5472
Steve Naroff7cae42b2009-07-10 23:34:53 +00005473 return Incompatible;
5474 }
Eli Friedman3360d892008-05-30 18:07:22 +00005475
John McCalle5255932011-01-31 22:28:28 +00005476 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00005477 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005478 if (Context.typesAreCompatible(lhsType, rhsType)) {
5479 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005480 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005481 }
Bill Wendling216423b2007-05-30 06:30:29 +00005482 }
John McCalle5255932011-01-31 22:28:28 +00005483
Steve Naroff98cf3e92007-06-06 18:38:38 +00005484 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005485}
5486
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005487/// \brief Constructs a transparent union from an expression that is
5488/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005489static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5490 ExprResult &EResult, QualType UnionType,
5491 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005492 // Build an initializer list that designates the appropriate member
5493 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005494 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005495 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005496 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005497 SourceLocation());
5498 Initializer->setType(UnionType);
5499 Initializer->setInitializedFieldInUnion(Field);
5500
5501 // Build a compound literal constructing a value of the transparent
5502 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005503 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005504 EResult = S.Owned(
5505 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5506 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005507}
5508
5509Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005510Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
5511 ExprResult &rExpr) {
John Wiegley01296292011-04-08 18:41:53 +00005512 QualType FromType = rExpr.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005513
Mike Stump11289f42009-09-09 15:08:12 +00005514 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005515 // transparent_union GCC extension.
5516 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005517 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005518 return Incompatible;
5519
5520 // The field to initialize within the transparent union.
5521 RecordDecl *UD = UT->getDecl();
5522 FieldDecl *InitField = 0;
5523 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005524 for (RecordDecl::field_iterator it = UD->field_begin(),
5525 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005526 it != itend; ++it) {
5527 if (it->getType()->isPointerType()) {
5528 // If the transparent union contains a pointer type, we allow:
5529 // 1) void pointer
5530 // 2) null pointer constant
5531 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005532 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley01296292011-04-08 18:41:53 +00005533 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005534 InitField = *it;
5535 break;
5536 }
Mike Stump11289f42009-09-09 15:08:12 +00005537
John Wiegley01296292011-04-08 18:41:53 +00005538 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00005539 Expr::NPC_ValueDependentIsNull)) {
Richard Trieucfc491d2011-08-02 04:35:43 +00005540 rExpr = ImpCastExprToType(rExpr.take(), it->getType(),
5541 CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005542 InitField = *it;
5543 break;
5544 }
5545 }
5546
John McCall8cb679e2010-11-15 09:13:47 +00005547 CastKind Kind = CK_Invalid;
John Wiegley01296292011-04-08 18:41:53 +00005548 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005549 == Compatible) {
John Wiegley01296292011-04-08 18:41:53 +00005550 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005551 InitField = *it;
5552 break;
5553 }
5554 }
5555
5556 if (!InitField)
5557 return Incompatible;
5558
John Wiegley01296292011-04-08 18:41:53 +00005559 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005560 return Compatible;
5561}
5562
Chris Lattner9bad62c2008-01-04 18:04:52 +00005563Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00005564Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005565 if (getLangOptions().CPlusPlus) {
5566 if (!lhsType->isRecordType()) {
5567 // C++ 5.17p3: If the left operand is not of class type, the
5568 // expression is implicitly converted (C++ 4) to the
5569 // cv-unqualified type of the left operand.
John Wiegley01296292011-04-08 18:41:53 +00005570 ExprResult Res = PerformImplicitConversion(rExpr.get(),
5571 lhsType.getUnqualifiedType(),
5572 AA_Assigning);
5573 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005574 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005575 Sema::AssignConvertType result = Compatible;
5576 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieucfc491d2011-08-02 04:35:43 +00005577 !CheckObjCARCUnavailableWeakConversion(lhsType,
5578 rExpr.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005579 result = IncompatibleObjCWeakRef;
John Wiegley01296292011-04-08 18:41:53 +00005580 rExpr = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005581 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005582 }
5583
5584 // FIXME: Currently, we fall through and treat C++ classes like C
5585 // structures.
John McCall34376a62010-12-04 03:47:34 +00005586 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005587
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005588 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5589 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00005590 if ((lhsType->isPointerType() ||
5591 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00005592 lhsType->isBlockPointerType())
John Wiegley01296292011-04-08 18:41:53 +00005593 && rExpr.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005594 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00005595 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005596 return Compatible;
5597 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005598
Chris Lattnere6dcd502007-10-16 02:55:40 +00005599 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005600 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005601 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005602 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005603 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005604 // Suppress this for references: C++ 8.5.3p5.
John Wiegley01296292011-04-08 18:41:53 +00005605 if (!lhsType->isReferenceType()) {
5606 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
5607 if (rExpr.isInvalid())
5608 return Incompatible;
5609 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005610
John McCall8cb679e2010-11-15 09:13:47 +00005611 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005612 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00005613 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005614
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005615 // C99 6.5.16.1p2: The value of the right operand is converted to the
5616 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005617 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5618 // so that we can use references in built-in functions even in C.
5619 // The getNonReferenceType() call makes sure that the resulting expression
5620 // does not have reference type.
John Wiegley01296292011-04-08 18:41:53 +00005621 if (result != Incompatible && rExpr.get()->getType() != lhsType)
Richard Trieucfc491d2011-08-02 04:35:43 +00005622 rExpr = ImpCastExprToType(rExpr.take(),
5623 lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005624 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005625}
5626
Richard Trieucfc491d2011-08-02 04:35:43 +00005627QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex,
5628 ExprResult &rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005629 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley01296292011-04-08 18:41:53 +00005630 << lex.get()->getType() << rex.get()->getType()
5631 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005632 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005633}
5634
Eli Friedman1408bc92011-06-23 18:10:35 +00005635QualType Sema::CheckVectorOperands(ExprResult &lex, ExprResult &rex,
5636 SourceLocation Loc, bool isCompAssign) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005637 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005638 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00005639 QualType lhsType =
John Wiegley01296292011-04-08 18:41:53 +00005640 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattner574dee62008-07-26 22:17:49 +00005641 QualType rhsType =
John Wiegley01296292011-04-08 18:41:53 +00005642 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005643
Nate Begeman191a6b12008-07-14 18:02:46 +00005644 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005645 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00005646 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005647
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005648 // Handle the case of equivalent AltiVec and GCC vector types
5649 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5650 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005651 if (lhsType->isExtVectorType()) {
5652 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5653 return lhsType;
5654 }
5655
5656 if (!isCompAssign)
5657 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005658 return rhsType;
5659 }
5660
Eli Friedman1408bc92011-06-23 18:10:35 +00005661 if (getLangOptions().LaxVectorConversions &&
5662 Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) {
5663 // If we are allowing lax vector conversions, and LHS and RHS are both
5664 // vectors, the total size only needs to be the same. This is a
5665 // bitcast; no bits are changed but the result type is different.
5666 // FIXME: Should we really be allowing this?
5667 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
5668 return lhsType;
5669 }
5670
Nate Begemanbd956c42009-06-28 02:36:38 +00005671 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5672 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5673 bool swapped = false;
Eli Friedman1408bc92011-06-23 18:10:35 +00005674 if (rhsType->isExtVectorType() && !isCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005675 swapped = true;
5676 std::swap(rex, lex);
5677 std::swap(rhsType, lhsType);
5678 }
Mike Stump11289f42009-09-09 15:08:12 +00005679
Nate Begeman886448d2009-06-28 19:12:57 +00005680 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00005681 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005682 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005683 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00005684 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5685 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00005686 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005687 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00005688 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005689 if (swapped) std::swap(rex, lex);
5690 return lhsType;
5691 }
5692 }
5693 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5694 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005695 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5696 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00005697 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005698 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00005699 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00005700 if (swapped) std::swap(rex, lex);
5701 return lhsType;
5702 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005703 }
5704 }
Mike Stump11289f42009-09-09 15:08:12 +00005705
Nate Begeman886448d2009-06-28 19:12:57 +00005706 // Vectors of different size or scalar and non-ext-vector are errors.
Eli Friedman1408bc92011-06-23 18:10:35 +00005707 if (swapped) std::swap(rex, lex);
Chris Lattner377d1f82008-11-18 22:52:51 +00005708 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley01296292011-04-08 18:41:53 +00005709 << lex.get()->getType() << rex.get()->getType()
5710 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005711 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005712}
5713
Richard Trieucfc491d2011-08-02 04:35:43 +00005714QualType Sema::CheckMultiplyDivideOperands(ExprResult &lex, ExprResult &rex,
5715 SourceLocation Loc,
5716 bool isCompAssign, bool isDiv) {
5717 if (lex.get()->getType()->isVectorType() ||
5718 rex.get()->getType()->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00005719 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005720
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005721 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00005722 if (lex.isInvalid() || rex.isInvalid())
5723 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005724
John Wiegley01296292011-04-08 18:41:53 +00005725 if (!lex.get()->getType()->isArithmeticType() ||
5726 !rex.get()->getType()->isArithmeticType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00005727 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005728
Chris Lattnerfaa54172010-01-12 21:23:57 +00005729 // Check for division by zero.
5730 if (isDiv &&
Richard Trieucfc491d2011-08-02 04:35:43 +00005731 rex.get()->isNullPointerConstant(Context,
5732 Expr::NPC_ValueDependentIsNotNull))
John Wiegley01296292011-04-08 18:41:53 +00005733 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
Richard Trieucfc491d2011-08-02 04:35:43 +00005734 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005735
Chris Lattnerfaa54172010-01-12 21:23:57 +00005736 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005737}
5738
Chris Lattnerfaa54172010-01-12 21:23:57 +00005739QualType Sema::CheckRemainderOperands(
John Wiegley01296292011-04-08 18:41:53 +00005740 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
Richard Trieucfc491d2011-08-02 04:35:43 +00005741 if (lex.get()->getType()->isVectorType() ||
5742 rex.get()->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005743 if (lex.get()->getType()->hasIntegerRepresentation() &&
5744 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedman1408bc92011-06-23 18:10:35 +00005745 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005746 return InvalidOperands(Loc, lex, rex);
5747 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005748
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005749 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00005750 if (lex.isInvalid() || rex.isInvalid())
5751 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005752
Richard Trieucfc491d2011-08-02 04:35:43 +00005753 if (!lex.get()->getType()->isIntegerType() ||
5754 !rex.get()->getType()->isIntegerType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00005755 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005756
Chris Lattnerfaa54172010-01-12 21:23:57 +00005757 // Check for remainder by zero.
Richard Trieucfc491d2011-08-02 04:35:43 +00005758 if (rex.get()->isNullPointerConstant(Context,
5759 Expr::NPC_ValueDependentIsNotNull))
John Wiegley01296292011-04-08 18:41:53 +00005760 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
5761 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005762
Chris Lattnerfaa54172010-01-12 21:23:57 +00005763 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005764}
5765
Chandler Carruthc9332212011-06-27 08:02:19 +00005766/// \brief Diagnose invalid arithmetic on two void pointers.
5767static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
5768 Expr *LHS, Expr *RHS) {
5769 S.Diag(Loc, S.getLangOptions().CPlusPlus
5770 ? diag::err_typecheck_pointer_arith_void_type
5771 : diag::ext_gnu_void_ptr)
5772 << 1 /* two pointers */ << LHS->getSourceRange() << RHS->getSourceRange();
5773}
5774
5775/// \brief Diagnose invalid arithmetic on a void pointer.
5776static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5777 Expr *Pointer) {
5778 S.Diag(Loc, S.getLangOptions().CPlusPlus
5779 ? diag::err_typecheck_pointer_arith_void_type
5780 : diag::ext_gnu_void_ptr)
5781 << 0 /* one pointer */ << Pointer->getSourceRange();
5782}
5783
5784/// \brief Diagnose invalid arithmetic on two function pointers.
5785static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5786 Expr *LHS, Expr *RHS) {
5787 assert(LHS->getType()->isAnyPointerType());
5788 assert(RHS->getType()->isAnyPointerType());
5789 S.Diag(Loc, S.getLangOptions().CPlusPlus
5790 ? diag::err_typecheck_pointer_arith_function_type
5791 : diag::ext_gnu_ptr_func_arith)
5792 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5793 // We only show the second type if it differs from the first.
5794 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5795 RHS->getType())
5796 << RHS->getType()->getPointeeType()
5797 << LHS->getSourceRange() << RHS->getSourceRange();
5798}
5799
5800/// \brief Diagnose invalid arithmetic on a function pointer.
5801static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5802 Expr *Pointer) {
5803 assert(Pointer->getType()->isAnyPointerType());
5804 S.Diag(Loc, S.getLangOptions().CPlusPlus
5805 ? diag::err_typecheck_pointer_arith_function_type
5806 : diag::ext_gnu_ptr_func_arith)
5807 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5808 << 0 /* one pointer, so only one type */
5809 << Pointer->getSourceRange();
5810}
5811
5812/// \brief Check the validity of an arithmetic pointer operand.
5813///
5814/// If the operand has pointer type, this code will check for pointer types
5815/// which are invalid in arithmetic operations. These will be diagnosed
5816/// appropriately, including whether or not the use is supported as an
5817/// extension.
5818///
5819/// \returns True when the operand is valid to use (even if as an extension).
5820static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5821 Expr *Operand) {
5822 if (!Operand->getType()->isAnyPointerType()) return true;
5823
5824 QualType PointeeTy = Operand->getType()->getPointeeType();
5825 if (PointeeTy->isVoidType()) {
5826 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5827 return !S.getLangOptions().CPlusPlus;
5828 }
5829 if (PointeeTy->isFunctionType()) {
5830 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5831 return !S.getLangOptions().CPlusPlus;
5832 }
5833
5834 if ((Operand->getType()->isPointerType() &&
5835 !Operand->getType()->isDependentType()) ||
5836 Operand->getType()->isObjCObjectPointerType()) {
5837 QualType PointeeTy = Operand->getType()->getPointeeType();
5838 if (S.RequireCompleteType(
5839 Loc, PointeeTy,
5840 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5841 << PointeeTy << Operand->getSourceRange()))
5842 return false;
5843 }
5844
5845 return true;
5846}
5847
5848/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5849/// operands.
5850///
5851/// This routine will diagnose any invalid arithmetic on pointer operands much
5852/// like \see checkArithmeticOpPointerOperand. However, it has special logic
5853/// for emitting a single diagnostic even for operations where both LHS and RHS
5854/// are (potentially problematic) pointers.
5855///
5856/// \returns True when the operand is valid to use (even if as an extension).
5857static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
5858 Expr *LHS, Expr *RHS) {
5859 bool isLHSPointer = LHS->getType()->isAnyPointerType();
5860 bool isRHSPointer = RHS->getType()->isAnyPointerType();
5861 if (!isLHSPointer && !isRHSPointer) return true;
5862
5863 QualType LHSPointeeTy, RHSPointeeTy;
5864 if (isLHSPointer) LHSPointeeTy = LHS->getType()->getPointeeType();
5865 if (isRHSPointer) RHSPointeeTy = RHS->getType()->getPointeeType();
5866
5867 // Check for arithmetic on pointers to incomplete types.
5868 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
5869 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
5870 if (isLHSVoidPtr || isRHSVoidPtr) {
5871 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHS);
5872 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHS);
5873 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHS, RHS);
5874
5875 return !S.getLangOptions().CPlusPlus;
5876 }
5877
5878 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
5879 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
5880 if (isLHSFuncPtr || isRHSFuncPtr) {
5881 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHS);
5882 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, RHS);
5883 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS, RHS);
5884
5885 return !S.getLangOptions().CPlusPlus;
5886 }
5887
5888 Expr *Operands[] = { LHS, RHS };
5889 for (unsigned i = 0; i < 2; ++i) {
5890 Expr *Operand = Operands[i];
5891 if ((Operand->getType()->isPointerType() &&
5892 !Operand->getType()->isDependentType()) ||
5893 Operand->getType()->isObjCObjectPointerType()) {
5894 QualType PointeeTy = Operand->getType()->getPointeeType();
5895 if (S.RequireCompleteType(
5896 Loc, PointeeTy,
5897 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5898 << PointeeTy << Operand->getSourceRange()))
5899 return false;
5900 }
5901 }
5902 return true;
5903}
5904
Chris Lattnerfaa54172010-01-12 21:23:57 +00005905QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00005906 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
Richard Trieucfc491d2011-08-02 04:35:43 +00005907 if (lex.get()->getType()->isVectorType() ||
5908 rex.get()->getType()->isVectorType()) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005909 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005910 if (CompLHSTy) *CompLHSTy = compType;
5911 return compType;
5912 }
Steve Naroff7a5af782007-07-13 16:58:59 +00005913
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005914 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00005915 if (lex.isInvalid() || rex.isInvalid())
5916 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00005917
Steve Naroffe4718892007-04-27 18:30:00 +00005918 // handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00005919 if (lex.get()->getType()->isArithmeticType() &&
5920 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005921 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005922 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005923 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00005924
Eli Friedman8e122982008-05-18 18:08:51 +00005925 // Put any potential pointer into PExp
John Wiegley01296292011-04-08 18:41:53 +00005926 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00005927 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00005928 std::swap(PExp, IExp);
5929
Steve Naroff6b712a72009-07-14 18:25:06 +00005930 if (PExp->getType()->isAnyPointerType()) {
Eli Friedman8e122982008-05-18 18:08:51 +00005931 if (IExp->getType()->isIntegerType()) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005932 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
5933 return QualType();
5934
Steve Naroffaacd4cc2009-07-13 21:20:41 +00005935 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005936
Chris Lattner12bdebb2009-04-24 23:50:08 +00005937 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005938 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005939 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5940 << PointeeTy << PExp->getSourceRange();
5941 return QualType();
5942 }
Mike Stump11289f42009-09-09 15:08:12 +00005943
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00005944 // Check array bounds for pointer arithemtic
5945 CheckArrayAccess(PExp, IExp);
5946
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005947 if (CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00005948 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman629ffb92009-08-20 04:21:42 +00005949 if (LHSTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +00005950 LHSTy = lex.get()->getType();
Eli Friedman629ffb92009-08-20 04:21:42 +00005951 if (LHSTy->isPromotableIntegerType())
5952 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00005953 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005954 *CompLHSTy = LHSTy;
5955 }
Eli Friedman8e122982008-05-18 18:08:51 +00005956 return PExp->getType();
5957 }
5958 }
5959
Chris Lattner326f7572008-11-18 01:30:42 +00005960 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005961}
5962
Chris Lattner2a3569b2008-04-07 05:30:13 +00005963// C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00005964QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Richard Trieucfc491d2011-08-02 04:35:43 +00005965 SourceLocation Loc,
5966 QualType* CompLHSTy) {
5967 if (lex.get()->getType()->isVectorType() ||
5968 rex.get()->getType()->isVectorType()) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005969 QualType compType = CheckVectorOperands(lex, rex, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005970 if (CompLHSTy) *CompLHSTy = compType;
5971 return compType;
5972 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005973
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005974 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00005975 if (lex.isInvalid() || rex.isInvalid())
5976 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005977
Chris Lattner4d62f422007-12-09 21:53:25 +00005978 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005979
Chris Lattner4d62f422007-12-09 21:53:25 +00005980 // Handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00005981 if (lex.get()->getType()->isArithmeticType() &&
5982 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005983 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005984 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005985 }
Mike Stump11289f42009-09-09 15:08:12 +00005986
Chris Lattner4d62f422007-12-09 21:53:25 +00005987 // Either ptr - int or ptr - ptr.
John Wiegley01296292011-04-08 18:41:53 +00005988 if (lex.get()->getType()->isAnyPointerType()) {
5989 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005990
Chris Lattner12bdebb2009-04-24 23:50:08 +00005991 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00005992 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00005993 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley01296292011-04-08 18:41:53 +00005994 << lpointee << lex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00005995 return QualType();
5996 }
Mike Stump11289f42009-09-09 15:08:12 +00005997
Chris Lattner4d62f422007-12-09 21:53:25 +00005998 // The result type of a pointer-int computation is the pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005999 if (rex.get()->getType()->isIntegerType()) {
Chandler Carruthc9332212011-06-27 08:02:19 +00006000 if (!checkArithmeticOpPointerOperand(*this, Loc, lex.get()))
6001 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006002
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006003 Expr *IExpr = rex.get()->IgnoreParenCasts();
6004 UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6005 OK_Ordinary, IExpr->getExprLoc());
6006 // Check array bounds for pointer arithemtic
6007 CheckArrayAccess(lex.get()->IgnoreParenCasts(), &negRex);
6008
John Wiegley01296292011-04-08 18:41:53 +00006009 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
6010 return lex.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006011 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006012
Chris Lattner4d62f422007-12-09 21:53:25 +00006013 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006014 if (const PointerType *RHSPTy
6015 = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006016 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006017
Eli Friedman168fe152009-05-16 13:54:38 +00006018 if (getLangOptions().CPlusPlus) {
6019 // Pointee types must be the same: C++ [expr.add]
6020 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6021 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00006022 << lex.get()->getType() << rex.get()->getType()
6023 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00006024 return QualType();
6025 }
6026 } else {
6027 // Pointee types must be compatible C99 6.5.6p3
6028 if (!Context.typesAreCompatible(
6029 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6030 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6031 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00006032 << lex.get()->getType() << rex.get()->getType()
6033 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00006034 return QualType();
6035 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006036 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006037
Chandler Carruthc9332212011-06-27 08:02:19 +00006038 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
6039 lex.get(), rex.get()))
6040 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006041
John Wiegley01296292011-04-08 18:41:53 +00006042 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006043 return Context.getPointerDiffType();
6044 }
6045 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006046
Chris Lattner326f7572008-11-18 01:30:42 +00006047 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006048}
6049
Douglas Gregor0bf31402010-10-08 23:50:27 +00006050static bool isScopedEnumerationType(QualType T) {
6051 if (const EnumType *ET = dyn_cast<EnumType>(T))
6052 return ET->getDecl()->isScoped();
6053 return false;
6054}
6055
John Wiegley01296292011-04-08 18:41:53 +00006056static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006057 SourceLocation Loc, unsigned Opc,
6058 QualType LHSTy) {
6059 llvm::APSInt Right;
6060 // Check right/shifter operand
Richard Trieucfc491d2011-08-02 04:35:43 +00006061 if (rex.get()->isValueDependent() ||
6062 !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006063 return;
6064
6065 if (Right.isNegative()) {
John Wiegley01296292011-04-08 18:41:53 +00006066 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006067 S.PDiag(diag::warn_shift_negative)
John Wiegley01296292011-04-08 18:41:53 +00006068 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006069 return;
6070 }
6071 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley01296292011-04-08 18:41:53 +00006072 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006073 if (Right.uge(LeftBits)) {
John Wiegley01296292011-04-08 18:41:53 +00006074 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006075 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley01296292011-04-08 18:41:53 +00006076 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006077 return;
6078 }
6079 if (Opc != BO_Shl)
6080 return;
6081
6082 // When left shifting an ICE which is signed, we can check for overflow which
6083 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6084 // integers have defined behavior modulo one more than the maximum value
6085 // representable in the result type, so never warn for those.
6086 llvm::APSInt Left;
Richard Trieucfc491d2011-08-02 04:35:43 +00006087 if (lex.get()->isValueDependent() ||
6088 !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006089 LHSTy->hasUnsignedIntegerRepresentation())
6090 return;
6091 llvm::APInt ResultBits =
6092 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6093 if (LeftBits.uge(ResultBits))
6094 return;
6095 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6096 Result = Result.shl(Right);
6097
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006098 // Print the bit representation of the signed integer as an unsigned
6099 // hexadecimal number.
6100 llvm::SmallString<40> HexResult;
6101 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6102
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006103 // If we are only missing a sign bit, this is less likely to result in actual
6104 // bugs -- if the result is cast back to an unsigned type, it will have the
6105 // expected value. Thus we place this behind a different warning that can be
6106 // turned off separately if needed.
6107 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006108 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6109 << HexResult.str() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00006110 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006111 return;
6112 }
6113
6114 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006115 << HexResult.str() << Result.getMinSignedBits() << LHSTy
Richard Trieucfc491d2011-08-02 04:35:43 +00006116 << Left.getBitWidth() << lex.get()->getSourceRange()
6117 << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006118}
6119
Chris Lattner2a3569b2008-04-07 05:30:13 +00006120// C99 6.5.7
Richard Trieucfc491d2011-08-02 04:35:43 +00006121QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex,
6122 SourceLocation Loc, unsigned Opc,
6123 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00006124 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley01296292011-04-08 18:41:53 +00006125 if (!lex.get()->getType()->hasIntegerRepresentation() ||
6126 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00006127 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006128
Douglas Gregor0bf31402010-10-08 23:50:27 +00006129 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6130 // hasIntegerRepresentation() above instead of this.
John Wiegley01296292011-04-08 18:41:53 +00006131 if (isScopedEnumerationType(lex.get()->getType()) ||
6132 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00006133 return InvalidOperands(Loc, lex, rex);
6134 }
6135
Nate Begemane46ee9a2009-10-25 02:26:48 +00006136 // Vector shifts promote their scalar inputs to vector type.
Richard Trieucfc491d2011-08-02 04:35:43 +00006137 if (lex.get()->getType()->isVectorType() ||
6138 rex.get()->getType()->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00006139 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006140
Chris Lattner5c11c412007-12-12 05:47:28 +00006141 // Shifts don't perform usual arithmetic conversions, they just do integer
6142 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006143
John McCall57cdd882010-12-16 19:28:59 +00006144 // For the LHS, do usual unary conversions, but then reset them away
6145 // if this is a compound assignment.
John Wiegley01296292011-04-08 18:41:53 +00006146 ExprResult old_lex = lex;
6147 lex = UsualUnaryConversions(lex.take());
6148 if (lex.isInvalid())
6149 return QualType();
6150 QualType LHSTy = lex.get()->getType();
John McCall57cdd882010-12-16 19:28:59 +00006151 if (isCompAssign) lex = old_lex;
6152
6153 // The RHS is simpler.
John Wiegley01296292011-04-08 18:41:53 +00006154 rex = UsualUnaryConversions(rex.take());
6155 if (rex.isInvalid())
6156 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006157
Ryan Flynnf53fab82009-08-07 16:20:20 +00006158 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006159 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006160
Chris Lattner5c11c412007-12-12 05:47:28 +00006161 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006162 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006163}
6164
Chandler Carruth17773fc2010-07-10 12:30:03 +00006165static bool IsWithinTemplateSpecialization(Decl *D) {
6166 if (DeclContext *DC = D->getDeclContext()) {
6167 if (isa<ClassTemplateSpecializationDecl>(DC))
6168 return true;
6169 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6170 return FD->isFunctionTemplateSpecialization();
6171 }
6172 return false;
6173}
6174
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006175// C99 6.5.8, C++ [expr.rel]
Richard Trieucfc491d2011-08-02 04:35:43 +00006176QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex,
6177 SourceLocation Loc, unsigned OpaqueOpc,
6178 bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00006179 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006180
Chris Lattner9a152e22009-12-05 05:40:13 +00006181 // Handle vector comparisons separately.
Richard Trieucfc491d2011-08-02 04:35:43 +00006182 if (lex.get()->getType()->isVectorType() ||
6183 rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006184 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006185
John Wiegley01296292011-04-08 18:41:53 +00006186 QualType lType = lex.get()->getType();
6187 QualType rType = rex.get()->getType();
Douglas Gregor1beec452011-03-12 01:48:56 +00006188
John Wiegley01296292011-04-08 18:41:53 +00006189 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
6190 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006191 QualType LHSStrippedType = LHSStripped->getType();
6192 QualType RHSStrippedType = RHSStripped->getType();
6193
Douglas Gregor1beec452011-03-12 01:48:56 +00006194
6195
Chandler Carruth712563b2011-02-17 08:37:06 +00006196 // Two different enums will raise a warning when compared.
6197 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
6198 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
6199 if (LHSEnumType->getDecl()->getIdentifier() &&
6200 RHSEnumType->getDecl()->getIdentifier() &&
6201 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
6202 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6203 << LHSStrippedType << RHSStrippedType
John Wiegley01296292011-04-08 18:41:53 +00006204 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth712563b2011-02-17 08:37:06 +00006205 }
6206 }
6207 }
6208
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006209 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00006210 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley01296292011-04-08 18:41:53 +00006211 !lex.get()->getLocStart().isMacroID() &&
6212 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006213 // For non-floating point types, check for self-comparisons of the form
6214 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6215 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006216 //
6217 // NOTE: Don't warn about comparison expressions resulting from macro
6218 // expansion. Also don't warn about comparisons which are only self
6219 // comparisons within a template specialization. The warnings should catch
6220 // obvious cases in the definition of the template anyways. The idea is to
6221 // warn when the typed comparison operator will always evaluate to the same
6222 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006223 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006224 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006225 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006226 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006227 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006228 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006229 << (Opc == BO_EQ
6230 || Opc == BO_LE
6231 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00006232 } else if (lType->isArrayType() && rType->isArrayType() &&
6233 !DRL->getDecl()->getType()->isReferenceType() &&
6234 !DRR->getDecl()->getType()->isReferenceType()) {
6235 // what is it always going to eval to?
6236 char always_evals_to;
6237 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006238 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006239 always_evals_to = 0; // false
6240 break;
John McCalle3027922010-08-25 11:45:40 +00006241 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006242 always_evals_to = 1; // true
6243 break;
6244 default:
6245 // best we can say is 'a constant'
6246 always_evals_to = 2; // e.g. array1 <= array2
6247 break;
6248 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006249 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006250 << 1 // array
6251 << always_evals_to);
6252 }
6253 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006254 }
Mike Stump11289f42009-09-09 15:08:12 +00006255
Chris Lattner222b8bd2009-03-08 19:39:53 +00006256 if (isa<CastExpr>(LHSStripped))
6257 LHSStripped = LHSStripped->IgnoreParenCasts();
6258 if (isa<CastExpr>(RHSStripped))
6259 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006260
Chris Lattner222b8bd2009-03-08 19:39:53 +00006261 // Warn about comparisons against a string constant (unless the other
6262 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006263 Expr *literalString = 0;
6264 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006265 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006266 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006267 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006268 literalString = lex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006269 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006270 } else if ((isa<StringLiteral>(RHSStripped) ||
6271 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006272 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006273 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006274 literalString = rex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006275 literalStringStripped = RHSStripped;
6276 }
6277
6278 if (literalString) {
6279 std::string resultComparison;
6280 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006281 case BO_LT: resultComparison = ") < 0"; break;
6282 case BO_GT: resultComparison = ") > 0"; break;
6283 case BO_LE: resultComparison = ") <= 0"; break;
6284 case BO_GE: resultComparison = ") >= 0"; break;
6285 case BO_EQ: resultComparison = ") == 0"; break;
6286 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006287 default: assert(false && "Invalid comparison operator");
6288 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006289
Ted Kremenek3427fac2011-02-23 01:52:04 +00006290 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006291 PDiag(diag::warn_stringcompare)
6292 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006293 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006294 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006295 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006296
Douglas Gregorec170db2010-06-08 19:50:34 +00006297 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieucfc491d2011-08-02 04:35:43 +00006298 if (lex.get()->getType()->isArithmeticType() &&
6299 rex.get()->getType()->isArithmeticType()) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006300 UsualArithmeticConversions(lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00006301 if (lex.isInvalid() || rex.isInvalid())
6302 return QualType();
6303 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006304 else {
John Wiegley01296292011-04-08 18:41:53 +00006305 lex = UsualUnaryConversions(lex.take());
6306 if (lex.isInvalid())
6307 return QualType();
6308
6309 rex = UsualUnaryConversions(rex.take());
6310 if (rex.isInvalid())
6311 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006312 }
6313
John Wiegley01296292011-04-08 18:41:53 +00006314 lType = lex.get()->getType();
6315 rType = rex.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006316
Douglas Gregorca63811b2008-11-19 03:25:36 +00006317 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006318 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006319
Chris Lattnerb620c342007-08-26 01:18:55 +00006320 if (isRelational) {
6321 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006322 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006323 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006324 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006325 if (lType->hasFloatingRepresentation())
John Wiegley01296292011-04-08 18:41:53 +00006326 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006327
Chris Lattnerb620c342007-08-26 01:18:55 +00006328 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006329 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006330 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006331
John Wiegley01296292011-04-08 18:41:53 +00006332 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006333 Expr::NPC_ValueDependentIsNull);
John Wiegley01296292011-04-08 18:41:53 +00006334 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006335 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006336
Douglas Gregorf267edd2010-06-15 21:38:40 +00006337 // All of the following pointer-related warnings are GCC extensions, except
6338 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00006339 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006340 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006341 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00006342 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006343 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006344
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006345 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006346 if (LCanPointeeTy == RCanPointeeTy)
6347 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006348 if (!isRelational &&
6349 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6350 // Valid unless comparison between non-null pointer and function pointer
6351 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006352 // In a SFINAE context, we treat this as a hard error to maintain
6353 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006354 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6355 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00006356 Diag(Loc,
6357 isSFINAEContext()?
6358 diag::err_typecheck_comparison_of_fptr_to_void
6359 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieucfc491d2011-08-02 04:35:43 +00006360 << lType << rType << lex.get()->getSourceRange()
6361 << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006362
6363 if (isSFINAEContext())
6364 return QualType();
6365
John Wiegley01296292011-04-08 18:41:53 +00006366 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006367 return ResultTy;
6368 }
6369 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006370
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006371 // C++ [expr.rel]p2:
6372 // [...] Pointer conversions (4.10) and qualification
6373 // conversions (4.4) are performed on pointer operands (or on
6374 // a pointer operand and a null pointer constant) to bring
6375 // them to their composite pointer type. [...]
6376 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006377 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006378 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006379 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006380 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006381 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006382 if (T.isNull()) {
6383 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00006384 << lType << rType << lex.get()->getSourceRange()
6385 << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006386 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006387 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006388 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006389 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006390 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00006391 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006392 }
6393
John Wiegley01296292011-04-08 18:41:53 +00006394 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6395 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006396 return ResultTy;
6397 }
Eli Friedman16c209612009-08-23 00:27:47 +00006398 // C99 6.5.9p2 and C99 6.5.8p2
6399 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6400 RCanPointeeTy.getUnqualifiedType())) {
6401 // Valid unless a relational comparison of function pointers
6402 if (isRelational && LCanPointeeTy->isFunctionType()) {
6403 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00006404 << lType << rType << lex.get()->getSourceRange()
6405 << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006406 }
6407 } else if (!isRelational &&
6408 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6409 // Valid unless comparison between non-null pointer and function pointer
6410 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6411 && !LHSIsNull && !RHSIsNull) {
6412 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieucfc491d2011-08-02 04:35:43 +00006413 << lType << rType << lex.get()->getSourceRange()
6414 << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006415 }
6416 } else {
6417 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00006418 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00006419 << lType << rType << lex.get()->getSourceRange()
6420 << rex.get()->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00006421 }
John McCall7684dde2011-03-11 04:25:25 +00006422 if (LCanPointeeTy != RCanPointeeTy) {
6423 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006424 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006425 else
John Wiegley01296292011-04-08 18:41:53 +00006426 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006427 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006428 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006429 }
Mike Stump11289f42009-09-09 15:08:12 +00006430
Sebastian Redl576fd422009-05-10 18:38:11 +00006431 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006432 // Comparison of nullptr_t with itself.
6433 if (lType->isNullPtrType() && rType->isNullPtrType())
6434 return ResultTy;
6435
Mike Stump11289f42009-09-09 15:08:12 +00006436 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006437 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006438 if (RHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00006439 ((lType->isAnyPointerType() || lType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00006440 (!isRelational &&
6441 (lType->isMemberPointerType() || lType->isBlockPointerType())))) {
John Wiegley01296292011-04-08 18:41:53 +00006442 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00006443 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006444 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006445 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006446 return ResultTy;
6447 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006448 if (LHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00006449 ((rType->isAnyPointerType() || rType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00006450 (!isRelational &&
6451 (rType->isMemberPointerType() || rType->isBlockPointerType())))) {
John Wiegley01296292011-04-08 18:41:53 +00006452 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00006453 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006454 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006455 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006456 return ResultTy;
6457 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006458
6459 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00006460 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006461 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6462 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006463 // In addition, pointers to members can be compared, or a pointer to
6464 // member and a null pointer constant. Pointer to member conversions
6465 // (4.11) and qualification conversions (4.4) are performed to bring
6466 // them to a common type. If one operand is a null pointer constant,
6467 // the common type is the type of the other operand. Otherwise, the
6468 // common type is a pointer to member type similar (4.4) to the type
6469 // of one of the operands, with a cv-qualification signature (4.4)
6470 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006471 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006472 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006473 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006474 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006475 if (T.isNull()) {
6476 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00006477 << lType << rType << lex.get()->getSourceRange()
6478 << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006479 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006480 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006481 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006482 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006483 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00006484 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006485 }
Mike Stump11289f42009-09-09 15:08:12 +00006486
John Wiegley01296292011-04-08 18:41:53 +00006487 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
6488 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006489 return ResultTy;
6490 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006491
6492 // Handle scoped enumeration types specifically, since they don't promote
6493 // to integers.
John Wiegley01296292011-04-08 18:41:53 +00006494 if (lex.get()->getType()->isEnumeralType() &&
Richard Trieucfc491d2011-08-02 04:35:43 +00006495 Context.hasSameUnqualifiedType(lex.get()->getType(),
6496 rex.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006497 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00006498 }
Mike Stump11289f42009-09-09 15:08:12 +00006499
Steve Naroff081c7422008-09-04 15:10:53 +00006500 // Handle block pointer types.
Richard Trieucfc491d2011-08-02 04:35:43 +00006501 if (!isRelational && lType->isBlockPointerType() &&
6502 rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006503 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6504 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006505
Steve Naroff081c7422008-09-04 15:10:53 +00006506 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006507 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006508 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieucfc491d2011-08-02 04:35:43 +00006509 << lType << rType << lex.get()->getSourceRange()
6510 << rex.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006511 }
John Wiegley01296292011-04-08 18:41:53 +00006512 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006513 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006514 }
John Wiegley01296292011-04-08 18:41:53 +00006515
Steve Naroffe18f94c2008-09-28 01:11:11 +00006516 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00006517 if (!isRelational
6518 && ((lType->isBlockPointerType() && rType->isPointerType())
6519 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006520 if (!LHSIsNull && !RHSIsNull) {
John McCall7684dde2011-03-11 04:25:25 +00006521 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006522 ->getPointeeType()->isVoidType())
John McCall7684dde2011-03-11 04:25:25 +00006523 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006524 ->getPointeeType()->isVoidType())))
6525 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieucfc491d2011-08-02 04:35:43 +00006526 << lType << rType << lex.get()->getSourceRange()
6527 << rex.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006528 }
John McCall7684dde2011-03-11 04:25:25 +00006529 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006530 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006531 else
John Wiegley01296292011-04-08 18:41:53 +00006532 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006533 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006534 }
Steve Naroff081c7422008-09-04 15:10:53 +00006535
John McCall7684dde2011-03-11 04:25:25 +00006536 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
6537 const PointerType *LPT = lType->getAs<PointerType>();
6538 const PointerType *RPT = rType->getAs<PointerType>();
6539 if (LPT || RPT) {
6540 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6541 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006542
Steve Naroff753567f2008-11-17 19:49:16 +00006543 if (!LPtrToVoid && !RPtrToVoid &&
6544 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006545 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00006546 << lType << rType << lex.get()->getSourceRange()
6547 << rex.get()->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006548 }
John McCall7684dde2011-03-11 04:25:25 +00006549 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006550 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006551 else
John Wiegley01296292011-04-08 18:41:53 +00006552 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006553 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006554 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006555 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006556 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006557 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieucfc491d2011-08-02 04:35:43 +00006558 << lType << rType << lex.get()->getSourceRange()
6559 << rex.get()->getSourceRange();
John McCall7684dde2011-03-11 04:25:25 +00006560 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00006561 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006562 else
John Wiegley01296292011-04-08 18:41:53 +00006563 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006564 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006565 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006566 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006567 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6568 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006569 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006570 bool isError = false;
6571 if ((LHSIsNull && lType->isIntegerType()) ||
6572 (RHSIsNull && rType->isIntegerType())) {
6573 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006574 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006575 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006576 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006577 else if (getLangOptions().CPlusPlus) {
6578 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6579 isError = true;
6580 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006581 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006582
Chris Lattnerd99bd522009-08-23 00:03:44 +00006583 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006584 Diag(Loc, DiagID)
Richard Trieucfc491d2011-08-02 04:35:43 +00006585 << lType << rType << lex.get()->getSourceRange()
6586 << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006587 if (isError)
6588 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006589 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006590
6591 if (lType->isIntegerType())
John Wiegley01296292011-04-08 18:41:53 +00006592 lex = ImpCastExprToType(lex.take(), rType,
John McCalle84af4e2010-11-13 01:35:44 +00006593 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006594 else
John Wiegley01296292011-04-08 18:41:53 +00006595 rex = ImpCastExprToType(rex.take(), lType,
John McCalle84af4e2010-11-13 01:35:44 +00006596 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006597 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006598 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006599
Steve Naroff4b191572008-09-04 16:56:14 +00006600 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00006601 if (!isRelational && RHSIsNull
6602 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley01296292011-04-08 18:41:53 +00006603 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006604 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006605 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00006606 if (!isRelational && LHSIsNull
6607 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley01296292011-04-08 18:41:53 +00006608 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006609 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006610 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006611
Chris Lattner326f7572008-11-18 01:30:42 +00006612 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006613}
6614
Nate Begeman191a6b12008-07-14 18:02:46 +00006615/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006616/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006617/// like a scalar comparison, a vector comparison produces a vector of integer
6618/// types.
John Wiegley01296292011-04-08 18:41:53 +00006619QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner326f7572008-11-18 01:30:42 +00006620 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00006621 bool isRelational) {
6622 // Check to make sure we're operating on vectors of the same type and width,
6623 // Allowing one side to be a scalar of element type.
Eli Friedman1408bc92011-06-23 18:10:35 +00006624 QualType vType = CheckVectorOperands(lex, rex, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00006625 if (vType.isNull())
6626 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006627
John Wiegley01296292011-04-08 18:41:53 +00006628 QualType lType = lex.get()->getType();
6629 QualType rType = rex.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006630
Anton Yartsev530deb92011-03-27 15:36:07 +00006631 // If AltiVec, the comparison results in a numeric type, i.e.
6632 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00006633 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00006634 return Context.getLogicalOperationType();
6635
Nate Begeman191a6b12008-07-14 18:02:46 +00006636 // For non-floating point types, check for self-comparisons of the form
6637 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6638 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006639 if (!lType->hasFloatingRepresentation()) {
John Wiegley01296292011-04-08 18:41:53 +00006640 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
6641 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00006642 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00006643 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00006644 PDiag(diag::warn_comparison_always)
6645 << 0 // self-
6646 << 2 // "a constant"
6647 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006648 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006649
Nate Begeman191a6b12008-07-14 18:02:46 +00006650 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00006651 if (!isRelational && lType->hasFloatingRepresentation()) {
6652 assert (rType->hasFloatingRepresentation());
John Wiegley01296292011-04-08 18:41:53 +00006653 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00006654 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006655
Nate Begeman191a6b12008-07-14 18:02:46 +00006656 // Return the type for the comparison, which is the same as vector type for
6657 // integer vectors, or an integer type of identical size and number of
6658 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006659 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00006660 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006661
John McCall9dd450b2009-09-21 23:43:11 +00006662 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006663 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006664 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006665 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006666 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006667 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6668
Mike Stump4e1f26a2009-02-19 03:04:26 +00006669 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006670 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006671 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6672}
6673
Steve Naroff218bc2b2007-05-04 21:54:46 +00006674inline QualType Sema::CheckBitwiseOperands(
John Wiegley01296292011-04-08 18:41:53 +00006675 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
Richard Trieucfc491d2011-08-02 04:35:43 +00006676 if (lex.get()->getType()->isVectorType() ||
6677 rex.get()->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00006678 if (lex.get()->getType()->hasIntegerRepresentation() &&
6679 rex.get()->getType()->hasIntegerRepresentation())
Eli Friedman1408bc92011-06-23 18:10:35 +00006680 return CheckVectorOperands(lex, rex, Loc, isCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006681
6682 return InvalidOperands(Loc, lex, rex);
6683 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006684
John Wiegley01296292011-04-08 18:41:53 +00006685 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
Richard Trieucfc491d2011-08-02 04:35:43 +00006686 QualType compType = UsualArithmeticConversions(lexResult, rexResult,
6687 isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00006688 if (lexResult.isInvalid() || rexResult.isInvalid())
6689 return QualType();
6690 lex = lexResult.take();
6691 rex = rexResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006692
John Wiegley01296292011-04-08 18:41:53 +00006693 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6694 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006695 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00006696 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006697}
6698
Steve Naroff218bc2b2007-05-04 21:54:46 +00006699inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley01296292011-04-08 18:41:53 +00006700 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00006701
6702 // Diagnose cases where the user write a logical and/or but probably meant a
6703 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6704 // is a constant.
Richard Trieucfc491d2011-08-02 04:35:43 +00006705 if (lex.get()->getType()->isIntegerType() &&
6706 !lex.get()->getType()->isBooleanType() &&
John Wiegley01296292011-04-08 18:41:53 +00006707 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00006708 // Don't warn in macros or template instantiations.
6709 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00006710 // If the RHS can be constant folded, and if it constant folds to something
6711 // that isn't 0 or 1 (which indicate a potential logical operation that
6712 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006713 // Parens on the RHS are ignored.
Chris Lattner938533d2010-07-24 01:10:11 +00006714 Expr::EvalResult Result;
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006715 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6716 if ((getLangOptions().Bool && !rex.get()->getType()->isBooleanType()) ||
6717 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6718 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6719 << rex.get()->getSourceRange()
6720 << (Opc == BO_LAnd ? "&&" : "||")
6721 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00006722 }
6723 }
Chris Lattner8406c512010-07-13 19:41:32 +00006724
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006725 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00006726 lex = UsualUnaryConversions(lex.take());
6727 if (lex.isInvalid())
6728 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006729
John Wiegley01296292011-04-08 18:41:53 +00006730 rex = UsualUnaryConversions(rex.take());
6731 if (rex.isInvalid())
6732 return QualType();
6733
Richard Trieucfc491d2011-08-02 04:35:43 +00006734 if (!lex.get()->getType()->isScalarType() ||
6735 !rex.get()->getType()->isScalarType())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006736 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006737
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006738 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006739 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006740
John McCall4a2429a2010-06-04 00:29:51 +00006741 // The following is safe because we only use this method for
6742 // non-overloadable operands.
6743
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006744 // C++ [expr.log.and]p1
6745 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006746 // The operands are both contextually converted to type bool.
John Wiegley01296292011-04-08 18:41:53 +00006747 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
6748 if (lexRes.isInvalid())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006749 return InvalidOperands(Loc, lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00006750 lex = move(lexRes);
6751
6752 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
6753 if (rexRes.isInvalid())
6754 return InvalidOperands(Loc, lex, rex);
6755 rex = move(rexRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006756
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006757 // C++ [expr.log.and]p2
6758 // C++ [expr.log.or]p2
6759 // The result is a bool.
6760 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006761}
6762
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006763/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6764/// is a read-only property; return true if so. A readonly property expression
6765/// depends on various declarations and thus must be treated specially.
6766///
Mike Stump11289f42009-09-09 15:08:12 +00006767static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006768 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6769 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00006770 if (PropExpr->isImplicitProperty()) return false;
6771
6772 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6773 QualType BaseType = PropExpr->isSuperReceiver() ?
6774 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00006775 PropExpr->getBase()->getType();
6776
John McCallb7bd14f2010-12-02 01:19:52 +00006777 if (const ObjCObjectPointerType *OPT =
6778 BaseType->getAsObjCInterfacePointerType())
6779 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6780 if (S.isPropertyReadonly(PDecl, IFace))
6781 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006782 }
6783 return false;
6784}
6785
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006786static bool IsConstProperty(Expr *E, Sema &S) {
6787 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6788 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6789 if (PropExpr->isImplicitProperty()) return false;
6790
6791 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6792 QualType T = PDecl->getType();
6793 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00006794 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006795 CanQualType CT = S.Context.getCanonicalType(T);
6796 return CT.isConstQualified();
6797 }
6798 return false;
6799}
6800
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006801static bool IsReadonlyMessage(Expr *E, Sema &S) {
6802 if (E->getStmtClass() != Expr::MemberExprClass)
6803 return false;
6804 const MemberExpr *ME = cast<MemberExpr>(E);
6805 NamedDecl *Member = ME->getMemberDecl();
6806 if (isa<FieldDecl>(Member)) {
6807 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
6808 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
6809 return false;
6810 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
6811 }
6812 return false;
6813}
6814
Chris Lattner30bd3272008-11-18 01:22:49 +00006815/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6816/// emit an error and return true. If so, return false.
6817static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006818 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00006819 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006820 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006821 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6822 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006823 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
6824 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006825 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
6826 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00006827 if (IsLV == Expr::MLV_Valid)
6828 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006829
Chris Lattner30bd3272008-11-18 01:22:49 +00006830 unsigned Diag = 0;
6831 bool NeedType = false;
6832 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00006833 case Expr::MLV_ConstQualified:
6834 Diag = diag::err_typecheck_assign_const;
6835
John McCalld4631322011-06-17 06:42:21 +00006836 // In ARC, use some specialized diagnostics for occasions where we
6837 // infer 'const'. These are always pseudo-strong variables.
John McCall31168b02011-06-15 23:02:42 +00006838 if (S.getLangOptions().ObjCAutoRefCount) {
6839 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
6840 if (declRef && isa<VarDecl>(declRef->getDecl())) {
6841 VarDecl *var = cast<VarDecl>(declRef->getDecl());
6842
John McCalld4631322011-06-17 06:42:21 +00006843 // Use the normal diagnostic if it's pseudo-__strong but the
6844 // user actually wrote 'const'.
6845 if (var->isARCPseudoStrong() &&
6846 (!var->getTypeSourceInfo() ||
6847 !var->getTypeSourceInfo()->getType().isConstQualified())) {
6848 // There are two pseudo-strong cases:
6849 // - self
John McCall31168b02011-06-15 23:02:42 +00006850 ObjCMethodDecl *method = S.getCurMethodDecl();
6851 if (method && var == method->getSelfDecl())
6852 Diag = diag::err_typecheck_arr_assign_self;
John McCalld4631322011-06-17 06:42:21 +00006853
6854 // - fast enumeration variables
6855 else
John McCall31168b02011-06-15 23:02:42 +00006856 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00006857
John McCall31168b02011-06-15 23:02:42 +00006858 SourceRange Assign;
6859 if (Loc != OrigLoc)
6860 Assign = SourceRange(OrigLoc, OrigLoc);
6861 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
6862 // We need to preserve the AST regardless, so migration tool
6863 // can do its job.
6864 return false;
6865 }
6866 }
6867 }
6868
6869 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006870 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006871 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6872 NeedType = true;
6873 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006874 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00006875 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6876 NeedType = true;
6877 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00006878 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00006879 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6880 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006881 case Expr::MLV_Valid:
6882 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00006883 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00006884 case Expr::MLV_MemberFunction:
6885 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00006886 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6887 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006888 case Expr::MLV_IncompleteType:
6889 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00006890 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006891 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00006892 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00006893 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00006894 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6895 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00006896 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00006897 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6898 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00006899 case Expr::MLV_ReadonlyProperty:
6900 Diag = diag::error_readonly_property_assignment;
6901 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00006902 case Expr::MLV_NoSetterProperty:
6903 Diag = diag::error_nosetter_property_assignment;
6904 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00006905 case Expr::MLV_InvalidMessageExpression:
6906 Diag = diag::error_readonly_message_assignment;
6907 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00006908 case Expr::MLV_SubObjCPropertySetting:
6909 Diag = diag::error_no_subobject_property_setting;
6910 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006911 }
Steve Naroffad373bd2007-07-31 12:34:36 +00006912
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006913 SourceRange Assign;
6914 if (Loc != OrigLoc)
6915 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00006916 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00006917 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006918 else
Mike Stump11289f42009-09-09 15:08:12 +00006919 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00006920 return true;
6921}
6922
6923
6924
6925// C99 6.5.16.1
John Wiegley01296292011-04-08 18:41:53 +00006926QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00006927 SourceLocation Loc,
6928 QualType CompoundType) {
6929 // Verify that LHS is a modifiable lvalue, and emit error if not.
6930 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00006931 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00006932
6933 QualType LHSType = LHS->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00006934 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
6935 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006936 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00006937 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006938 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006939 // Simple assignment "x = y".
John Wiegley01296292011-04-08 18:41:53 +00006940 if (LHS->getObjectKind() == OK_ObjCProperty) {
6941 ExprResult LHSResult = Owned(LHS);
6942 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
6943 if (LHSResult.isInvalid())
6944 return QualType();
6945 LHS = LHSResult.take();
6946 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00006947 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00006948 if (RHS.isInvalid())
6949 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006950 // Special case of NSObject attributes on c-style pointer types.
6951 if (ConvTy == IncompatiblePointer &&
6952 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006953 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006954 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00006955 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00006956 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006957
John McCall7decc9e2010-11-18 06:31:45 +00006958 if (ConvTy == Compatible &&
6959 getLangOptions().ObjCNonFragileABI &&
6960 LHSType->isObjCObjectType())
6961 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
6962 << LHSType;
6963
Chris Lattnerea714382008-08-21 18:04:13 +00006964 // If the RHS is a unary plus or minus, check to see if they = and + are
6965 // right next to each other. If so, the user may have typo'd "x =+ 4"
6966 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00006967 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00006968 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
6969 RHSCheck = ICE->getSubExpr();
6970 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00006971 if ((UO->getOpcode() == UO_Plus ||
6972 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00006973 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00006974 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00006975 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
6976 // And there is a space or other character before the subexpr of the
6977 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00006978 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
6979 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00006980 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00006981 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00006982 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00006983 }
Chris Lattnerea714382008-08-21 18:04:13 +00006984 }
John McCall31168b02011-06-15 23:02:42 +00006985
6986 if (ConvTy == Compatible) {
6987 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
6988 checkRetainCycles(LHS, RHS.get());
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006989 else if (getLangOptions().ObjCAutoRefCount)
6990 checkUnsafeExprAssigns(Loc, LHS, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00006991 }
Chris Lattnerea714382008-08-21 18:04:13 +00006992 } else {
6993 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00006994 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00006995 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00006996
Chris Lattner326f7572008-11-18 01:30:42 +00006997 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00006998 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00006999 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007000
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +00007001 CheckForNullPointerDereference(*this, LHS);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007002
Steve Naroff98cf3e92007-06-06 18:38:38 +00007003 // C99 6.5.16p3: The type of an assignment expression is the type of the
7004 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007005 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007006 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7007 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007008 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007009 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007010 return (getLangOptions().CPlusPlus
7011 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007012}
7013
Chris Lattner326f7572008-11-18 01:30:42 +00007014// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007015static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007016 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00007017 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007018
John McCall3aef3d82011-04-10 19:13:55 +00007019 LHS = S.CheckPlaceholderExpr(LHS.take());
7020 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007021 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007022 return QualType();
7023
John McCall73d36182010-10-12 07:14:40 +00007024 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7025 // operands, but not unary promotions.
7026 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007027
John McCall34376a62010-12-04 03:47:34 +00007028 // So we treat the LHS as a ignored value, and in C++ we allow the
7029 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007030 LHS = S.IgnoredValueConversions(LHS.take());
7031 if (LHS.isInvalid())
7032 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007033
7034 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007035 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7036 if (RHS.isInvalid())
7037 return QualType();
7038 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007039 S.RequireCompleteType(Loc, RHS.get()->getType(),
7040 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007041 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007042
John Wiegley01296292011-04-08 18:41:53 +00007043 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007044}
7045
Steve Naroff7a5af782007-07-13 16:58:59 +00007046/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7047/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007048static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7049 ExprValueKind &VK,
7050 SourceLocation OpLoc,
7051 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007052 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007053 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007054
Chris Lattner6b0cf142008-11-21 07:05:48 +00007055 QualType ResType = Op->getType();
7056 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007057
John McCall4bc41ae2010-11-18 19:01:18 +00007058 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007059 // Decrement of bool is not allowed.
7060 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007061 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007062 return QualType();
7063 }
7064 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007065 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007066 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007067 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007068 } else if (ResType->isAnyPointerType()) {
7069 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00007070
Chris Lattner6b0cf142008-11-21 07:05:48 +00007071 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007072 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007073 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007074
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007075 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00007076 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7077 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007078 << PointeeTy << Op->getSourceRange();
7079 return QualType();
7080 }
Eli Friedman090addd2010-01-03 00:20:48 +00007081 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007082 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007083 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007084 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007085 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007086 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007087 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007088 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7089 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007090 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7091 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007092 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007093 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00007094 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007095 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007096 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007097 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007098 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007099 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007100 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007101 // In C++, a prefix increment is the same type as the operand. Otherwise
7102 // (in C or with postfix), the increment is the unqualified type of the
7103 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00007104 if (isPrefix && S.getLangOptions().CPlusPlus) {
7105 VK = VK_LValue;
7106 return ResType;
7107 } else {
7108 VK = VK_RValue;
7109 return ResType.getUnqualifiedType();
7110 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007111}
7112
John Wiegley01296292011-04-08 18:41:53 +00007113ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00007114 assert(E->getValueKind() == VK_LValue &&
7115 E->getObjectKind() == OK_ObjCProperty);
7116 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7117
Douglas Gregor33823722011-06-11 01:09:30 +00007118 QualType T = E->getType();
7119 QualType ReceiverType;
7120 if (PRE->isObjectReceiver())
7121 ReceiverType = PRE->getBase()->getType();
7122 else if (PRE->isSuperReceiver())
7123 ReceiverType = PRE->getSuperReceiverType();
7124 else
7125 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
7126
John McCall34376a62010-12-04 03:47:34 +00007127 ExprValueKind VK = VK_RValue;
7128 if (PRE->isImplicitProperty()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007129 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007130 PRE->getImplicitPropertyGetter()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007131 T = getMessageSendResultType(ReceiverType, GetterMethod,
7132 PRE->isClassReceiver(),
7133 PRE->isSuperReceiver());
7134 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007135 }
7136 else {
7137 Diag(PRE->getLocation(), diag::err_getter_not_found)
7138 << PRE->getBase()->getType();
7139 }
John McCall34376a62010-12-04 03:47:34 +00007140 }
Douglas Gregor33823722011-06-11 01:09:30 +00007141
7142 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCall34376a62010-12-04 03:47:34 +00007143 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007144
7145 ExprResult Result = MaybeBindToTemporary(E);
7146 if (!Result.isInvalid())
7147 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00007148
7149 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00007150}
7151
Richard Trieucfc491d2011-08-02 04:35:43 +00007152void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
7153 QualType &LHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00007154 assert(LHS.get()->getValueKind() == VK_LValue &&
7155 LHS.get()->getObjectKind() == OK_ObjCProperty);
7156 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00007157
John McCall31168b02011-06-15 23:02:42 +00007158 bool Consumed = false;
7159
John Wiegley01296292011-04-08 18:41:53 +00007160 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00007161 // If using property-dot syntax notation for assignment, and there is a
7162 // setter, RHS expression is being passed to the setter argument. So,
7163 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00007164 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00007165 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7166 LHSTy = (*P)->getType();
John McCall31168b02011-06-15 23:02:42 +00007167 Consumed = (getLangOptions().ObjCAutoRefCount &&
7168 (*P)->hasAttr<NSConsumedAttr>());
John McCall34376a62010-12-04 03:47:34 +00007169
7170 // Otherwise, if the getter returns an l-value, just call that.
7171 } else {
John Wiegley01296292011-04-08 18:41:53 +00007172 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00007173 ExprValueKind VK = Expr::getValueKindForType(Result);
7174 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00007175 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7176 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00007177 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007178 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007179 }
John McCall31168b02011-06-15 23:02:42 +00007180 } else if (getLangOptions().ObjCAutoRefCount) {
7181 const ObjCMethodDecl *setter
7182 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7183 if (setter) {
7184 ObjCMethodDecl::param_iterator P = setter->param_begin();
7185 LHSTy = (*P)->getType();
7186 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7187 }
John McCall34376a62010-12-04 03:47:34 +00007188 }
7189
John McCall31168b02011-06-15 23:02:42 +00007190 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7191 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007192 InitializedEntity Entity =
John McCall31168b02011-06-15 23:02:42 +00007193 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley01296292011-04-08 18:41:53 +00007194 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCall31168b02011-06-15 23:02:42 +00007195 if (!ArgE.isInvalid()) {
John Wiegley01296292011-04-08 18:41:53 +00007196 RHS = ArgE;
John McCall31168b02011-06-15 23:02:42 +00007197 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7198 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7199 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007200 }
7201}
7202
7203
Anders Carlsson806700f2008-02-01 07:15:58 +00007204/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007205/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007206/// where the declaration is needed for type checking. We only need to
7207/// handle cases when the expression references a function designator
7208/// or is an lvalue. Here are some examples:
7209/// - &(x) => x
7210/// - &*****f => f for f a function designator.
7211/// - &s.xx => s
7212/// - &s.zz[1].yy -> s, if zz is an array
7213/// - *(x + 1) -> x, if x is an array
7214/// - &"123"[2] -> 0
7215/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007216static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007217 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007218 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007219 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007220 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007221 // If this is an arrow operator, the address is an offset from
7222 // the base's value, so the object the base refers to is
7223 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007224 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007225 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007226 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007227 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007228 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007229 // FIXME: This code shouldn't be necessary! We should catch the implicit
7230 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007231 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7232 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7233 if (ICE->getSubExpr()->getType()->isArrayType())
7234 return getPrimaryDecl(ICE->getSubExpr());
7235 }
7236 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007237 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007238 case Stmt::UnaryOperatorClass: {
7239 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007240
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007241 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007242 case UO_Real:
7243 case UO_Imag:
7244 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007245 return getPrimaryDecl(UO->getSubExpr());
7246 default:
7247 return 0;
7248 }
7249 }
Steve Naroff47500512007-04-19 23:00:49 +00007250 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007251 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007252 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007253 // If the result of an implicit cast is an l-value, we care about
7254 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007255 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007256 default:
7257 return 0;
7258 }
7259}
7260
7261/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007262/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007263/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007264/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007265/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007266/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007267/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007268static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7269 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007270 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007271 return S.Context.DependentTy;
7272 if (OrigOp->getType() == S.Context.OverloadTy)
7273 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00007274 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7275 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00007276 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7277 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7278 << OrigOp->getSourceRange();
7279 return QualType();
7280 }
John McCall8d08b9b2010-08-27 09:08:28 +00007281
John McCall2979fe02011-04-12 00:42:48 +00007282 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007283
John McCall8d08b9b2010-08-27 09:08:28 +00007284 // Make sure to ignore parentheses in subsequent checks
7285 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007286
John McCall4bc41ae2010-11-18 19:01:18 +00007287 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007288 // Implement C99-only parts of addressof rules.
7289 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007290 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007291 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7292 // (assuming the deref expression is valid).
7293 return uOp->getSubExpr()->getType();
7294 }
7295 // Technically, there should be a check for array subscript
7296 // expressions here, but the result of one is always an lvalue anyway.
7297 }
John McCallf3a88602011-02-03 08:15:49 +00007298 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007299 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00007300
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007301 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007302 bool sfinae = S.isSFINAEContext();
7303 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7304 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007305 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007306 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007307 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007308 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007309 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007310 } else if (lval == Expr::LV_MemberFunction) {
7311 // If it's an instance method, make a member pointer.
7312 // The expression must have exactly the form &A::foo.
7313
7314 // If the underlying expression isn't a decl ref, give up.
7315 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007316 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007317 << OrigOp->getSourceRange();
7318 return QualType();
7319 }
7320 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7321 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7322
7323 // The id-expression was parenthesized.
7324 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007325 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007326 << OrigOp->getSourceRange();
7327
7328 // The method was named without a qualifier.
7329 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007330 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007331 << op->getSourceRange();
7332 }
7333
John McCall4bc41ae2010-11-18 19:01:18 +00007334 return S.Context.getMemberPointerType(op->getType(),
7335 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007336 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007337 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007338 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007339 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007340 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007341 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007342 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007343 return QualType();
7344 }
John McCall086a4642010-11-24 05:12:34 +00007345 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007346 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00007347 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00007348 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00007349 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007350 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007351 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00007352 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00007353 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007354 return QualType();
John McCall086a4642010-11-24 05:12:34 +00007355 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007356 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00007357 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00007358 << "property expression" << op->getSourceRange();
7359 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007360 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007361 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007362 // with the register storage-class specifier.
7363 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007364 // in C++ it is not error to take address of a register
7365 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007366 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007367 !S.getLangOptions().CPlusPlus) {
7368 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00007369 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007370 return QualType();
7371 }
John McCalld14a8642009-11-21 08:51:07 +00007372 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007373 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007374 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007375 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007376 // Could be a pointer to member, though, if there is an explicit
7377 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007378 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007379 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007380 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007381 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007382 S.Diag(OpLoc,
7383 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007384 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007385 return QualType();
7386 }
Mike Stump11289f42009-09-09 15:08:12 +00007387
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007388 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7389 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007390 return S.Context.getMemberPointerType(op->getType(),
7391 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007392 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007393 }
Anders Carlsson5b535762009-05-16 21:43:42 +00007394 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00007395 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007396 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007397
Eli Friedmance7f9002009-05-16 23:27:50 +00007398 if (lval == Expr::LV_IncompleteVoidType) {
7399 // Taking the address of a void variable is technically illegal, but we
7400 // allow it in cases which are otherwise valid.
7401 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007402 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007403 }
7404
Steve Naroff47500512007-04-19 23:00:49 +00007405 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007406 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007407 return S.Context.getObjCObjectPointerType(op->getType());
7408 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007409}
7410
Chris Lattner9156f1b2010-07-05 19:17:26 +00007411/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007412static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7413 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007414 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007415 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007416
John Wiegley01296292011-04-08 18:41:53 +00007417 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7418 if (ConvResult.isInvalid())
7419 return QualType();
7420 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007421 QualType OpTy = Op->getType();
7422 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007423
7424 if (isa<CXXReinterpretCastExpr>(Op)) {
7425 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7426 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7427 Op->getSourceRange());
7428 }
7429
Chris Lattner9156f1b2010-07-05 19:17:26 +00007430 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7431 // is an incomplete type or void. It would be possible to warn about
7432 // dereferencing a void pointer, but it's completely well-defined, and such a
7433 // warning is unlikely to catch any mistakes.
7434 if (const PointerType *PT = OpTy->getAs<PointerType>())
7435 Result = PT->getPointeeType();
7436 else if (const ObjCObjectPointerType *OPT =
7437 OpTy->getAs<ObjCObjectPointerType>())
7438 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007439 else {
John McCall3aef3d82011-04-10 19:13:55 +00007440 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007441 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007442 if (PR.take() != Op)
7443 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007444 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007445
Chris Lattner9156f1b2010-07-05 19:17:26 +00007446 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007447 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007448 << OpTy << Op->getSourceRange();
7449 return QualType();
7450 }
John McCall4bc41ae2010-11-18 19:01:18 +00007451
7452 // Dereferences are usually l-values...
7453 VK = VK_LValue;
7454
7455 // ...except that certain expressions are never l-values in C.
Douglas Gregor5476205b2011-06-23 00:49:38 +00007456 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007457 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007458
7459 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007460}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007461
John McCalle3027922010-08-25 11:45:40 +00007462static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007463 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007464 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007465 switch (Kind) {
7466 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007467 case tok::periodstar: Opc = BO_PtrMemD; break;
7468 case tok::arrowstar: Opc = BO_PtrMemI; break;
7469 case tok::star: Opc = BO_Mul; break;
7470 case tok::slash: Opc = BO_Div; break;
7471 case tok::percent: Opc = BO_Rem; break;
7472 case tok::plus: Opc = BO_Add; break;
7473 case tok::minus: Opc = BO_Sub; break;
7474 case tok::lessless: Opc = BO_Shl; break;
7475 case tok::greatergreater: Opc = BO_Shr; break;
7476 case tok::lessequal: Opc = BO_LE; break;
7477 case tok::less: Opc = BO_LT; break;
7478 case tok::greaterequal: Opc = BO_GE; break;
7479 case tok::greater: Opc = BO_GT; break;
7480 case tok::exclaimequal: Opc = BO_NE; break;
7481 case tok::equalequal: Opc = BO_EQ; break;
7482 case tok::amp: Opc = BO_And; break;
7483 case tok::caret: Opc = BO_Xor; break;
7484 case tok::pipe: Opc = BO_Or; break;
7485 case tok::ampamp: Opc = BO_LAnd; break;
7486 case tok::pipepipe: Opc = BO_LOr; break;
7487 case tok::equal: Opc = BO_Assign; break;
7488 case tok::starequal: Opc = BO_MulAssign; break;
7489 case tok::slashequal: Opc = BO_DivAssign; break;
7490 case tok::percentequal: Opc = BO_RemAssign; break;
7491 case tok::plusequal: Opc = BO_AddAssign; break;
7492 case tok::minusequal: Opc = BO_SubAssign; break;
7493 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7494 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7495 case tok::ampequal: Opc = BO_AndAssign; break;
7496 case tok::caretequal: Opc = BO_XorAssign; break;
7497 case tok::pipeequal: Opc = BO_OrAssign; break;
7498 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007499 }
7500 return Opc;
7501}
7502
John McCalle3027922010-08-25 11:45:40 +00007503static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007504 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007505 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007506 switch (Kind) {
7507 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007508 case tok::plusplus: Opc = UO_PreInc; break;
7509 case tok::minusminus: Opc = UO_PreDec; break;
7510 case tok::amp: Opc = UO_AddrOf; break;
7511 case tok::star: Opc = UO_Deref; break;
7512 case tok::plus: Opc = UO_Plus; break;
7513 case tok::minus: Opc = UO_Minus; break;
7514 case tok::tilde: Opc = UO_Not; break;
7515 case tok::exclaim: Opc = UO_LNot; break;
7516 case tok::kw___real: Opc = UO_Real; break;
7517 case tok::kw___imag: Opc = UO_Imag; break;
7518 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007519 }
7520 return Opc;
7521}
7522
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007523/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7524/// This warning is only emitted for builtin assignment operations. It is also
7525/// suppressed in the event of macro expansions.
7526static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7527 SourceLocation OpLoc) {
7528 if (!S.ActiveTemplateInstantiations.empty())
7529 return;
7530 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7531 return;
7532 lhs = lhs->IgnoreParenImpCasts();
7533 rhs = rhs->IgnoreParenImpCasts();
7534 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7535 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7536 if (!LeftDeclRef || !RightDeclRef ||
7537 LeftDeclRef->getLocation().isMacroID() ||
7538 RightDeclRef->getLocation().isMacroID())
7539 return;
7540 const ValueDecl *LeftDecl =
7541 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7542 const ValueDecl *RightDecl =
7543 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7544 if (LeftDecl != RightDecl)
7545 return;
7546 if (LeftDecl->getType().isVolatileQualified())
7547 return;
7548 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7549 if (RefTy->getPointeeType().isVolatileQualified())
7550 return;
7551
7552 S.Diag(OpLoc, diag::warn_self_assignment)
7553 << LeftDeclRef->getType()
7554 << lhs->getSourceRange() << rhs->getSourceRange();
7555}
7556
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007557/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7558/// operator @p Opc at location @c TokLoc. This routine only supports
7559/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007560ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007561 BinaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00007562 Expr *lhsExpr, Expr *rhsExpr) {
7563 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007564 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007565 // The following two variables are used for compound assignment operators
7566 QualType CompLHSTy; // Type of LHS after promotions for computation
7567 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007568 ExprValueKind VK = VK_RValue;
7569 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007570
Douglas Gregor1beec452011-03-12 01:48:56 +00007571 // Check if a 'foo<int>' involved in a binary op, identifies a single
7572 // function unambiguously (i.e. an lvalue ala 13.4)
7573 // But since an assignment can trigger target based overload, exclude it in
7574 // our blind search. i.e:
7575 // template<class T> void f(); template<class T, class U> void f(U);
7576 // f<int> == 0; // resolve f<int> blindly
7577 // void (*p)(int); p = f<int>; // resolve f<int> using target
7578 if (Opc != BO_Assign) {
John McCall3aef3d82011-04-10 19:13:55 +00007579 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall31996342011-04-07 08:22:57 +00007580 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007581 lhs = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00007582
John McCall3aef3d82011-04-10 19:13:55 +00007583 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall31996342011-04-07 08:22:57 +00007584 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007585 rhs = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00007586 }
7587
Eli Friedman8e6f5a62011-06-17 20:52:22 +00007588 // The canonical way to check for a GNU null is with isNullPointerConstant,
7589 // but we use a bit of a hack here for speed; this is a relatively
7590 // hot path, and isNullPointerConstant is slow.
7591 bool LeftNull = isa<GNUNullExpr>(lhs.get()->IgnoreParenImpCasts());
7592 bool RightNull = isa<GNUNullExpr>(rhs.get()->IgnoreParenImpCasts());
Richard Trieu701fb362011-06-16 21:36:56 +00007593
7594 // Detect when a NULL constant is used improperly in an expression. These
7595 // are mainly cases where the null pointer is used as an integer instead
7596 // of a pointer.
7597 if (LeftNull || RightNull) {
Chandler Carruth4f04b432011-06-20 07:38:51 +00007598 // Avoid analyzing cases where the result will either be invalid (and
7599 // diagnosed as such) or entirely valid and not something to warn about.
7600 QualType LeftType = lhs.get()->getType();
7601 QualType RightType = rhs.get()->getType();
7602 if (!LeftType->isBlockPointerType() && !LeftType->isMemberPointerType() &&
7603 !LeftType->isFunctionType() &&
7604 !RightType->isBlockPointerType() &&
7605 !RightType->isMemberPointerType() &&
7606 !RightType->isFunctionType()) {
7607 if (Opc == BO_Mul || Opc == BO_Div || Opc == BO_Rem || Opc == BO_Add ||
7608 Opc == BO_Sub || Opc == BO_Shl || Opc == BO_Shr || Opc == BO_And ||
7609 Opc == BO_Xor || Opc == BO_Or || Opc == BO_MulAssign ||
7610 Opc == BO_DivAssign || Opc == BO_AddAssign || Opc == BO_SubAssign ||
7611 Opc == BO_RemAssign || Opc == BO_ShlAssign || Opc == BO_ShrAssign ||
7612 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign) {
7613 // These are the operations that would not make sense with a null pointer
Richard Trieucfc491d2011-08-02 04:35:43 +00007614 // pointer no matter what the other expression is.
Chandler Carruthe1db1cf2011-06-19 09:05:14 +00007615 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
Chandler Carruth4f04b432011-06-20 07:38:51 +00007616 << (LeftNull ? lhs.get()->getSourceRange() : SourceRange())
7617 << (RightNull ? rhs.get()->getSourceRange() : SourceRange());
7618 } else if (Opc == BO_LE || Opc == BO_LT || Opc == BO_GE || Opc == BO_GT ||
7619 Opc == BO_EQ || Opc == BO_NE) {
7620 // These are the operations that would not make sense with a null pointer
7621 // if the other expression the other expression is not a pointer.
7622 if (LeftNull != RightNull &&
7623 !LeftType->isAnyPointerType() &&
7624 !LeftType->canDecayToPointerType() &&
7625 !RightType->isAnyPointerType() &&
7626 !RightType->canDecayToPointerType()) {
7627 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
7628 << (LeftNull ? lhs.get()->getSourceRange()
7629 : rhs.get()->getSourceRange());
7630 }
Richard Trieu701fb362011-06-16 21:36:56 +00007631 }
7632 }
7633 }
7634
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007635 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007636 case BO_Assign:
John Wiegley01296292011-04-08 18:41:53 +00007637 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007638 if (getLangOptions().CPlusPlus &&
John Wiegley01296292011-04-08 18:41:53 +00007639 lhs.get()->getObjectKind() != OK_ObjCProperty) {
7640 VK = lhs.get()->getValueKind();
7641 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007642 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007643 if (!ResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00007644 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007645 break;
John McCalle3027922010-08-25 11:45:40 +00007646 case BO_PtrMemD:
7647 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00007648 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007649 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007650 break;
John McCalle3027922010-08-25 11:45:40 +00007651 case BO_Mul:
7652 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007653 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007654 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007655 break;
John McCalle3027922010-08-25 11:45:40 +00007656 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007657 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7658 break;
John McCalle3027922010-08-25 11:45:40 +00007659 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007660 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7661 break;
John McCalle3027922010-08-25 11:45:40 +00007662 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007663 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7664 break;
John McCalle3027922010-08-25 11:45:40 +00007665 case BO_Shl:
7666 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007667 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007668 break;
John McCalle3027922010-08-25 11:45:40 +00007669 case BO_LE:
7670 case BO_LT:
7671 case BO_GE:
7672 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007673 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007674 break;
John McCalle3027922010-08-25 11:45:40 +00007675 case BO_EQ:
7676 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007677 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007678 break;
John McCalle3027922010-08-25 11:45:40 +00007679 case BO_And:
7680 case BO_Xor:
7681 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007682 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7683 break;
John McCalle3027922010-08-25 11:45:40 +00007684 case BO_LAnd:
7685 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00007686 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007687 break;
John McCalle3027922010-08-25 11:45:40 +00007688 case BO_MulAssign:
7689 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00007690 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007691 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007692 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007693 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7694 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007695 break;
John McCalle3027922010-08-25 11:45:40 +00007696 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007697 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7698 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007699 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7700 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007701 break;
John McCalle3027922010-08-25 11:45:40 +00007702 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007703 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007704 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7705 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007706 break;
John McCalle3027922010-08-25 11:45:40 +00007707 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007708 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007709 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7710 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007711 break;
John McCalle3027922010-08-25 11:45:40 +00007712 case BO_ShlAssign:
7713 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007714 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007715 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007716 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7717 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007718 break;
John McCalle3027922010-08-25 11:45:40 +00007719 case BO_AndAssign:
7720 case BO_XorAssign:
7721 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007722 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7723 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00007724 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
7725 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007726 break;
John McCalle3027922010-08-25 11:45:40 +00007727 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00007728 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00007729 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
7730 VK = rhs.get()->getValueKind();
7731 OK = rhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007732 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007733 break;
7734 }
John Wiegley01296292011-04-08 18:41:53 +00007735 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007736 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007737
7738 // Check for array bounds violations for both sides of the BinaryOperator
7739 CheckArrayAccess(lhs.get());
7740 CheckArrayAccess(rhs.get());
7741
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007742 if (CompResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00007743 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
7744 ResultTy, VK, OK, OpLoc));
Richard Trieucfc491d2011-08-02 04:35:43 +00007745 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() !=
7746 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007747 VK = VK_LValue;
John Wiegley01296292011-04-08 18:41:53 +00007748 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007749 }
John Wiegley01296292011-04-08 18:41:53 +00007750 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
7751 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00007752 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007753}
7754
Sebastian Redl44615072009-10-27 12:10:02 +00007755/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7756/// operators are mixed in a way that suggests that the programmer forgot that
7757/// comparison operators have higher precedence. The most typical example of
7758/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007759static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007760 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00007761 typedef BinaryOperator BinOp;
7762 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7763 rhsopc = static_cast<BinOp::Opcode>(-1);
7764 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007765 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00007766 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00007767 rhsopc = BO->getOpcode();
7768
7769 // Subs are not binary operators.
7770 if (lhsopc == -1 && rhsopc == -1)
7771 return;
7772
7773 // Bitwise operations are sometimes used as eager logical ops.
7774 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00007775 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7776 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007777 return;
7778
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007779 if (BinOp::isComparisonOp(lhsopc)) {
7780 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7781 << SourceRange(lhs->getLocStart(), OpLoc)
7782 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc);
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007783 SuggestParentheses(Self, OpLoc,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00007784 Self.PDiag(diag::note_precedence_bitwise_silence)
7785 << BinOp::getOpcodeStr(lhsopc),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007786 lhs->getSourceRange());
7787 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00007788 Self.PDiag(diag::note_precedence_bitwise_first)
7789 << BinOp::getOpcodeStr(Opc),
7790 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007791 } else if (BinOp::isComparisonOp(rhsopc)) {
7792 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7793 << SourceRange(OpLoc, rhs->getLocEnd())
7794 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc);
Sebastian Redl4afb7c582009-10-26 17:01:32 +00007795 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00007796 Self.PDiag(diag::note_precedence_bitwise_silence)
7797 << BinOp::getOpcodeStr(rhsopc),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007798 rhs->getSourceRange());
7799 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007800 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00007801 << BinOp::getOpcodeStr(Opc),
Douglas Gregorbb9a5e62011-06-22 18:41:08 +00007802 SourceRange(lhs->getLocStart(),
7803 cast<BinOp>(rhs)->getLHS()->getLocStart()));
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007804 }
Sebastian Redl43028242009-10-26 15:24:15 +00007805}
7806
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007807/// \brief It accepts a '&' expr that is inside a '|' one.
7808/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7809/// in parentheses.
7810static void
7811EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7812 BinaryOperator *Bop) {
7813 assert(Bop->getOpcode() == BO_And);
7814 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7815 << Bop->getSourceRange() << OpLoc;
7816 SuggestParentheses(Self, Bop->getOperatorLoc(),
7817 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7818 Bop->getSourceRange());
7819}
7820
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007821/// \brief It accepts a '&&' expr that is inside a '||' one.
7822/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7823/// in parentheses.
7824static void
7825EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007826 BinaryOperator *Bop) {
7827 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007828 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7829 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007830 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007831 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007832 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007833}
7834
7835/// \brief Returns true if the given expression can be evaluated as a constant
7836/// 'true'.
7837static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7838 bool Res;
7839 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7840}
7841
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007842/// \brief Returns true if the given expression can be evaluated as a constant
7843/// 'false'.
7844static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7845 bool Res;
7846 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7847}
7848
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007849/// \brief Look for '&&' in the left hand of a '||' expr.
7850static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007851 Expr *OrLHS, Expr *OrRHS) {
7852 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007853 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007854 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7855 if (EvaluatesAsFalse(S, OrRHS))
7856 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007857 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7858 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7859 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7860 } else if (Bop->getOpcode() == BO_LOr) {
7861 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7862 // If it's "a || b && 1 || c" we didn't warn earlier for
7863 // "a || b && 1", but warn now.
7864 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7865 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7866 }
7867 }
7868 }
7869}
7870
7871/// \brief Look for '&&' in the right hand of a '||' expr.
7872static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007873 Expr *OrLHS, Expr *OrRHS) {
7874 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007875 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007876 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7877 if (EvaluatesAsFalse(S, OrLHS))
7878 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007879 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7880 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7881 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007882 }
7883 }
7884}
7885
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007886/// \brief Look for '&' in the left or right hand of a '|' expr.
7887static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7888 Expr *OrArg) {
7889 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7890 if (Bop->getOpcode() == BO_And)
7891 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7892 }
7893}
7894
Sebastian Redl43028242009-10-26 15:24:15 +00007895/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007896/// precedence.
John McCalle3027922010-08-25 11:45:40 +00007897static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00007898 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007899 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00007900 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007901 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7902
7903 // Diagnose "arg1 & arg2 | arg3"
7904 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7905 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, lhs);
7906 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, rhs);
7907 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007908
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007909 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7910 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00007911 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007912 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7913 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007914 }
Sebastian Redl43028242009-10-26 15:24:15 +00007915}
7916
Steve Naroff218bc2b2007-05-04 21:54:46 +00007917// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00007918ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00007919 tok::TokenKind Kind,
7920 Expr *lhs, Expr *rhs) {
7921 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00007922 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
7923 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00007924
Sebastian Redl43028242009-10-26 15:24:15 +00007925 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7926 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
7927
Douglas Gregor5287f092009-11-05 00:51:44 +00007928 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
7929}
7930
John McCalldadc5752010-08-24 06:29:42 +00007931ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007932 BinaryOperatorKind Opc,
7933 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00007934 if (getLangOptions().CPlusPlus) {
7935 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007936
John McCall622114c2010-12-06 05:26:58 +00007937 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
7938 UseBuiltinOperator = false;
7939 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
7940 UseBuiltinOperator = true;
7941 } else {
7942 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
7943 !rhs->getType()->isOverloadableType();
7944 }
7945
7946 if (!UseBuiltinOperator) {
7947 // Find all of the overloaded operators visible from this
7948 // point. We perform both an operator-name lookup from the local
7949 // scope and an argument-dependent lookup based on the types of
7950 // the arguments.
7951 UnresolvedSet<16> Functions;
7952 OverloadedOperatorKind OverOp
7953 = BinaryOperator::getOverloadedOperator(Opc);
7954 if (S && OverOp != OO_None)
7955 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
7956 Functions);
7957
7958 // Build the (potentially-overloaded, potentially-dependent)
7959 // binary operation.
7960 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
7961 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00007962 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007963
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007964 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00007965 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00007966}
7967
John McCalldadc5752010-08-24 06:29:42 +00007968ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007969 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00007970 Expr *InputExpr) {
7971 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00007972 ExprValueKind VK = VK_RValue;
7973 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00007974 QualType resultType;
7975 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007976 case UO_PreInc:
7977 case UO_PreDec:
7978 case UO_PostInc:
7979 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00007980 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007981 Opc == UO_PreInc ||
7982 Opc == UO_PostInc,
7983 Opc == UO_PreInc ||
7984 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00007985 break;
John McCalle3027922010-08-25 11:45:40 +00007986 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00007987 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007988 break;
John McCall31996342011-04-07 08:22:57 +00007989 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00007990 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00007991 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007992 Input = move(resolved);
7993 Input = DefaultFunctionArrayLvalueConversion(Input.take());
7994 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00007995 break;
John McCall31996342011-04-07 08:22:57 +00007996 }
John McCalle3027922010-08-25 11:45:40 +00007997 case UO_Plus:
7998 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00007999 Input = UsualUnaryConversions(Input.take());
8000 if (Input.isInvalid()) return ExprError();
8001 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008002 if (resultType->isDependentType())
8003 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008004 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8005 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008006 break;
8007 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8008 resultType->isEnumeralType())
8009 break;
8010 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008011 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008012 resultType->isPointerType())
8013 break;
John McCall36226622010-10-12 02:09:17 +00008014 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008015 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008016 if (Input.isInvalid()) return ExprError();
8017 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008018 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008019
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008020 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008021 << resultType << Input.get()->getSourceRange());
8022
John McCalle3027922010-08-25 11:45:40 +00008023 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008024 Input = UsualUnaryConversions(Input.take());
8025 if (Input.isInvalid()) return ExprError();
8026 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008027 if (resultType->isDependentType())
8028 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008029 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8030 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8031 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008032 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008033 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008034 else if (resultType->hasIntegerRepresentation())
8035 break;
8036 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008037 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008038 if (Input.isInvalid()) return ExprError();
8039 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008040 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008041 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008042 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008043 }
Steve Naroff35d85152007-05-07 00:24:15 +00008044 break;
John Wiegley01296292011-04-08 18:41:53 +00008045
John McCalle3027922010-08-25 11:45:40 +00008046 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008047 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008048 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8049 if (Input.isInvalid()) return ExprError();
8050 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008051 if (resultType->isDependentType())
8052 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008053 if (resultType->isScalarType()) {
8054 // C99 6.5.3.3p1: ok, fallthrough;
8055 if (Context.getLangOptions().CPlusPlus) {
8056 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8057 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008058 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8059 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008060 }
John McCall36226622010-10-12 02:09:17 +00008061 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008062 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008063 if (Input.isInvalid()) return ExprError();
8064 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008065 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008066 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008067 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008068 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008069
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008070 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008071 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008072 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008073 break;
John McCalle3027922010-08-25 11:45:40 +00008074 case UO_Real:
8075 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008076 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008077 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00008078 if (Input.isInvalid()) return ExprError();
8079 if (Input.get()->getValueKind() != VK_RValue &&
8080 Input.get()->getObjectKind() == OK_Ordinary)
8081 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008082 break;
John McCalle3027922010-08-25 11:45:40 +00008083 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008084 resultType = Input.get()->getType();
8085 VK = Input.get()->getValueKind();
8086 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008087 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008088 }
John Wiegley01296292011-04-08 18:41:53 +00008089 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008090 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008091
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008092 // Check for array bounds violations in the operand of the UnaryOperator,
8093 // except for the '*' and '&' operators that have to be handled specially
8094 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8095 // that are explicitly defined as valid by the standard).
8096 if (Opc != UO_AddrOf && Opc != UO_Deref)
8097 CheckArrayAccess(Input.get());
8098
John Wiegley01296292011-04-08 18:41:53 +00008099 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008100 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008101}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008102
John McCalldadc5752010-08-24 06:29:42 +00008103ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008104 UnaryOperatorKind Opc,
8105 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008106 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008107 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008108 // Find all of the overloaded operators visible from this
8109 // point. We perform both an operator-name lookup from the local
8110 // scope and an argument-dependent lookup based on the types of
8111 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008112 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008113 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008114 if (S && OverOp != OO_None)
8115 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8116 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008117
John McCallb268a282010-08-23 23:25:46 +00008118 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008119 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008120
John McCallb268a282010-08-23 23:25:46 +00008121 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008122}
8123
Douglas Gregor5287f092009-11-05 00:51:44 +00008124// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008125ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008126 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008127 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008128}
8129
Steve Naroff66356bd2007-09-16 14:56:35 +00008130/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008131ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008132 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008133 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008134 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008135 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008136 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008137}
8138
John McCall31168b02011-06-15 23:02:42 +00008139/// Given the last statement in a statement-expression, check whether
8140/// the result is a producing expression (like a call to an
8141/// ns_returns_retained function) and, if so, rebuild it to hoist the
8142/// release out of the full-expression. Otherwise, return null.
8143/// Cannot fail.
8144static Expr *maybeRebuildARCConsumingStmt(Stmt *s) {
8145 // Should always be wrapped with one of these.
8146 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(s);
8147 if (!cleanups) return 0;
8148
8149 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
8150 if (!cast || cast->getCastKind() != CK_ObjCConsumeObject)
8151 return 0;
8152
8153 // Splice out the cast. This shouldn't modify any interesting
8154 // features of the statement.
8155 Expr *producer = cast->getSubExpr();
8156 assert(producer->getType() == cast->getType());
8157 assert(producer->getValueKind() == cast->getValueKind());
8158 cleanups->setSubExpr(producer);
8159 return cleanups;
8160}
8161
John McCalldadc5752010-08-24 06:29:42 +00008162ExprResult
John McCallb268a282010-08-23 23:25:46 +00008163Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008164 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008165 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8166 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8167
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008168 bool isFileScope
8169 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008170 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008171 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008172
Chris Lattner366727f2007-07-24 16:58:17 +00008173 // FIXME: there are a variety of strange constraints to enforce here, for
8174 // example, it is not possible to goto into a stmt expression apparently.
8175 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008176
Chris Lattner366727f2007-07-24 16:58:17 +00008177 // If there are sub stmts in the compound stmt, take the type of the last one
8178 // as the type of the stmtexpr.
8179 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008180 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008181 if (!Compound->body_empty()) {
8182 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008183 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008184 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008185 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8186 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008187 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008188 }
John McCall31168b02011-06-15 23:02:42 +00008189
John Wiegley01296292011-04-08 18:41:53 +00008190 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008191 // Do function/array conversion on the last expression, but not
8192 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008193 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8194 if (LastExpr.isInvalid())
8195 return ExprError();
8196 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008197
John Wiegley01296292011-04-08 18:41:53 +00008198 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008199 // In ARC, if the final expression ends in a consume, splice
8200 // the consume out and bind it later. In the alternate case
8201 // (when dealing with a retainable type), the result
8202 // initialization will create a produce. In both cases the
8203 // result will be +1, and we'll need to balance that out with
8204 // a bind.
8205 if (Expr *rebuiltLastStmt
8206 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8207 LastExpr = rebuiltLastStmt;
8208 } else {
8209 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008210 InitializedEntity::InitializeResult(LPLoc,
8211 Ty,
8212 false),
8213 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008214 LastExpr);
8215 }
8216
John Wiegley01296292011-04-08 18:41:53 +00008217 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008218 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008219 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008220 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008221 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008222 else
John Wiegley01296292011-04-08 18:41:53 +00008223 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008224 StmtExprMayBindToTemp = true;
8225 }
8226 }
8227 }
Chris Lattner944d3062008-07-26 19:51:01 +00008228 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008229
Eli Friedmanba961a92009-03-23 00:24:07 +00008230 // FIXME: Check that expression type is complete/non-abstract; statement
8231 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008232 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8233 if (StmtExprMayBindToTemp)
8234 return MaybeBindToTemporary(ResStmtExpr);
8235 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008236}
Steve Naroff78864672007-08-01 22:05:33 +00008237
John McCalldadc5752010-08-24 06:29:42 +00008238ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008239 TypeSourceInfo *TInfo,
8240 OffsetOfComponent *CompPtr,
8241 unsigned NumComponents,
8242 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008243 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008244 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008245 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008246
Chris Lattnerf17bd422007-08-30 17:45:32 +00008247 // We must have at least one component that refers to the type, and the first
8248 // one is known to be a field designator. Verify that the ArgTy represents
8249 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008250 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008251 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8252 << ArgTy << TypeRange);
8253
8254 // Type must be complete per C99 7.17p3 because a declaring a variable
8255 // with an incomplete type would be ill-formed.
8256 if (!Dependent
8257 && RequireCompleteType(BuiltinLoc, ArgTy,
8258 PDiag(diag::err_offsetof_incomplete_type)
8259 << TypeRange))
8260 return ExprError();
8261
Chris Lattner78502cf2007-08-31 21:49:13 +00008262 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8263 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008264 // FIXME: This diagnostic isn't actually visible because the location is in
8265 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008266 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008267 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8268 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008269
8270 bool DidWarnAboutNonPOD = false;
8271 QualType CurrentType = ArgTy;
8272 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008273 SmallVector<OffsetOfNode, 4> Comps;
8274 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008275 for (unsigned i = 0; i != NumComponents; ++i) {
8276 const OffsetOfComponent &OC = CompPtr[i];
8277 if (OC.isBrackets) {
8278 // Offset of an array sub-field. TODO: Should we allow vector elements?
8279 if (!CurrentType->isDependentType()) {
8280 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8281 if(!AT)
8282 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8283 << CurrentType);
8284 CurrentType = AT->getElementType();
8285 } else
8286 CurrentType = Context.DependentTy;
8287
8288 // The expression must be an integral expression.
8289 // FIXME: An integral constant expression?
8290 Expr *Idx = static_cast<Expr*>(OC.U.E);
8291 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8292 !Idx->getType()->isIntegerType())
8293 return ExprError(Diag(Idx->getLocStart(),
8294 diag::err_typecheck_subscript_not_integer)
8295 << Idx->getSourceRange());
8296
8297 // Record this array index.
8298 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8299 Exprs.push_back(Idx);
8300 continue;
8301 }
8302
8303 // Offset of a field.
8304 if (CurrentType->isDependentType()) {
8305 // We have the offset of a field, but we can't look into the dependent
8306 // type. Just record the identifier of the field.
8307 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8308 CurrentType = Context.DependentTy;
8309 continue;
8310 }
8311
8312 // We need to have a complete type to look into.
8313 if (RequireCompleteType(OC.LocStart, CurrentType,
8314 diag::err_offsetof_incomplete_type))
8315 return ExprError();
8316
8317 // Look for the designated field.
8318 const RecordType *RC = CurrentType->getAs<RecordType>();
8319 if (!RC)
8320 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8321 << CurrentType);
8322 RecordDecl *RD = RC->getDecl();
8323
8324 // C++ [lib.support.types]p5:
8325 // The macro offsetof accepts a restricted set of type arguments in this
8326 // International Standard. type shall be a POD structure or a POD union
8327 // (clause 9).
8328 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8329 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008330 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008331 PDiag(diag::warn_offsetof_non_pod_type)
8332 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8333 << CurrentType))
8334 DidWarnAboutNonPOD = true;
8335 }
8336
8337 // Look for the field.
8338 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8339 LookupQualifiedName(R, RD);
8340 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008341 IndirectFieldDecl *IndirectMemberDecl = 0;
8342 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008343 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008344 MemberDecl = IndirectMemberDecl->getAnonField();
8345 }
8346
Douglas Gregor882211c2010-04-28 22:16:22 +00008347 if (!MemberDecl)
8348 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8349 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8350 OC.LocEnd));
8351
Douglas Gregor10982ea2010-04-28 22:36:06 +00008352 // C99 7.17p3:
8353 // (If the specified member is a bit-field, the behavior is undefined.)
8354 //
8355 // We diagnose this as an error.
8356 if (MemberDecl->getBitWidth()) {
8357 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8358 << MemberDecl->getDeclName()
8359 << SourceRange(BuiltinLoc, RParenLoc);
8360 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8361 return ExprError();
8362 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008363
8364 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008365 if (IndirectMemberDecl)
8366 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008367
Douglas Gregord1702062010-04-29 00:18:15 +00008368 // If the member was found in a base class, introduce OffsetOfNodes for
8369 // the base class indirections.
8370 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8371 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008372 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008373 CXXBasePath &Path = Paths.front();
8374 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8375 B != BEnd; ++B)
8376 Comps.push_back(OffsetOfNode(B->Base));
8377 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008378
Francois Pichet783dd6e2010-11-21 06:08:52 +00008379 if (IndirectMemberDecl) {
8380 for (IndirectFieldDecl::chain_iterator FI =
8381 IndirectMemberDecl->chain_begin(),
8382 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8383 assert(isa<FieldDecl>(*FI));
8384 Comps.push_back(OffsetOfNode(OC.LocStart,
8385 cast<FieldDecl>(*FI), OC.LocEnd));
8386 }
8387 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008388 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008389
Douglas Gregor882211c2010-04-28 22:16:22 +00008390 CurrentType = MemberDecl->getType().getNonReferenceType();
8391 }
8392
8393 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8394 TInfo, Comps.data(), Comps.size(),
8395 Exprs.data(), Exprs.size(), RParenLoc));
8396}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008397
John McCalldadc5752010-08-24 06:29:42 +00008398ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008399 SourceLocation BuiltinLoc,
8400 SourceLocation TypeLoc,
8401 ParsedType argty,
8402 OffsetOfComponent *CompPtr,
8403 unsigned NumComponents,
8404 SourceLocation RPLoc) {
8405
Douglas Gregor882211c2010-04-28 22:16:22 +00008406 TypeSourceInfo *ArgTInfo;
8407 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8408 if (ArgTy.isNull())
8409 return ExprError();
8410
Eli Friedman06dcfd92010-08-05 10:15:45 +00008411 if (!ArgTInfo)
8412 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8413
8414 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8415 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008416}
8417
8418
John McCalldadc5752010-08-24 06:29:42 +00008419ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008420 Expr *CondExpr,
8421 Expr *LHSExpr, Expr *RHSExpr,
8422 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008423 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8424
John McCall7decc9e2010-11-18 06:31:45 +00008425 ExprValueKind VK = VK_RValue;
8426 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008427 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008428 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008429 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008430 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008431 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008432 } else {
8433 // The conditional expression is required to be a constant expression.
8434 llvm::APSInt condEval(32);
8435 SourceLocation ExpLoc;
8436 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008437 return ExprError(Diag(ExpLoc,
8438 diag::err_typecheck_choose_expr_requires_constant)
8439 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008440
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008441 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008442 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8443
8444 resType = ActiveExpr->getType();
8445 ValueDependent = ActiveExpr->isValueDependent();
8446 VK = ActiveExpr->getValueKind();
8447 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008448 }
8449
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008450 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008451 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008452 resType->isDependentType(),
8453 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008454}
8455
Steve Naroffc540d662008-09-03 18:15:37 +00008456//===----------------------------------------------------------------------===//
8457// Clang Extensions.
8458//===----------------------------------------------------------------------===//
8459
8460/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008461void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008462 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8463 PushBlockScope(BlockScope, Block);
8464 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008465 if (BlockScope)
8466 PushDeclContext(BlockScope, Block);
8467 else
8468 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008469}
8470
Mike Stump82f071f2009-02-04 22:31:32 +00008471void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008472 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008473 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008474 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008475
John McCall8cb7bdf2010-06-04 23:28:52 +00008476 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008477 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008478
John McCall3882ace2011-01-05 12:14:39 +00008479 // GetTypeForDeclarator always produces a function type for a block
8480 // literal signature. Furthermore, it is always a FunctionProtoType
8481 // unless the function was written with a typedef.
8482 assert(T->isFunctionType() &&
8483 "GetTypeForDeclarator made a non-function block signature");
8484
8485 // Look for an explicit signature in that function type.
8486 FunctionProtoTypeLoc ExplicitSignature;
8487
8488 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8489 if (isa<FunctionProtoTypeLoc>(tmp)) {
8490 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8491
8492 // Check whether that explicit signature was synthesized by
8493 // GetTypeForDeclarator. If so, don't save that as part of the
8494 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008495 if (ExplicitSignature.getLocalRangeBegin() ==
8496 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008497 // This would be much cheaper if we stored TypeLocs instead of
8498 // TypeSourceInfos.
8499 TypeLoc Result = ExplicitSignature.getResultLoc();
8500 unsigned Size = Result.getFullDataSize();
8501 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8502 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8503
8504 ExplicitSignature = FunctionProtoTypeLoc();
8505 }
John McCalla3ccba02010-06-04 11:21:44 +00008506 }
Mike Stump11289f42009-09-09 15:08:12 +00008507
John McCall3882ace2011-01-05 12:14:39 +00008508 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8509 CurBlock->FunctionType = T;
8510
8511 const FunctionType *Fn = T->getAs<FunctionType>();
8512 QualType RetTy = Fn->getResultType();
8513 bool isVariadic =
8514 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8515
John McCall8e346702010-06-04 19:02:56 +00008516 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008517
John McCalla3ccba02010-06-04 11:21:44 +00008518 // Don't allow returning a objc interface by value.
8519 if (RetTy->isObjCObjectType()) {
8520 Diag(ParamInfo.getSourceRange().getBegin(),
8521 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8522 return;
8523 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008524
John McCalla3ccba02010-06-04 11:21:44 +00008525 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008526 // return type. TODO: what should we do with declarators like:
8527 // ^ * { ... }
8528 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008529 if (RetTy != Context.DependentTy)
8530 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008531
John McCalla3ccba02010-06-04 11:21:44 +00008532 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008533 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008534 if (ExplicitSignature) {
8535 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8536 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008537 if (Param->getIdentifier() == 0 &&
8538 !Param->isImplicit() &&
8539 !Param->isInvalidDecl() &&
8540 !getLangOptions().CPlusPlus)
8541 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008542 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008543 }
John McCalla3ccba02010-06-04 11:21:44 +00008544
8545 // Fake up parameter variables if we have a typedef, like
8546 // ^ fntype { ... }
8547 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8548 for (FunctionProtoType::arg_type_iterator
8549 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8550 ParmVarDecl *Param =
8551 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8552 ParamInfo.getSourceRange().getBegin(),
8553 *I);
John McCall8e346702010-06-04 19:02:56 +00008554 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008555 }
Steve Naroffc540d662008-09-03 18:15:37 +00008556 }
John McCalla3ccba02010-06-04 11:21:44 +00008557
John McCall8e346702010-06-04 19:02:56 +00008558 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008559 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00008560 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00008561 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8562 CurBlock->TheDecl->param_end(),
8563 /*CheckParameterNames=*/false);
8564 }
8565
John McCalla3ccba02010-06-04 11:21:44 +00008566 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008567 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008568
John McCall8e346702010-06-04 19:02:56 +00008569 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008570 Diag(ParamInfo.getAttributes()->getLoc(),
8571 diag::warn_attribute_sentinel_not_variadic) << 1;
8572 // FIXME: remove the attribute.
8573 }
8574
8575 // Put the parameter variables in scope. We can bail out immediately
8576 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008577 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008578 return;
8579
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008580 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008581 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8582 (*AI)->setOwningFunction(CurBlock->TheDecl);
8583
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008584 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008585 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008586 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008587
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008588 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008589 }
John McCallf7b2fb52010-01-22 00:28:27 +00008590 }
Steve Naroffc540d662008-09-03 18:15:37 +00008591}
8592
8593/// ActOnBlockError - If there is an error parsing a block, this callback
8594/// is invoked to pop the information about the block from the action impl.
8595void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008596 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008597 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008598 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008599}
8600
8601/// ActOnBlockStmtExpr - This is called when the body of a block statement
8602/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008603ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008604 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008605 // If blocks are disabled, emit an error.
8606 if (!LangOpts.Blocks)
8607 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008608
Douglas Gregor9a28e842010-03-01 23:15:13 +00008609 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008610
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008611 PopDeclContext();
8612
Steve Naroffc540d662008-09-03 18:15:37 +00008613 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008614 if (!BSI->ReturnType.isNull())
8615 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008616
Mike Stump3bf1ab42009-07-28 22:04:01 +00008617 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008618 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008619
John McCallc63de662011-02-02 13:00:07 +00008620 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008621 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8622 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00008623
John McCall8e346702010-06-04 19:02:56 +00008624 // If the user wrote a function type in some form, try to use that.
8625 if (!BSI->FunctionType.isNull()) {
8626 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8627
8628 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8629 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8630
8631 // Turn protoless block types into nullary block types.
8632 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008633 FunctionProtoType::ExtProtoInfo EPI;
8634 EPI.ExtInfo = Ext;
8635 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008636
8637 // Otherwise, if we don't need to change anything about the function type,
8638 // preserve its sugar structure.
8639 } else if (FTy->getResultType() == RetTy &&
8640 (!NoReturn || FTy->getNoReturnAttr())) {
8641 BlockTy = BSI->FunctionType;
8642
8643 // Otherwise, make the minimal modifications to the function type.
8644 } else {
8645 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008646 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8647 EPI.TypeQuals = 0; // FIXME: silently?
8648 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008649 BlockTy = Context.getFunctionType(RetTy,
8650 FPT->arg_type_begin(),
8651 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008652 EPI);
John McCall8e346702010-06-04 19:02:56 +00008653 }
8654
8655 // If we don't have a function type, just build one from nothing.
8656 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008657 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00008658 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008659 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008660 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008661
John McCall8e346702010-06-04 19:02:56 +00008662 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8663 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008664 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008665
Chris Lattner45542ea2009-04-19 05:28:12 +00008666 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00008667 if (getCurFunction()->NeedsScopeChecking() &&
8668 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008669 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008670
Chris Lattner60f84492011-02-17 23:58:47 +00008671 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008672
Fariborz Jahanian256d39d2011-07-11 18:04:54 +00008673 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8674 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8675 const VarDecl *variable = ci->getVariable();
8676 QualType T = variable->getType();
8677 QualType::DestructionKind destructKind = T.isDestructedType();
8678 if (destructKind != QualType::DK_none)
8679 getCurFunction()->setHasBranchProtectedScope();
8680 }
8681
Benjamin Kramera4fb8362011-07-12 14:11:05 +00008682 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8683 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8684 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8685
Douglas Gregor9a28e842010-03-01 23:15:13 +00008686 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008687}
8688
John McCalldadc5752010-08-24 06:29:42 +00008689ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00008690 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008691 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008692 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00008693 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00008694 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008695}
8696
John McCalldadc5752010-08-24 06:29:42 +00008697ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008698 Expr *E, TypeSourceInfo *TInfo,
8699 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008700 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008701
Eli Friedman121ba0c2008-08-09 23:32:40 +00008702 // Get the va_list type
8703 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008704 if (VaListType->isArrayType()) {
8705 // Deal with implicit array decay; for example, on x86-64,
8706 // va_list is an array, but it's supposed to decay to
8707 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008708 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008709 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00008710 ExprResult Result = UsualUnaryConversions(E);
8711 if (Result.isInvalid())
8712 return ExprError();
8713 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00008714 } else {
8715 // Otherwise, the va_list argument must be an l-value because
8716 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008717 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008718 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008719 return ExprError();
8720 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008721
Douglas Gregorad3150c2009-05-19 23:10:31 +00008722 if (!E->isTypeDependent() &&
8723 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008724 return ExprError(Diag(E->getLocStart(),
8725 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008726 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008727 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008728
David Majnemerc75d1a12011-06-14 05:17:32 +00008729 if (!TInfo->getType()->isDependentType()) {
8730 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8731 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8732 << TInfo->getTypeLoc().getSourceRange()))
8733 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00008734
David Majnemerc75d1a12011-06-14 05:17:32 +00008735 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8736 TInfo->getType(),
8737 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8738 << TInfo->getTypeLoc().getSourceRange()))
8739 return ExprError();
8740
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008741 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00008742 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008743 TInfo->getType()->isObjCLifetimeType()
8744 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8745 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00008746 << TInfo->getType()
8747 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008748 }
Eli Friedman6290ae42011-07-11 21:45:59 +00008749
8750 // Check for va_arg where arguments of the given type will be promoted
8751 // (i.e. this va_arg is guaranteed to have undefined behavior).
8752 QualType PromoteType;
8753 if (TInfo->getType()->isPromotableIntegerType()) {
8754 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8755 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8756 PromoteType = QualType();
8757 }
8758 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8759 PromoteType = Context.DoubleTy;
8760 if (!PromoteType.isNull())
8761 Diag(TInfo->getTypeLoc().getBeginLoc(),
8762 diag::warn_second_parameter_to_va_arg_never_compatible)
8763 << TInfo->getType()
8764 << PromoteType
8765 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00008766 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008767
Abramo Bagnara27db2392010-08-10 10:06:15 +00008768 QualType T = TInfo->getType().getNonLValueExprType(Context);
8769 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008770}
8771
John McCalldadc5752010-08-24 06:29:42 +00008772ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008773 // The type of __null will be int or long, depending on the size of
8774 // pointers on the target.
8775 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008776 unsigned pw = Context.Target.getPointerWidth(0);
8777 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008778 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008779 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008780 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008781 else if (pw == Context.Target.getLongLongWidth())
8782 Ty = Context.LongLongTy;
8783 else {
8784 assert(!"I don't know size of pointer!");
8785 Ty = Context.IntTy;
8786 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00008787
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008788 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008789}
8790
Alexis Huntc46382e2010-04-28 23:02:27 +00008791static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008792 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008793 if (!SemaRef.getLangOptions().ObjC1)
8794 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008795
Anders Carlssonace5d072009-11-10 04:46:30 +00008796 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8797 if (!PT)
8798 return;
8799
8800 // Check if the destination is of type 'id'.
8801 if (!PT->isObjCIdType()) {
8802 // Check if the destination is the 'NSString' interface.
8803 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8804 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8805 return;
8806 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008807
Anders Carlssonace5d072009-11-10 04:46:30 +00008808 // Strip off any parens and casts.
8809 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregorfb65e592011-07-27 05:40:30 +00008810 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00008811 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008812
Douglas Gregora771f462010-03-31 17:46:05 +00008813 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00008814}
8815
Chris Lattner9bad62c2008-01-04 18:04:52 +00008816bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8817 SourceLocation Loc,
8818 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008819 Expr *SrcExpr, AssignmentAction Action,
8820 bool *Complained) {
8821 if (Complained)
8822 *Complained = false;
8823
Chris Lattner9bad62c2008-01-04 18:04:52 +00008824 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00008825 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008826 bool isInvalid = false;
8827 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00008828 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00008829 ConversionFixItGenerator ConvHints;
8830 bool MayHaveConvFixit = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008831
Chris Lattner9bad62c2008-01-04 18:04:52 +00008832 switch (ConvTy) {
8833 default: assert(0 && "Unknown conversion type");
8834 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008835 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00008836 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00008837 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8838 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008839 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008840 case IntToPointer:
8841 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00008842 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8843 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00008844 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008845 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00008846 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00008847 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00008848 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
8849 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00008850 if (Hint.isNull() && !CheckInferredResultType) {
8851 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8852 }
8853 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008854 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00008855 case IncompatiblePointerSign:
8856 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8857 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008858 case FunctionVoidPointer:
8859 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8860 break;
John McCall4fff8f62011-02-01 00:10:29 +00008861 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00008862 // Perform array-to-pointer decay if necessary.
8863 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8864
John McCall4fff8f62011-02-01 00:10:29 +00008865 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8866 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8867 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8868 DiagKind = diag::err_typecheck_incompatible_address_space;
8869 break;
John McCall31168b02011-06-15 23:02:42 +00008870
8871
8872 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008873 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00008874 break;
John McCall4fff8f62011-02-01 00:10:29 +00008875 }
8876
8877 llvm_unreachable("unknown error case for discarding qualifiers!");
8878 // fallthrough
8879 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00008880 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008881 // If the qualifiers lost were because we were applying the
8882 // (deprecated) C++ conversion from a string literal to a char*
8883 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8884 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00008885 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008886 // bit of refactoring (so that the second argument is an
8887 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00008888 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00008889 // C++ semantics.
8890 if (getLangOptions().CPlusPlus &&
8891 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8892 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008893 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8894 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00008895 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00008896 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00008897 break;
Steve Naroff081c7422008-09-04 15:10:53 +00008898 case IntToBlockPointer:
8899 DiagKind = diag::err_int_to_block_pointer;
8900 break;
8901 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00008902 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00008903 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00008904 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00008905 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00008906 // it can give a more specific diagnostic.
8907 DiagKind = diag::warn_incompatible_qualified_id;
8908 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00008909 case IncompatibleVectors:
8910 DiagKind = diag::warn_incompatible_vectors;
8911 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00008912 case IncompatibleObjCWeakRef:
8913 DiagKind = diag::err_arc_weak_unavailable_assign;
8914 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008915 case Incompatible:
8916 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00008917 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8918 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008919 isInvalid = true;
8920 break;
8921 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008922
Douglas Gregorc68e1402010-04-09 00:35:39 +00008923 QualType FirstType, SecondType;
8924 switch (Action) {
8925 case AA_Assigning:
8926 case AA_Initializing:
8927 // The destination type comes first.
8928 FirstType = DstType;
8929 SecondType = SrcType;
8930 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00008931
Douglas Gregorc68e1402010-04-09 00:35:39 +00008932 case AA_Returning:
8933 case AA_Passing:
8934 case AA_Converting:
8935 case AA_Sending:
8936 case AA_Casting:
8937 // The source type comes first.
8938 FirstType = SrcType;
8939 SecondType = DstType;
8940 break;
8941 }
Alexis Huntc46382e2010-04-28 23:02:27 +00008942
Anna Zaks3b402712011-07-28 19:51:27 +00008943 PartialDiagnostic FDiag = PDiag(DiagKind);
8944 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
8945
8946 // If we can fix the conversion, suggest the FixIts.
8947 assert(ConvHints.isNull() || Hint.isNull());
8948 if (!ConvHints.isNull()) {
8949 for (llvm::SmallVector<FixItHint, 1>::iterator
8950 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
8951 HI != HE; ++HI)
8952 FDiag << *HI;
8953 } else {
8954 FDiag << Hint;
8955 }
8956 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
8957
8958 Diag(Loc, FDiag);
8959
Douglas Gregor33823722011-06-11 01:09:30 +00008960 if (CheckInferredResultType)
8961 EmitRelatedResultTypeNote(SrcExpr);
8962
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008963 if (Complained)
8964 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008965 return isInvalid;
8966}
Anders Carlssone54e8a12008-11-30 19:50:32 +00008967
Chris Lattnerc71d08b2009-04-25 21:59:05 +00008968bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008969 llvm::APSInt ICEResult;
8970 if (E->isIntegerConstantExpr(ICEResult, Context)) {
8971 if (Result)
8972 *Result = ICEResult;
8973 return false;
8974 }
8975
Anders Carlssone54e8a12008-11-30 19:50:32 +00008976 Expr::EvalResult EvalResult;
8977
Mike Stump4e1f26a2009-02-19 03:04:26 +00008978 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00008979 EvalResult.HasSideEffects) {
8980 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
8981
8982 if (EvalResult.Diag) {
8983 // We only show the note if it's not the usual "invalid subexpression"
8984 // or if it's actually in a subexpression.
8985 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
8986 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
8987 Diag(EvalResult.DiagLoc, EvalResult.Diag);
8988 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008989
Anders Carlssone54e8a12008-11-30 19:50:32 +00008990 return true;
8991 }
8992
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008993 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
8994 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00008995
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008996 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008997 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
8998 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00008999 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009000
Anders Carlssone54e8a12008-11-30 19:50:32 +00009001 if (Result)
9002 *Result = EvalResult.Val.getInt();
9003 return false;
9004}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009005
Douglas Gregorff790f12009-11-26 00:44:06 +00009006void
Mike Stump11289f42009-09-09 15:08:12 +00009007Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009008 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00009009 ExpressionEvaluationContextRecord(NewContext,
9010 ExprTemporaries.size(),
9011 ExprNeedsCleanups));
9012 ExprNeedsCleanups = false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009013}
9014
Richard Trieucfc491d2011-08-02 04:35:43 +00009015void Sema::PopExpressionEvaluationContext() {
Douglas Gregorff790f12009-11-26 00:44:06 +00009016 // Pop the current expression evaluation context off the stack.
9017 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9018 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009019
Douglas Gregorfab31f42009-12-12 07:57:52 +00009020 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9021 if (Rec.PotentiallyReferenced) {
9022 // Mark any remaining declarations in the current position of the stack
9023 // as "referenced". If they were not meant to be referenced, semantic
9024 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009025 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009026 I = Rec.PotentiallyReferenced->begin(),
9027 IEnd = Rec.PotentiallyReferenced->end();
9028 I != IEnd; ++I)
9029 MarkDeclarationReferenced(I->first, I->second);
9030 }
9031
9032 if (Rec.PotentiallyDiagnosed) {
9033 // Emit any pending diagnostics.
9034 for (PotentiallyEmittedDiagnostics::iterator
9035 I = Rec.PotentiallyDiagnosed->begin(),
9036 IEnd = Rec.PotentiallyDiagnosed->end();
9037 I != IEnd; ++I)
9038 Diag(I->first, I->second);
9039 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009040 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009041
9042 // When are coming out of an unevaluated context, clear out any
9043 // temporaries that we may have created as part of the evaluation of
9044 // the expression in that context: they aren't relevant because they
9045 // will never be constructed.
John McCall31168b02011-06-15 23:02:42 +00009046 if (Rec.Context == Unevaluated) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009047 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9048 ExprTemporaries.end());
John McCall31168b02011-06-15 23:02:42 +00009049 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9050
9051 // Otherwise, merge the contexts together.
9052 } else {
9053 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9054 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009055
9056 // Destroy the popped expression evaluation record.
9057 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009058}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009059
John McCall31168b02011-06-15 23:02:42 +00009060void Sema::DiscardCleanupsInEvaluationContext() {
9061 ExprTemporaries.erase(
9062 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
9063 ExprTemporaries.end());
9064 ExprNeedsCleanups = false;
9065}
9066
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009067/// \brief Note that the given declaration was referenced in the source code.
9068///
9069/// This routine should be invoke whenever a given declaration is referenced
9070/// in the source code, and where that reference occurred. If this declaration
9071/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9072/// C99 6.9p3), then the declaration will be marked as used.
9073///
9074/// \param Loc the location where the declaration was referenced.
9075///
9076/// \param D the declaration that has been referenced by the source code.
9077void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9078 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009079
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00009080 D->setReferenced();
9081
Douglas Gregorebada0772010-06-17 23:14:26 +00009082 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009083 return;
Mike Stump11289f42009-09-09 15:08:12 +00009084
Richard Trieucfc491d2011-08-02 04:35:43 +00009085 // Mark a parameter or variable declaration "used", regardless of whether
9086 // we're in a template or not. The reason for this is that unevaluated
9087 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9088 // (-Wunused-variables and -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009089 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009090 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009091 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009092 return;
9093 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009094
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009095 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9096 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009097
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009098 // Do not mark anything as "used" within a dependent context; wait for
9099 // an instantiation.
9100 if (CurContext->isDependentContext())
9101 return;
Mike Stump11289f42009-09-09 15:08:12 +00009102
Douglas Gregorff790f12009-11-26 00:44:06 +00009103 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009104 case Unevaluated:
9105 // We are in an expression that is not potentially evaluated; do nothing.
9106 return;
Mike Stump11289f42009-09-09 15:08:12 +00009107
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009108 case PotentiallyEvaluated:
9109 // We are in a potentially-evaluated expression, so this declaration is
9110 // "used"; handle this below.
9111 break;
Mike Stump11289f42009-09-09 15:08:12 +00009112
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009113 case PotentiallyPotentiallyEvaluated:
9114 // We are in an expression that may be potentially evaluated; queue this
9115 // declaration reference until we know whether the expression is
9116 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009117 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009118 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009119
9120 case PotentiallyEvaluatedIfUsed:
9121 // Referenced declarations will only be used if the construct in the
9122 // containing expression is used.
9123 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009124 }
Mike Stump11289f42009-09-09 15:08:12 +00009125
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009126 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009127 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Alexis Huntf92197c2011-05-12 03:51:51 +00009128 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor()) {
9129 if (Constructor->isTrivial())
Chandler Carruthc9262402010-08-23 07:55:51 +00009130 return;
9131 if (!Constructor->isUsed(false))
9132 DefineImplicitDefaultConstructor(Loc, Constructor);
Alexis Hunt22b5b132011-05-14 18:20:50 +00009133 } else if (Constructor->isDefaulted() &&
Alexis Hunt913820d2011-05-13 06:10:58 +00009134 Constructor->isCopyConstructor()) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009135 if (!Constructor->isUsed(false))
Alexis Hunt913820d2011-05-13 06:10:58 +00009136 DefineImplicitCopyConstructor(Loc, Constructor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009137 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009138
Douglas Gregor88d292c2010-05-13 16:44:06 +00009139 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009140 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Alexis Huntf91729462011-05-12 22:46:25 +00009141 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009142 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009143 if (Destructor->isVirtual())
9144 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009145 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Alexis Huntc9a55732011-05-14 05:23:28 +00009146 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009147 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009148 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00009149 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009150 } else if (MethodDecl->isVirtual())
9151 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009152 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009153 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009154 // Recursive functions should be marked when used from another function.
9155 if (CurContext == Function) return;
9156
Mike Stump11289f42009-09-09 15:08:12 +00009157 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009158 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009159 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009160 bool AlreadyInstantiated = false;
9161 if (FunctionTemplateSpecializationInfo *SpecInfo
9162 = Function->getTemplateSpecializationInfo()) {
9163 if (SpecInfo->getPointOfInstantiation().isInvalid())
9164 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009165 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009166 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009167 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009168 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009169 = Function->getMemberSpecializationInfo()) {
9170 if (MSInfo->getPointOfInstantiation().isInvalid())
9171 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009172 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009173 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009174 AlreadyInstantiated = true;
9175 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009176
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009177 if (!AlreadyInstantiated) {
9178 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9179 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9180 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9181 Loc));
9182 else
Chandler Carruth54080172010-08-25 08:44:16 +00009183 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009184 }
John McCall83779672011-02-19 02:53:41 +00009185 } else {
9186 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009187 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9188 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009189 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009190 MarkDeclarationReferenced(Loc, *i);
9191 }
John McCall83779672011-02-19 02:53:41 +00009192 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009193
John McCall83779672011-02-19 02:53:41 +00009194 // Keep track of used but undefined functions.
9195 if (!Function->isPure() && !Function->hasBody() &&
9196 Function->getLinkage() != ExternalLinkage) {
9197 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9198 if (old.isInvalid()) old = Loc;
9199 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009200
John McCall83779672011-02-19 02:53:41 +00009201 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009202 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009203 }
Mike Stump11289f42009-09-09 15:08:12 +00009204
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009205 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009206 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009207 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009208 Var->getInstantiatedFromStaticDataMember()) {
9209 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9210 assert(MSInfo && "Missing member specialization information?");
9211 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9212 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9213 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redl2ac2c722011-04-29 08:19:30 +00009214 // This is a modification of an existing AST node. Notify listeners.
9215 if (ASTMutationListener *L = getASTMutationListener())
9216 L->StaticDataMemberInstantiated(Var);
Chandler Carruth54080172010-08-25 08:44:16 +00009217 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009218 }
9219 }
Mike Stump11289f42009-09-09 15:08:12 +00009220
John McCall15dd4042011-02-21 19:25:48 +00009221 // Keep track of used but undefined variables. We make a hole in
9222 // the warning for static const data members with in-line
9223 // initializers.
John McCall83779672011-02-19 02:53:41 +00009224 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009225 && Var->getLinkage() != ExternalLinkage
9226 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009227 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9228 if (old.isInvalid()) old = Loc;
9229 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009230
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009231 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009232 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009233 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009234}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009235
Douglas Gregor5597ab42010-05-07 23:12:07 +00009236namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009237 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009238 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009239 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009240 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9241 Sema &S;
9242 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009243
Douglas Gregor5597ab42010-05-07 23:12:07 +00009244 public:
9245 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009246
Douglas Gregor5597ab42010-05-07 23:12:07 +00009247 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009248
9249 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9250 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009251 };
9252}
9253
Chandler Carruthaf80f662010-06-09 08:17:30 +00009254bool MarkReferencedDecls::TraverseTemplateArgument(
9255 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009256 if (Arg.getKind() == TemplateArgument::Declaration) {
9257 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9258 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009259
9260 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009261}
9262
Chandler Carruthaf80f662010-06-09 08:17:30 +00009263bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009264 if (ClassTemplateSpecializationDecl *Spec
9265 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9266 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009267 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009268 }
9269
Chandler Carruthc65667c2010-06-10 10:31:57 +00009270 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009271}
9272
9273void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9274 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009275 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009276}
9277
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009278namespace {
9279 /// \brief Helper class that marks all of the declarations referenced by
9280 /// potentially-evaluated subexpressions as "referenced".
9281 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9282 Sema &S;
9283
9284 public:
9285 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9286
9287 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9288
9289 void VisitDeclRefExpr(DeclRefExpr *E) {
9290 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9291 }
9292
9293 void VisitMemberExpr(MemberExpr *E) {
9294 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009295 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009296 }
9297
9298 void VisitCXXNewExpr(CXXNewExpr *E) {
9299 if (E->getConstructor())
9300 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9301 if (E->getOperatorNew())
9302 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9303 if (E->getOperatorDelete())
9304 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009305 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009306 }
9307
9308 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9309 if (E->getOperatorDelete())
9310 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009311 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9312 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9313 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9314 S.MarkDeclarationReferenced(E->getLocStart(),
9315 S.LookupDestructor(Record));
9316 }
9317
Douglas Gregor32b3de52010-09-11 23:32:50 +00009318 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009319 }
9320
9321 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9322 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009323 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009324 }
9325
9326 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9327 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9328 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009329
9330 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9331 Visit(E->getExpr());
9332 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009333 };
9334}
9335
9336/// \brief Mark any declarations that appear within this expression or any
9337/// potentially-evaluated subexpressions as "referenced".
9338void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9339 EvaluatedExprMarker(*this).Visit(E);
9340}
9341
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009342/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9343/// of the program being compiled.
9344///
9345/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009346/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009347/// possibility that the code will actually be executable. Code in sizeof()
9348/// expressions, code used only during overload resolution, etc., are not
9349/// potentially evaluated. This routine will suppress such diagnostics or,
9350/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009351/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009352/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009353///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009354/// This routine should be used for all diagnostics that describe the run-time
9355/// behavior of a program, such as passing a non-POD value through an ellipsis.
9356/// Failure to do so will likely result in spurious diagnostics or failures
9357/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +00009358bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009359 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +00009360 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009361 case Unevaluated:
9362 // The argument will never be evaluated, so don't complain.
9363 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009364
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009365 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009366 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +00009367 if (stmt && getCurFunctionOrMethodDecl()) {
9368 FunctionScopes.back()->PossiblyUnreachableDiags.
9369 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
9370 }
9371 else
9372 Diag(Loc, PD);
9373
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009374 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009375
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009376 case PotentiallyPotentiallyEvaluated:
9377 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9378 break;
9379 }
9380
9381 return false;
9382}
9383
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009384bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9385 CallExpr *CE, FunctionDecl *FD) {
9386 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9387 return false;
9388
9389 PartialDiagnostic Note =
9390 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9391 << FD->getDeclName() : PDiag();
9392 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009393
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009394 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009395 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009396 PDiag(diag::err_call_function_incomplete_return)
9397 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009398 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009399 << CE->getSourceRange(),
9400 std::make_pair(NoteLoc, Note)))
9401 return true;
9402
9403 return false;
9404}
9405
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009406// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009407// will prevent this condition from triggering, which is what we want.
9408void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9409 SourceLocation Loc;
9410
John McCall0506e4a2009-11-11 02:41:58 +00009411 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009412 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009413
John McCalld5707ab2009-10-12 21:59:07 +00009414 if (isa<BinaryOperator>(E)) {
9415 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009416 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009417 return;
9418
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009419 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9420
John McCallb0e419e2009-11-12 00:06:05 +00009421 // Greylist some idioms by putting them into a warning subcategory.
9422 if (ObjCMessageExpr *ME
9423 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9424 Selector Sel = ME->getSelector();
9425
John McCallb0e419e2009-11-12 00:06:05 +00009426 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009427 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009428 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9429
9430 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009431 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009432 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9433 }
John McCall0506e4a2009-11-11 02:41:58 +00009434
John McCalld5707ab2009-10-12 21:59:07 +00009435 Loc = Op->getOperatorLoc();
9436 } else if (isa<CXXOperatorCallExpr>(E)) {
9437 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009438 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009439 return;
9440
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009441 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009442 Loc = Op->getOperatorLoc();
9443 } else {
9444 // Not an assignment.
9445 return;
9446 }
9447
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009448 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009449
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009450 SourceLocation Open = E->getSourceRange().getBegin();
9451 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9452 Diag(Loc, diag::note_condition_assign_silence)
9453 << FixItHint::CreateInsertion(Open, "(")
9454 << FixItHint::CreateInsertion(Close, ")");
9455
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009456 if (IsOrAssign)
9457 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9458 << FixItHint::CreateReplacement(Loc, "!=");
9459 else
9460 Diag(Loc, diag::note_condition_assign_to_comparison)
9461 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00009462}
9463
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009464/// \brief Redundant parentheses over an equality comparison can indicate
9465/// that the user intended an assignment used as condition.
9466void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009467 // Don't warn if the parens came from a macro.
9468 SourceLocation parenLoc = parenE->getLocStart();
9469 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9470 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009471 // Don't warn for dependent expressions.
9472 if (parenE->isTypeDependent())
9473 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009474
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009475 Expr *E = parenE->IgnoreParens();
9476
9477 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009478 if (opE->getOpcode() == BO_EQ &&
9479 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9480 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009481 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009482
Ted Kremenekae022092011-02-02 02:20:30 +00009483 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +00009484 Diag(Loc, diag::note_equality_comparison_silence)
9485 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9486 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009487 Diag(Loc, diag::note_equality_comparison_to_assign)
9488 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009489 }
9490}
9491
John Wiegley01296292011-04-08 18:41:53 +00009492ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +00009493 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009494 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9495 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009496
John McCall0009fcc2011-04-26 20:42:42 +00009497 ExprResult result = CheckPlaceholderExpr(E);
9498 if (result.isInvalid()) return ExprError();
9499 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009500
John McCall0009fcc2011-04-26 20:42:42 +00009501 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +00009502 if (getLangOptions().CPlusPlus)
9503 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9504
John Wiegley01296292011-04-08 18:41:53 +00009505 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9506 if (ERes.isInvalid())
9507 return ExprError();
9508 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +00009509
9510 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +00009511 if (!T->isScalarType()) { // C99 6.8.4.1p1
9512 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9513 << T << E->getSourceRange();
9514 return ExprError();
9515 }
John McCalld5707ab2009-10-12 21:59:07 +00009516 }
9517
John Wiegley01296292011-04-08 18:41:53 +00009518 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +00009519}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009520
John McCalldadc5752010-08-24 06:29:42 +00009521ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9522 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +00009523 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009524 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009525
9526 return CheckBooleanCondition(Sub, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +00009527}
John McCall36e7fe32010-10-12 00:20:44 +00009528
John McCall31996342011-04-07 08:22:57 +00009529namespace {
John McCall2979fe02011-04-12 00:42:48 +00009530 /// A visitor for rebuilding a call to an __unknown_any expression
9531 /// to have an appropriate type.
9532 struct RebuildUnknownAnyFunction
9533 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9534
9535 Sema &S;
9536
9537 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9538
9539 ExprResult VisitStmt(Stmt *S) {
9540 llvm_unreachable("unexpected statement!");
9541 return ExprError();
9542 }
9543
9544 ExprResult VisitExpr(Expr *expr) {
9545 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
9546 << expr->getSourceRange();
9547 return ExprError();
9548 }
9549
9550 /// Rebuild an expression which simply semantically wraps another
9551 /// expression which it shares the type and value kind of.
9552 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9553 ExprResult subResult = Visit(expr->getSubExpr());
9554 if (subResult.isInvalid()) return ExprError();
9555
9556 Expr *subExpr = subResult.take();
9557 expr->setSubExpr(subExpr);
9558 expr->setType(subExpr->getType());
9559 expr->setValueKind(subExpr->getValueKind());
9560 assert(expr->getObjectKind() == OK_Ordinary);
9561 return expr;
9562 }
9563
9564 ExprResult VisitParenExpr(ParenExpr *paren) {
9565 return rebuildSugarExpr(paren);
9566 }
9567
9568 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9569 return rebuildSugarExpr(op);
9570 }
9571
9572 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9573 ExprResult subResult = Visit(op->getSubExpr());
9574 if (subResult.isInvalid()) return ExprError();
9575
9576 Expr *subExpr = subResult.take();
9577 op->setSubExpr(subExpr);
9578 op->setType(S.Context.getPointerType(subExpr->getType()));
9579 assert(op->getValueKind() == VK_RValue);
9580 assert(op->getObjectKind() == OK_Ordinary);
9581 return op;
9582 }
9583
9584 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
9585 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
9586
9587 expr->setType(decl->getType());
9588
9589 assert(expr->getValueKind() == VK_RValue);
9590 if (S.getLangOptions().CPlusPlus &&
9591 !(isa<CXXMethodDecl>(decl) &&
9592 cast<CXXMethodDecl>(decl)->isInstance()))
9593 expr->setValueKind(VK_LValue);
9594
9595 return expr;
9596 }
9597
9598 ExprResult VisitMemberExpr(MemberExpr *mem) {
9599 return resolveDecl(mem, mem->getMemberDecl());
9600 }
9601
9602 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
9603 return resolveDecl(ref, ref->getDecl());
9604 }
9605 };
9606}
9607
9608/// Given a function expression of unknown-any type, try to rebuild it
9609/// to have a function type.
9610static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
9611 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
9612 if (result.isInvalid()) return ExprError();
9613 return S.DefaultFunctionArrayConversion(result.take());
9614}
9615
9616namespace {
John McCall2d2e8702011-04-11 07:02:50 +00009617 /// A visitor for rebuilding an expression of type __unknown_anytype
9618 /// into one which resolves the type directly on the referring
9619 /// expression. Strict preservation of the original source
9620 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +00009621 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +00009622 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +00009623
9624 Sema &S;
9625
9626 /// The current destination type.
9627 QualType DestType;
9628
9629 RebuildUnknownAnyExpr(Sema &S, QualType castType)
9630 : S(S), DestType(castType) {}
9631
John McCall39439732011-04-09 22:50:59 +00009632 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +00009633 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +00009634 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009635 }
9636
John McCall2d2e8702011-04-11 07:02:50 +00009637 ExprResult VisitExpr(Expr *expr) {
9638 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9639 << expr->getSourceRange();
9640 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009641 }
9642
John McCall2d2e8702011-04-11 07:02:50 +00009643 ExprResult VisitCallExpr(CallExpr *call);
9644 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
9645
John McCall39439732011-04-09 22:50:59 +00009646 /// Rebuild an expression which simply semantically wraps another
9647 /// expression which it shares the type and value kind of.
9648 template <class T> ExprResult rebuildSugarExpr(T *expr) {
9649 ExprResult subResult = Visit(expr->getSubExpr());
John McCall2979fe02011-04-12 00:42:48 +00009650 if (subResult.isInvalid()) return ExprError();
John McCall39439732011-04-09 22:50:59 +00009651 Expr *subExpr = subResult.take();
9652 expr->setSubExpr(subExpr);
9653 expr->setType(subExpr->getType());
9654 expr->setValueKind(subExpr->getValueKind());
9655 assert(expr->getObjectKind() == OK_Ordinary);
9656 return expr;
9657 }
John McCall31996342011-04-07 08:22:57 +00009658
John McCall39439732011-04-09 22:50:59 +00009659 ExprResult VisitParenExpr(ParenExpr *paren) {
9660 return rebuildSugarExpr(paren);
9661 }
9662
9663 ExprResult VisitUnaryExtension(UnaryOperator *op) {
9664 return rebuildSugarExpr(op);
9665 }
9666
John McCall2979fe02011-04-12 00:42:48 +00009667 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
9668 const PointerType *ptr = DestType->getAs<PointerType>();
9669 if (!ptr) {
9670 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
9671 << op->getSourceRange();
9672 return ExprError();
9673 }
9674 assert(op->getValueKind() == VK_RValue);
9675 assert(op->getObjectKind() == OK_Ordinary);
9676 op->setType(DestType);
9677
9678 // Build the sub-expression as if it were an object of the pointee type.
9679 DestType = ptr->getPointeeType();
9680 ExprResult subResult = Visit(op->getSubExpr());
9681 if (subResult.isInvalid()) return ExprError();
9682 op->setSubExpr(subResult.take());
9683 return op;
9684 }
9685
John McCall2d2e8702011-04-11 07:02:50 +00009686 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCall39439732011-04-09 22:50:59 +00009687
John McCall2979fe02011-04-12 00:42:48 +00009688 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCall39439732011-04-09 22:50:59 +00009689
John McCall2979fe02011-04-12 00:42:48 +00009690 ExprResult VisitMemberExpr(MemberExpr *mem) {
9691 return resolveDecl(mem, mem->getMemberDecl());
9692 }
John McCall39439732011-04-09 22:50:59 +00009693
9694 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall2d2e8702011-04-11 07:02:50 +00009695 return resolveDecl(ref, ref->getDecl());
John McCall31996342011-04-07 08:22:57 +00009696 }
9697 };
9698}
9699
John McCall2d2e8702011-04-11 07:02:50 +00009700/// Rebuilds a call expression which yielded __unknown_anytype.
9701ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
9702 Expr *callee = call->getCallee();
9703
9704 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +00009705 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +00009706 FK_FunctionPointer,
9707 FK_BlockPointer
9708 };
9709
9710 FnKind kind;
9711 QualType type = callee->getType();
John McCall4adb38c2011-04-27 00:36:17 +00009712 if (type == S.Context.BoundMemberTy) {
9713 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
9714 kind = FK_MemberFunction;
9715 type = Expr::findBoundMemberType(callee);
John McCall2d2e8702011-04-11 07:02:50 +00009716 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
9717 type = ptr->getPointeeType();
9718 kind = FK_FunctionPointer;
9719 } else {
9720 type = type->castAs<BlockPointerType>()->getPointeeType();
9721 kind = FK_BlockPointer;
9722 }
9723 const FunctionType *fnType = type->castAs<FunctionType>();
9724
9725 // Verify that this is a legal result type of a function.
9726 if (DestType->isArrayType() || DestType->isFunctionType()) {
9727 unsigned diagID = diag::err_func_returning_array_function;
9728 if (kind == FK_BlockPointer)
9729 diagID = diag::err_block_returning_array_function;
9730
9731 S.Diag(call->getExprLoc(), diagID)
9732 << DestType->isFunctionType() << DestType;
9733 return ExprError();
9734 }
9735
9736 // Otherwise, go ahead and set DestType as the call's result.
9737 call->setType(DestType.getNonLValueExprType(S.Context));
9738 call->setValueKind(Expr::getValueKindForType(DestType));
9739 assert(call->getObjectKind() == OK_Ordinary);
9740
9741 // Rebuild the function type, replacing the result type with DestType.
9742 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
9743 DestType = S.Context.getFunctionType(DestType,
9744 proto->arg_type_begin(),
9745 proto->getNumArgs(),
9746 proto->getExtProtoInfo());
9747 else
9748 DestType = S.Context.getFunctionNoProtoType(DestType,
9749 fnType->getExtInfo());
9750
9751 // Rebuild the appropriate pointer-to-function type.
9752 switch (kind) {
John McCall4adb38c2011-04-27 00:36:17 +00009753 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +00009754 // Nothing to do.
9755 break;
9756
9757 case FK_FunctionPointer:
9758 DestType = S.Context.getPointerType(DestType);
9759 break;
9760
9761 case FK_BlockPointer:
9762 DestType = S.Context.getBlockPointerType(DestType);
9763 break;
9764 }
9765
9766 // Finally, we can recurse.
9767 ExprResult calleeResult = Visit(callee);
9768 if (!calleeResult.isUsable()) return ExprError();
9769 call->setCallee(calleeResult.take());
9770
9771 // Bind a temporary if necessary.
9772 return S.MaybeBindToTemporary(call);
9773}
9774
9775ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall2979fe02011-04-12 00:42:48 +00009776 // Verify that this is a legal result type of a call.
9777 if (DestType->isArrayType() || DestType->isFunctionType()) {
9778 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
9779 << DestType->isFunctionType() << DestType;
9780 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009781 }
9782
John McCall3f4138c2011-07-13 17:56:40 +00009783 // Rewrite the method result type if available.
9784 if (ObjCMethodDecl *method = msg->getMethodDecl()) {
9785 assert(method->getResultType() == S.Context.UnknownAnyTy);
9786 method->setResultType(DestType);
9787 }
John McCall2979fe02011-04-12 00:42:48 +00009788
John McCall2d2e8702011-04-11 07:02:50 +00009789 // Change the type of the message.
John McCall2979fe02011-04-12 00:42:48 +00009790 msg->setType(DestType.getNonReferenceType());
9791 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +00009792
John McCall2979fe02011-04-12 00:42:48 +00009793 return S.MaybeBindToTemporary(msg);
John McCall2d2e8702011-04-11 07:02:50 +00009794}
9795
9796ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall2979fe02011-04-12 00:42:48 +00009797 // The only case we should ever see here is a function-to-pointer decay.
John McCall2d2e8702011-04-11 07:02:50 +00009798 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall2d2e8702011-04-11 07:02:50 +00009799 assert(ice->getValueKind() == VK_RValue);
9800 assert(ice->getObjectKind() == OK_Ordinary);
9801
John McCall2979fe02011-04-12 00:42:48 +00009802 ice->setType(DestType);
9803
John McCall2d2e8702011-04-11 07:02:50 +00009804 // Rebuild the sub-expression as the pointee (function) type.
9805 DestType = DestType->castAs<PointerType>()->getPointeeType();
9806
9807 ExprResult result = Visit(ice->getSubExpr());
9808 if (!result.isUsable()) return ExprError();
9809
9810 ice->setSubExpr(result.take());
9811 return S.Owned(ice);
9812}
9813
John McCall2979fe02011-04-12 00:42:48 +00009814ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall2d2e8702011-04-11 07:02:50 +00009815 ExprValueKind valueKind = VK_LValue;
John McCall2d2e8702011-04-11 07:02:50 +00009816 QualType type = DestType;
9817
9818 // We know how to make this work for certain kinds of decls:
9819
9820 // - functions
John McCall2979fe02011-04-12 00:42:48 +00009821 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCall9a877fe2011-08-10 04:12:23 +00009822 if (const PointerType *ptr = type->getAs<PointerType>()) {
9823 DestType = ptr->getPointeeType();
9824 ExprResult result = resolveDecl(expr, decl);
9825 if (result.isInvalid()) return ExprError();
9826 return S.ImpCastExprToType(result.take(), type,
9827 CK_FunctionToPointerDecay, VK_RValue);
9828 }
9829
9830 if (!type->isFunctionType()) {
9831 S.Diag(expr->getExprLoc(), diag::err_unknown_any_function)
9832 << decl << expr->getSourceRange();
9833 return ExprError();
9834 }
John McCall2d2e8702011-04-11 07:02:50 +00009835
John McCall4adb38c2011-04-27 00:36:17 +00009836 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
9837 if (method->isInstance()) {
9838 valueKind = VK_RValue;
9839 type = S.Context.BoundMemberTy;
9840 }
9841
John McCall2d2e8702011-04-11 07:02:50 +00009842 // Function references aren't l-values in C.
9843 if (!S.getLangOptions().CPlusPlus)
9844 valueKind = VK_RValue;
9845
9846 // - variables
9847 } else if (isa<VarDecl>(decl)) {
John McCall2979fe02011-04-12 00:42:48 +00009848 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
9849 type = refTy->getPointeeType();
John McCall2d2e8702011-04-11 07:02:50 +00009850 } else if (type->isFunctionType()) {
John McCall2979fe02011-04-12 00:42:48 +00009851 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
9852 << decl << expr->getSourceRange();
9853 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009854 }
9855
9856 // - nothing else
9857 } else {
9858 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
9859 << decl << expr->getSourceRange();
9860 return ExprError();
9861 }
9862
John McCall2979fe02011-04-12 00:42:48 +00009863 decl->setType(DestType);
9864 expr->setType(type);
9865 expr->setValueKind(valueKind);
9866 return S.Owned(expr);
John McCall2d2e8702011-04-11 07:02:50 +00009867}
9868
John McCall31996342011-04-07 08:22:57 +00009869/// Check a cast of an unknown-any type. We intentionally only
9870/// trigger this for C-style casts.
John Wiegley01296292011-04-08 18:41:53 +00009871ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
9872 Expr *castExpr, CastKind &castKind,
9873 ExprValueKind &VK, CXXCastPath &path) {
John McCall31996342011-04-07 08:22:57 +00009874 // Rewrite the casted expression from scratch.
John McCall39439732011-04-09 22:50:59 +00009875 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
9876 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +00009877
John McCall39439732011-04-09 22:50:59 +00009878 castExpr = result.take();
9879 VK = castExpr->getValueKind();
9880 castKind = CK_NoOp;
9881
9882 return castExpr;
John McCall31996342011-04-07 08:22:57 +00009883}
9884
9885static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
9886 Expr *orig = e;
John McCall2d2e8702011-04-11 07:02:50 +00009887 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +00009888 while (true) {
9889 e = e->IgnoreParenImpCasts();
John McCall2d2e8702011-04-11 07:02:50 +00009890 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall31996342011-04-07 08:22:57 +00009891 e = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +00009892 diagID = diag::err_uncasted_call_of_unknown_any;
9893 } else {
John McCall31996342011-04-07 08:22:57 +00009894 break;
John McCall2d2e8702011-04-11 07:02:50 +00009895 }
John McCall31996342011-04-07 08:22:57 +00009896 }
9897
John McCall2d2e8702011-04-11 07:02:50 +00009898 SourceLocation loc;
9899 NamedDecl *d;
9900 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9901 loc = ref->getLocation();
9902 d = ref->getDecl();
9903 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
9904 loc = mem->getMemberLoc();
9905 d = mem->getMemberDecl();
9906 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
9907 diagID = diag::err_uncasted_call_of_unknown_any;
9908 loc = msg->getSelectorLoc();
9909 d = msg->getMethodDecl();
9910 assert(d && "unknown method returning __unknown_any?");
9911 } else {
9912 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9913 << e->getSourceRange();
9914 return ExprError();
9915 }
9916
9917 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +00009918
9919 // Never recoverable.
9920 return ExprError();
9921}
9922
John McCall36e7fe32010-10-12 00:20:44 +00009923/// Check for operands with placeholder types and complain if found.
9924/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +00009925ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +00009926 // Placeholder types are always *exactly* the appropriate builtin type.
9927 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +00009928
John McCall31996342011-04-07 08:22:57 +00009929 // Overloaded expressions.
9930 if (type == Context.OverloadTy)
9931 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +00009932 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +00009933 QualType(),
9934 diag::err_ovl_unresolvable);
9935
John McCall0009fcc2011-04-26 20:42:42 +00009936 // Bound member functions.
9937 if (type == Context.BoundMemberTy) {
9938 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9939 << E->getSourceRange();
9940 return ExprError();
9941 }
9942
John McCall31996342011-04-07 08:22:57 +00009943 // Expressions of unknown type.
9944 if (type == Context.UnknownAnyTy)
9945 return diagnoseUnknownAnyExpr(*this, E);
9946
9947 assert(!type->isPlaceholderType());
9948 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +00009949}
Richard Trieu2c850c02011-04-21 21:44:26 +00009950
9951bool Sema::CheckCaseExpression(Expr *expr) {
9952 if (expr->isTypeDependent())
9953 return true;
9954 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
9955 return expr->getType()->isIntegralOrEnumerationType();
9956 return false;
9957}