blob: 2b67b4dc486ead79f58df016852e44a274b1f072 [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
Sebastian Redlb49c46c2011-09-24 17:48:00 +000044/// \brief Determine whether the use of this declaration is valid, without
45/// emitting diagnostics.
46bool Sema::CanUseDecl(NamedDecl *D) {
47 // See if this is an auto-typed variable whose initializer we are parsing.
48 if (ParsingInitForAutoVars.count(D))
49 return false;
50
51 // See if this is a deleted function.
52 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
53 if (FD->isDeleted())
54 return false;
55 }
56 return true;
57}
David Chisnall9f57c292009-08-17 16:35:33 +000058
Douglas Gregor171c45a2009-02-18 21:56:37 +000059/// \brief Determine whether the use of this declaration is valid, and
60/// emit any corresponding diagnostics.
61///
62/// This routine diagnoses various problems with referencing
63/// declarations that can occur when using a declaration. For example,
64/// it might warn if a deprecated or unavailable declaration is being
65/// used, or produce an error (and return true) if a C++0x deleted
66/// function is being used.
67///
68/// \returns true if there was an error (this declaration cannot be
69/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000070///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000071bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahaniandbbdd2f2011-04-23 17:27:19 +000072 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000073 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
74 // If there were any diagnostics suppressed by template argument deduction,
75 // emit them now.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000076 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000077 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
78 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000079 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000080 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
81 Diag(Suppressed[I].first, Suppressed[I].second);
82
83 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000084 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000085 // entry from the table, because we want to avoid ever emitting these
86 // diagnostics again.
87 Suppressed.clear();
88 }
89 }
90
Richard Smith30482bc2011-02-20 03:19:35 +000091 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +000092 if (ParsingInitForAutoVars.count(D)) {
93 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
94 << D->getDeclName();
95 return true;
Richard Smith30482bc2011-02-20 03:19:35 +000096 }
97
Douglas Gregor171c45a2009-02-18 21:56:37 +000098 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000099 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +0000100 if (FD->isDeleted()) {
101 Diag(Loc, diag::err_deleted_function_use);
John McCall31168b02011-06-15 23:02:42 +0000102 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
Douglas Gregor171c45a2009-02-18 21:56:37 +0000103 return true;
104 }
Douglas Gregorde681d42009-02-24 04:26:15 +0000105 }
Douglas Gregor171c45a2009-02-18 21:56:37 +0000106
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000107 // See if this declaration is unavailable or deprecated.
108 std::string Message;
109 switch (D->getAvailability(&Message)) {
110 case AR_Available:
111 case AR_NotYetIntroduced:
112 break;
113
114 case AR_Deprecated:
115 EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
116 break;
117
118 case AR_Unavailable:
Argyrios Kyrtzidisc30661f2011-06-17 17:28:30 +0000119 if (cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) {
120 if (Message.empty()) {
121 if (!UnknownObjCClass)
122 Diag(Loc, diag::err_unavailable) << D->getDeclName();
123 else
124 Diag(Loc, diag::warn_unavailable_fwdclass_message)
125 << D->getDeclName();
126 }
127 else
128 Diag(Loc, diag::err_unavailable_message)
129 << D->getDeclName() << Message;
130 Diag(D->getLocation(), diag::note_unavailable_here)
131 << isa<FunctionDecl>(D) << false;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000132 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000133 break;
134 }
135
Anders Carlsson73067a02010-10-22 23:37:08 +0000136 // Warn if this is used but marked unused.
137 if (D->hasAttr<UnusedAttr>())
138 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
139
Douglas Gregor171c45a2009-02-18 21:56:37 +0000140 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000141}
142
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000143/// \brief Retrieve the message suffix that should be added to a
144/// diagnostic complaining about the given function being deleted or
145/// unavailable.
146std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
147 // FIXME: C++0x implicitly-deleted special member functions could be
148 // detected here so that we could improve diagnostics to say, e.g.,
149 // "base class 'A' had a deleted copy constructor".
150 if (FD->isDeleted())
151 return std::string();
152
153 std::string Message;
154 if (FD->getAvailability(&Message))
155 return ": " + Message;
156
157 return std::string();
158}
159
John McCallb46f2872011-09-09 07:56:05 +0000160/// DiagnoseSentinelCalls - This routine checks whether a call or
161/// message-send is to a declaration with the sentinel attribute, and
162/// if so, it checks that the requirements of the sentinel are
163/// satisfied.
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000164void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCallb46f2872011-09-09 07:56:05 +0000165 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000166 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000167 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000168 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000169
John McCallb46f2872011-09-09 07:56:05 +0000170 // The number of formal parameters of the declaration.
171 unsigned numFormalParams;
Mike Stump11289f42009-09-09 15:08:12 +0000172
John McCallb46f2872011-09-09 07:56:05 +0000173 // The kind of declaration. This is also an index into a %select in
174 // the diagnostic.
175 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
176
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000177 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000178 numFormalParams = MD->param_size();
179 calleeType = CT_Method;
Mike Stump12b8ce12009-08-04 21:02:39 +0000180 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000181 numFormalParams = FD->param_size();
182 calleeType = CT_Function;
183 } else if (isa<VarDecl>(D)) {
184 QualType type = cast<ValueDecl>(D)->getType();
185 const FunctionType *fn = 0;
186 if (const PointerType *ptr = type->getAs<PointerType>()) {
187 fn = ptr->getPointeeType()->getAs<FunctionType>();
188 if (!fn) return;
189 calleeType = CT_Function;
190 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
191 fn = ptr->getPointeeType()->castAs<FunctionType>();
192 calleeType = CT_Block;
193 } else {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000194 return;
John McCallb46f2872011-09-09 07:56:05 +0000195 }
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000196
John McCallb46f2872011-09-09 07:56:05 +0000197 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
198 numFormalParams = proto->getNumArgs();
199 } else {
200 numFormalParams = 0;
201 }
202 } else {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000203 return;
204 }
John McCallb46f2872011-09-09 07:56:05 +0000205
206 // "nullPos" is the number of formal parameters at the end which
207 // effectively count as part of the variadic arguments. This is
208 // useful if you would prefer to not have *any* formal parameters,
209 // but the language forces you to have at least one.
210 unsigned nullPos = attr->getNullPos();
211 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
212 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
213
214 // The number of arguments which should follow the sentinel.
215 unsigned numArgsAfterSentinel = attr->getSentinel();
216
217 // If there aren't enough arguments for all the formal parameters,
218 // the sentinel, and the args after the sentinel, complain.
219 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000220 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCallb46f2872011-09-09 07:56:05 +0000221 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000222 return;
223 }
John McCallb46f2872011-09-09 07:56:05 +0000224
225 // Otherwise, find the sentinel expression.
226 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall7ddbcf42010-05-06 23:53:00 +0000227 if (!sentinelExpr) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000228 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000229
230 // nullptr_t is always treated as null.
231 if (sentinelExpr->getType()->isNullPtrType()) return;
232
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000233 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000234 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
235 Expr::NPC_ValueDependentIsNull))
236 return;
237
238 // Unfortunately, __null has type 'int'.
239 if (isa<GNUNullExpr>(sentinelExpr)) return;
240
John McCallb46f2872011-09-09 07:56:05 +0000241 // Pick a reasonable string to insert. Optimistically use 'nil' or
242 // 'NULL' if those are actually defined in the context. Only use
243 // 'nil' for ObjC methods, where it's much more likely that the
244 // variadic arguments form a list of object pointers.
245 SourceLocation MissingNilLoc
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000246 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
247 std::string NullValue;
John McCallb46f2872011-09-09 07:56:05 +0000248 if (calleeType == CT_Method &&
249 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000250 NullValue = "nil";
251 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
252 NullValue = "NULL";
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000253 else
John McCallb46f2872011-09-09 07:56:05 +0000254 NullValue = "(void*) 0";
Eli Friedman9ab36372011-09-27 23:46:37 +0000255
256 if (MissingNilLoc.isInvalid())
257 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
258 else
259 Diag(MissingNilLoc, diag::warn_missing_sentinel)
260 << calleeType
261 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCallb46f2872011-09-09 07:56:05 +0000262 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000263}
264
Richard Trieuba63ce62011-09-09 01:45:06 +0000265SourceRange Sema::getExprRange(Expr *E) const {
266 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor87f95b02009-02-26 21:00:50 +0000267}
268
Chris Lattner513165e2008-07-25 21:10:04 +0000269//===----------------------------------------------------------------------===//
270// Standard Promotions and Conversions
271//===----------------------------------------------------------------------===//
272
Chris Lattner513165e2008-07-25 21:10:04 +0000273/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000274ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattner513165e2008-07-25 21:10:04 +0000275 QualType Ty = E->getType();
276 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
277
Chris Lattner513165e2008-07-25 21:10:04 +0000278 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000279 E = ImpCastExprToType(E, Context.getPointerType(Ty),
280 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000281 else if (Ty->isArrayType()) {
282 // In C90 mode, arrays only promote to pointers if the array expression is
283 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
284 // type 'array of type' is converted to an expression that has type 'pointer
285 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
286 // that has type 'array of type' ...". The relevant change is "an lvalue"
287 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000288 //
289 // C++ 4.2p1:
290 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
291 // T" can be converted to an rvalue of type "pointer to T".
292 //
John McCall086a4642010-11-24 05:12:34 +0000293 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000294 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
295 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000296 }
John Wiegley01296292011-04-08 18:41:53 +0000297 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000298}
299
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000300static void CheckForNullPointerDereference(Sema &S, Expr *E) {
301 // Check to see if we are dereferencing a null pointer. If so,
302 // and if not volatile-qualified, this is undefined behavior that the
303 // optimizer will delete, so warn about it. People sometimes try to use this
304 // to get a deterministic trap and are surprised by clang's behavior. This
305 // only handles the pattern "*null", which is a very syntactic check.
306 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
307 if (UO->getOpcode() == UO_Deref &&
308 UO->getSubExpr()->IgnoreParenCasts()->
309 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
310 !UO->getType().isVolatileQualified()) {
311 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
312 S.PDiag(diag::warn_indirection_through_null)
313 << UO->getSubExpr()->getSourceRange());
314 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
315 S.PDiag(diag::note_indirection_through_null));
316 }
317}
318
John Wiegley01296292011-04-08 18:41:53 +0000319ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000320 // C++ [conv.lval]p1:
321 // A glvalue of a non-function, non-array type T can be
322 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000323 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000324
John McCall27584242010-12-06 20:48:59 +0000325 QualType T = E->getType();
326 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000327
John McCall27584242010-12-06 20:48:59 +0000328 // Create a load out of an ObjCProperty l-value, if necessary.
329 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +0000330 ExprResult Res = ConvertPropertyForRValue(E);
331 if (Res.isInvalid())
332 return Owned(E);
333 E = Res.take();
John McCall27584242010-12-06 20:48:59 +0000334 if (!E->isGLValue())
John Wiegley01296292011-04-08 18:41:53 +0000335 return Owned(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000336 }
John McCall27584242010-12-06 20:48:59 +0000337
338 // We don't want to throw lvalue-to-rvalue casts on top of
339 // expressions of certain types in C++.
340 if (getLangOptions().CPlusPlus &&
341 (E->getType() == Context.OverloadTy ||
342 T->isDependentType() ||
343 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000344 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000345
346 // The C standard is actually really unclear on this point, and
347 // DR106 tells us what the result should be but not why. It's
348 // generally best to say that void types just doesn't undergo
349 // lvalue-to-rvalue at all. Note that expressions of unqualified
350 // 'void' type are never l-values, but qualified void can be.
351 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000352 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000353
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000354 CheckForNullPointerDereference(*this, E);
355
John McCall27584242010-12-06 20:48:59 +0000356 // C++ [conv.lval]p1:
357 // [...] If T is a non-class type, the type of the prvalue is the
358 // cv-unqualified version of T. Otherwise, the type of the
359 // rvalue is T.
360 //
361 // C99 6.3.2.1p2:
362 // If the lvalue has qualified type, the value has the unqualified
363 // version of the type of the lvalue; otherwise, the value has the
364 // type of the lvalue.
365 if (T.hasQualifiers())
366 T = T.getUnqualifiedType();
Ted Kremenek64699be2011-02-16 01:57:07 +0000367
John Wiegley01296292011-04-08 18:41:53 +0000368 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
369 E, 0, VK_RValue));
John McCall27584242010-12-06 20:48:59 +0000370}
371
John Wiegley01296292011-04-08 18:41:53 +0000372ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
373 ExprResult Res = DefaultFunctionArrayConversion(E);
374 if (Res.isInvalid())
375 return ExprError();
376 Res = DefaultLvalueConversion(Res.take());
377 if (Res.isInvalid())
378 return ExprError();
379 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000380}
381
382
Chris Lattner513165e2008-07-25 21:10:04 +0000383/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000384/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000385/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000386/// apply if the array is an argument to the sizeof or address (&) operators.
387/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000388ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000389 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000390 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
391 if (Res.isInvalid())
392 return Owned(E);
393 E = Res.take();
John McCallf3735e02010-12-01 04:43:34 +0000394
395 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000396 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000397
398 // Try to perform integral promotions if the object has a theoretically
399 // promotable type.
400 if (Ty->isIntegralOrUnscopedEnumerationType()) {
401 // C99 6.3.1.1p2:
402 //
403 // The following may be used in an expression wherever an int or
404 // unsigned int may be used:
405 // - an object or expression with an integer type whose integer
406 // conversion rank is less than or equal to the rank of int
407 // and unsigned int.
408 // - A bit-field of type _Bool, int, signed int, or unsigned int.
409 //
410 // If an int can represent all values of the original type, the
411 // value is converted to an int; otherwise, it is converted to an
412 // unsigned int. These are called the integer promotions. All
413 // other types are unchanged by the integer promotions.
414
415 QualType PTy = Context.isPromotableBitField(E);
416 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000417 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
418 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000419 }
420 if (Ty->isPromotableIntegerType()) {
421 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000422 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
423 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000424 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000425 }
John Wiegley01296292011-04-08 18:41:53 +0000426 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000427}
428
Chris Lattner2ce500f2008-07-25 22:25:12 +0000429/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000430/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000431/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000432ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
433 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000434 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000435
John Wiegley01296292011-04-08 18:41:53 +0000436 ExprResult Res = UsualUnaryConversions(E);
437 if (Res.isInvalid())
438 return Owned(E);
439 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000440
Chris Lattner2ce500f2008-07-25 22:25:12 +0000441 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000442 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000443 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
444
John McCall4bb057d2011-08-27 22:06:17 +0000445 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall0562caa2011-08-29 23:55:37 +0000446 // promotion, even on class types, but note:
447 // C++11 [conv.lval]p2:
448 // When an lvalue-to-rvalue conversion occurs in an unevaluated
449 // operand or a subexpression thereof the value contained in the
450 // referenced object is not accessed. Otherwise, if the glvalue
451 // has a class type, the conversion copy-initializes a temporary
452 // of type T from the glvalue and the result of the conversion
453 // is a prvalue for the temporary.
454 // FIXME: add some way to gate this entire thing for correctness in
455 // potentially potentially evaluated contexts.
John McCall4bb057d2011-08-27 22:06:17 +0000456 if (getLangOptions().CPlusPlus && E->isGLValue() &&
457 ExprEvalContexts.back().Context != Unevaluated) {
John McCall29ad95b2011-08-27 01:09:30 +0000458 ExprResult Temp = PerformCopyInitialization(
459 InitializedEntity::InitializeTemporary(E->getType()),
460 E->getExprLoc(),
461 Owned(E));
462 if (Temp.isInvalid())
463 return ExprError();
464 E = Temp.get();
465 }
466
John Wiegley01296292011-04-08 18:41:53 +0000467 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000468}
469
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000470/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
471/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000472/// interfaces passed by value.
473ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000474 FunctionDecl *FDecl) {
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000475 ExprResult ExprRes = CheckPlaceholderExpr(E);
476 if (ExprRes.isInvalid())
477 return ExprError();
478
479 ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000480 if (ExprRes.isInvalid())
481 return ExprError();
482 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000483
Douglas Gregor347e0f22011-05-21 19:26:31 +0000484 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000485 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000486 DiagRuntimeBehavior(E->getLocStart(), 0,
487 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
488 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000489 return ExprError();
John McCall29ad95b2011-08-27 01:09:30 +0000490
John McCall31168b02011-06-15 23:02:42 +0000491 if (!E->getType().isPODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000492 // C++0x [expr.call]p7:
493 // Passing a potentially-evaluated argument of class type (Clause 9)
494 // having a non-trivial copy constructor, a non-trivial move constructor,
495 // or a non-trivial destructor, with no corresponding parameter,
496 // is conditionally-supported with implementation-defined semantics.
497 bool TrivialEnough = false;
498 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
499 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
500 if (Record->hasTrivialCopyConstructor() &&
501 Record->hasTrivialMoveConstructor() &&
502 Record->hasTrivialDestructor())
503 TrivialEnough = true;
504 }
505 }
John McCall31168b02011-06-15 23:02:42 +0000506
507 if (!TrivialEnough &&
508 getLangOptions().ObjCAutoRefCount &&
509 E->getType()->isObjCLifetimeType())
510 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000511
512 if (TrivialEnough) {
513 // Nothing to diagnose. This is okay.
514 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000515 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor253cadf2011-05-21 16:27:21 +0000516 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000517 << CT)) {
518 // Turn this into a trap.
519 CXXScopeSpec SS;
520 UnqualifiedId Name;
521 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
522 E->getLocStart());
523 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
524 if (TrapFn.isInvalid())
525 return ExprError();
526
527 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
528 MultiExprArg(), E->getLocEnd());
529 if (Call.isInvalid())
530 return ExprError();
531
532 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
533 Call.get(), E);
534 if (Comma.isInvalid())
John McCall1cd60a22011-08-26 18:41:18 +0000535 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000536 E = Comma.get();
537 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000538 }
539
John Wiegley01296292011-04-08 18:41:53 +0000540 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000541}
542
Richard Trieu7aa58f12011-09-02 20:58:51 +0000543/// \brief Converts an integer to complex float type. Helper function of
544/// UsualArithmeticConversions()
545///
546/// \return false if the integer expression is an integer type and is
547/// successfully converted to the complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000548static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
549 ExprResult &ComplexExpr,
550 QualType IntTy,
551 QualType ComplexTy,
552 bool SkipCast) {
553 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
554 if (SkipCast) return false;
555 if (IntTy->isIntegerType()) {
556 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
557 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
558 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000559 CK_FloatingRealToComplex);
560 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +0000561 assert(IntTy->isComplexIntegerType());
562 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000563 CK_IntegralComplexToFloatingComplex);
564 }
565 return false;
566}
567
568/// \brief Takes two complex float types and converts them to the same type.
569/// Helper function of UsualArithmeticConversions()
570static QualType
Richard Trieu5065cdd2011-09-06 18:25:09 +0000571handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
572 ExprResult &RHS, QualType LHSType,
573 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000574 bool IsCompAssign) {
Richard Trieu5065cdd2011-09-06 18:25:09 +0000575 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000576
577 if (order < 0) {
578 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000579 if (!IsCompAssign)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000580 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
581 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000582 }
583 if (order > 0)
584 // _Complex float -> _Complex double
Richard Trieu5065cdd2011-09-06 18:25:09 +0000585 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
586 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000587}
588
589/// \brief Converts otherExpr to complex float and promotes complexExpr if
590/// necessary. Helper function of UsualArithmeticConversions()
591static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuba63ce62011-09-09 01:45:06 +0000592 ExprResult &ComplexExpr,
593 ExprResult &OtherExpr,
594 QualType ComplexTy,
595 QualType OtherTy,
596 bool ConvertComplexExpr,
597 bool ConvertOtherExpr) {
598 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000599
600 // If just the complexExpr is complex, the otherExpr needs to be converted,
601 // and the complexExpr might need to be promoted.
602 if (order > 0) { // complexExpr is wider
603 // float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000604 if (ConvertOtherExpr) {
605 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
606 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
607 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000608 CK_FloatingRealToComplex);
609 }
Richard Trieuba63ce62011-09-09 01:45:06 +0000610 return ComplexTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000611 }
612
613 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000614 QualType result = (order == 0 ? ComplexTy :
615 S.Context.getComplexType(OtherTy));
Richard Trieu7aa58f12011-09-02 20:58:51 +0000616
617 // double -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000618 if (ConvertOtherExpr)
619 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000620 CK_FloatingRealToComplex);
621
622 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000623 if (ConvertComplexExpr && order < 0)
624 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000625 CK_FloatingComplexCast);
626
627 return result;
628}
629
630/// \brief Handle arithmetic conversion with complex types. Helper function of
631/// UsualArithmeticConversions()
Richard Trieu5065cdd2011-09-06 18:25:09 +0000632static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
633 ExprResult &RHS, QualType LHSType,
634 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000635 bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000636 // if we have an integer operand, the result is the complex type.
Richard Trieu5065cdd2011-09-06 18:25:09 +0000637 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000638 /*skipCast*/false))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000639 return LHSType;
640 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000641 /*skipCast*/IsCompAssign))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000642 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000643
644 // This handles complex/complex, complex/float, or float/complex.
645 // When both operands are complex, the shorter operand is converted to the
646 // type of the longer, and that is the type of the result. This corresponds
647 // to what is done when combining two real floating-point operands.
648 // The fun begins when size promotion occur across type domains.
649 // From H&S 6.3.4: When one operand is complex and the other is a real
650 // floating-point type, the less precise type is converted, within it's
651 // real or complex domain, to the precision of the other type. For example,
652 // when combining a "long double" with a "double _Complex", the
653 // "double _Complex" is promoted to "long double _Complex".
654
Richard Trieu5065cdd2011-09-06 18:25:09 +0000655 bool LHSComplexFloat = LHSType->isComplexType();
656 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000657
658 // If both are complex, just cast to the more precise type.
659 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000660 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
661 LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000662 IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000663
664 // If only one operand is complex, promote it if necessary and convert the
665 // other operand to complex.
666 if (LHSComplexFloat)
667 return handleOtherComplexFloatConversion(
Richard Trieuba63ce62011-09-09 01:45:06 +0000668 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000669 /*convertOtherExpr*/ true);
670
671 assert(RHSComplexFloat);
672 return handleOtherComplexFloatConversion(
Richard Trieu5065cdd2011-09-06 18:25:09 +0000673 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000674 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000675}
676
677/// \brief Hande arithmetic conversion from integer to float. Helper function
678/// of UsualArithmeticConversions()
Richard Trieuba63ce62011-09-09 01:45:06 +0000679static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
680 ExprResult &IntExpr,
681 QualType FloatTy, QualType IntTy,
682 bool ConvertFloat, bool ConvertInt) {
683 if (IntTy->isIntegerType()) {
684 if (ConvertInt)
Richard Trieu7aa58f12011-09-02 20:58:51 +0000685 // Convert intExpr to the lhs floating point type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000686 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000687 CK_IntegralToFloating);
Richard Trieuba63ce62011-09-09 01:45:06 +0000688 return FloatTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000689 }
690
691 // Convert both sides to the appropriate complex float.
Richard Trieuba63ce62011-09-09 01:45:06 +0000692 assert(IntTy->isComplexIntegerType());
693 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000694
695 // _Complex int -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000696 if (ConvertInt)
697 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000698 CK_IntegralComplexToFloatingComplex);
699
700 // float -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000701 if (ConvertFloat)
702 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000703 CK_FloatingRealToComplex);
704
705 return result;
706}
707
708/// \brief Handle arithmethic conversion with floating point types. Helper
709/// function of UsualArithmeticConversions()
Richard Trieucfe3f212011-09-06 18:38:41 +0000710static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
711 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000712 QualType RHSType, bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000713 bool LHSFloat = LHSType->isRealFloatingType();
714 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000715
716 // If we have two real floating types, convert the smaller operand
717 // to the bigger result.
718 if (LHSFloat && RHSFloat) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000719 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000720 if (order > 0) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000721 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
722 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000723 }
724
725 assert(order < 0 && "illegal float comparison");
Richard Trieuba63ce62011-09-09 01:45:06 +0000726 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000727 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
728 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000729 }
730
731 if (LHSFloat)
Richard Trieucfe3f212011-09-06 18:38:41 +0000732 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000733 /*convertFloat=*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000734 /*convertInt=*/ true);
735 assert(RHSFloat);
Richard Trieucfe3f212011-09-06 18:38:41 +0000736 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000737 /*convertInt=*/ true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000738 /*convertFloat=*/!IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000739}
740
741/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000742/// of UsualArithmeticConversions()
Richard Trieu7aa58f12011-09-02 20:58:51 +0000743// FIXME: if the operands are (int, _Complex long), we currently
744// don't promote the complex. Also, signedness?
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000745static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
746 ExprResult &RHS, QualType LHSType,
747 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000748 bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000749 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
750 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000751
Richard Trieucfe3f212011-09-06 18:38:41 +0000752 if (LHSComplexInt && RHSComplexInt) {
753 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
754 RHSComplexInt->getElementType());
Richard Trieu7aa58f12011-09-02 20:58:51 +0000755 assert(order && "inequal types with equal element ordering");
756 if (order > 0) {
757 // _Complex int -> _Complex long
Richard Trieucfe3f212011-09-06 18:38:41 +0000758 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
759 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000760 }
761
Richard Trieuba63ce62011-09-09 01:45:06 +0000762 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000763 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
764 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000765 }
766
Richard Trieucfe3f212011-09-06 18:38:41 +0000767 if (LHSComplexInt) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000768 // int -> _Complex int
Richard Trieucfe3f212011-09-06 18:38:41 +0000769 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
770 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000771 }
772
Richard Trieucfe3f212011-09-06 18:38:41 +0000773 assert(RHSComplexInt);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000774 // int -> _Complex int
Richard Trieuba63ce62011-09-09 01:45:06 +0000775 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000776 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
777 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000778}
779
780/// \brief Handle integer arithmetic conversions. Helper function of
781/// UsualArithmeticConversions()
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000782static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
783 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000784 QualType RHSType, bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000785 // The rules for this case are in C99 6.3.1.8
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000786 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
787 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
788 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
789 if (LHSSigned == RHSSigned) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000790 // Same signedness; use the higher-ranked type
791 if (order >= 0) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000792 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
793 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000794 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000795 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
796 return RHSType;
797 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000798 // The unsigned type has greater than or equal rank to the
799 // signed type, so use the unsigned type
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000800 if (RHSSigned) {
801 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
802 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000803 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000804 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
805 return RHSType;
806 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000807 // The two types are different widths; if we are here, that
808 // means the signed type is larger than the unsigned type, so
809 // use the signed type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000810 if (LHSSigned) {
811 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
812 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000813 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000814 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
815 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000816 } else {
817 // The signed type is higher-ranked than the unsigned type,
818 // but isn't actually any bigger (like unsigned int and long
819 // on most 32-bit systems). Use the unsigned type corresponding
820 // to the signed type.
821 QualType result =
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000822 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
823 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuba63ce62011-09-09 01:45:06 +0000824 if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000825 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000826 return result;
827 }
828}
829
Chris Lattner513165e2008-07-25 21:10:04 +0000830/// UsualArithmeticConversions - Performs various conversions that are common to
831/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000832/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000833/// responsible for emitting appropriate error diagnostics.
834/// FIXME: verify the conversion rules for "complex int" are consistent with
835/// GCC.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000836QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +0000837 bool IsCompAssign) {
838 if (!IsCompAssign) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000839 LHS = UsualUnaryConversions(LHS.take());
840 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000841 return QualType();
842 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000843
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000844 RHS = UsualUnaryConversions(RHS.take());
845 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000846 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000847
Mike Stump11289f42009-09-09 15:08:12 +0000848 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000849 // For example, "const float" and "float" are equivalent.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000850 QualType LHSType =
851 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
852 QualType RHSType =
853 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000854
855 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000856 if (LHSType == RHSType)
857 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000858
859 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
860 // The caller can deal with this (e.g. pointer + int).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000861 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
862 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000863
John McCalld005ac92010-11-13 08:17:45 +0000864 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000865 QualType LHSUnpromotedType = LHSType;
866 if (LHSType->isPromotableIntegerType())
867 LHSType = Context.getPromotedIntegerType(LHSType);
868 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000869 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000870 LHSType = LHSBitfieldPromoteTy;
Richard Trieuba63ce62011-09-09 01:45:06 +0000871 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000872 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000873
John McCalld005ac92010-11-13 08:17:45 +0000874 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000875 if (LHSType == RHSType)
876 return LHSType;
John McCalld005ac92010-11-13 08:17:45 +0000877
878 // At this point, we have two different arithmetic types.
879
880 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000881 if (LHSType->isComplexType() || RHSType->isComplexType())
882 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000883 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000884
885 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000886 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
887 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000888 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000889
890 // Handle GCC complex int extension.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000891 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000892 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000893 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000894
895 // Finally, we have two differing integer types.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000896 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000897 IsCompAssign);
Douglas Gregora11693b2008-11-12 17:17:38 +0000898}
899
Chris Lattner513165e2008-07-25 21:10:04 +0000900//===----------------------------------------------------------------------===//
901// Semantic Analysis for various Expression Types
902//===----------------------------------------------------------------------===//
903
904
Peter Collingbourne91147592011-04-15 00:35:48 +0000905ExprResult
906Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
907 SourceLocation DefaultLoc,
908 SourceLocation RParenLoc,
909 Expr *ControllingExpr,
Richard Trieuba63ce62011-09-09 01:45:06 +0000910 MultiTypeArg ArgTypes,
911 MultiExprArg ArgExprs) {
912 unsigned NumAssocs = ArgTypes.size();
913 assert(NumAssocs == ArgExprs.size());
Peter Collingbourne91147592011-04-15 00:35:48 +0000914
Richard Trieuba63ce62011-09-09 01:45:06 +0000915 ParsedType *ParsedTypes = ArgTypes.release();
916 Expr **Exprs = ArgExprs.release();
Peter Collingbourne91147592011-04-15 00:35:48 +0000917
918 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
919 for (unsigned i = 0; i < NumAssocs; ++i) {
920 if (ParsedTypes[i])
921 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
922 else
923 Types[i] = 0;
924 }
925
926 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
927 ControllingExpr, Types, Exprs,
928 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000929 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000930 return ER;
931}
932
933ExprResult
934Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
935 SourceLocation DefaultLoc,
936 SourceLocation RParenLoc,
937 Expr *ControllingExpr,
938 TypeSourceInfo **Types,
939 Expr **Exprs,
940 unsigned NumAssocs) {
941 bool TypeErrorFound = false,
942 IsResultDependent = ControllingExpr->isTypeDependent(),
943 ContainsUnexpandedParameterPack
944 = ControllingExpr->containsUnexpandedParameterPack();
945
946 for (unsigned i = 0; i < NumAssocs; ++i) {
947 if (Exprs[i]->containsUnexpandedParameterPack())
948 ContainsUnexpandedParameterPack = true;
949
950 if (Types[i]) {
951 if (Types[i]->getType()->containsUnexpandedParameterPack())
952 ContainsUnexpandedParameterPack = true;
953
954 if (Types[i]->getType()->isDependentType()) {
955 IsResultDependent = true;
956 } else {
957 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
958 // complete object type other than a variably modified type."
959 unsigned D = 0;
960 if (Types[i]->getType()->isIncompleteType())
961 D = diag::err_assoc_type_incomplete;
962 else if (!Types[i]->getType()->isObjectType())
963 D = diag::err_assoc_type_nonobject;
964 else if (Types[i]->getType()->isVariablyModifiedType())
965 D = diag::err_assoc_type_variably_modified;
966
967 if (D != 0) {
968 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
969 << Types[i]->getTypeLoc().getSourceRange()
970 << Types[i]->getType();
971 TypeErrorFound = true;
972 }
973
974 // C1X 6.5.1.1p2 "No two generic associations in the same generic
975 // selection shall specify compatible types."
976 for (unsigned j = i+1; j < NumAssocs; ++j)
977 if (Types[j] && !Types[j]->getType()->isDependentType() &&
978 Context.typesAreCompatible(Types[i]->getType(),
979 Types[j]->getType())) {
980 Diag(Types[j]->getTypeLoc().getBeginLoc(),
981 diag::err_assoc_compatible_types)
982 << Types[j]->getTypeLoc().getSourceRange()
983 << Types[j]->getType()
984 << Types[i]->getType();
985 Diag(Types[i]->getTypeLoc().getBeginLoc(),
986 diag::note_compat_assoc)
987 << Types[i]->getTypeLoc().getSourceRange()
988 << Types[i]->getType();
989 TypeErrorFound = true;
990 }
991 }
992 }
993 }
994 if (TypeErrorFound)
995 return ExprError();
996
997 // If we determined that the generic selection is result-dependent, don't
998 // try to compute the result expression.
999 if (IsResultDependent)
1000 return Owned(new (Context) GenericSelectionExpr(
1001 Context, KeyLoc, ControllingExpr,
1002 Types, Exprs, NumAssocs, DefaultLoc,
1003 RParenLoc, ContainsUnexpandedParameterPack));
1004
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001005 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +00001006 unsigned DefaultIndex = -1U;
1007 for (unsigned i = 0; i < NumAssocs; ++i) {
1008 if (!Types[i])
1009 DefaultIndex = i;
1010 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1011 Types[i]->getType()))
1012 CompatIndices.push_back(i);
1013 }
1014
1015 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
1016 // type compatible with at most one of the types named in its generic
1017 // association list."
1018 if (CompatIndices.size() > 1) {
1019 // We strip parens here because the controlling expression is typically
1020 // parenthesized in macro definitions.
1021 ControllingExpr = ControllingExpr->IgnoreParens();
1022 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1023 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1024 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001025 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +00001026 E = CompatIndices.end(); I != E; ++I) {
1027 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1028 diag::note_compat_assoc)
1029 << Types[*I]->getTypeLoc().getSourceRange()
1030 << Types[*I]->getType();
1031 }
1032 return ExprError();
1033 }
1034
1035 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
1036 // its controlling expression shall have type compatible with exactly one of
1037 // the types named in its generic association list."
1038 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1039 // We strip parens here because the controlling expression is typically
1040 // parenthesized in macro definitions.
1041 ControllingExpr = ControllingExpr->IgnoreParens();
1042 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1043 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1044 return ExprError();
1045 }
1046
1047 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
1048 // type name that is compatible with the type of the controlling expression,
1049 // then the result expression of the generic selection is the expression
1050 // in that generic association. Otherwise, the result expression of the
1051 // generic selection is the expression in the default generic association."
1052 unsigned ResultIndex =
1053 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1054
1055 return Owned(new (Context) GenericSelectionExpr(
1056 Context, KeyLoc, ControllingExpr,
1057 Types, Exprs, NumAssocs, DefaultLoc,
1058 RParenLoc, ContainsUnexpandedParameterPack,
1059 ResultIndex));
1060}
1061
Steve Naroff83895f72007-09-16 03:34:24 +00001062/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001063/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1064/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1065/// multiple tokens. However, the common case is that StringToks points to one
1066/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001067///
John McCalldadc5752010-08-24 06:29:42 +00001068ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +00001069Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001070 assert(NumStringToks && "Must have at least one string!");
1071
Chris Lattner8a24e582009-01-16 18:51:42 +00001072 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001073 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001074 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001075
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001076 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001077 for (unsigned i = 0; i != NumStringToks; ++i)
1078 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001079
Chris Lattner36fc8792008-02-11 00:02:17 +00001080 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001081 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001082 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001083 else if (Literal.isUTF16())
1084 StrTy = Context.Char16Ty;
1085 else if (Literal.isUTF32())
1086 StrTy = Context.Char32Ty;
Anders Carlsson6b06e182011-04-06 18:42:48 +00001087 else if (Literal.Pascal)
1088 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001089
Douglas Gregorfb65e592011-07-27 05:40:30 +00001090 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1091 if (Literal.isWide())
1092 Kind = StringLiteral::Wide;
1093 else if (Literal.isUTF8())
1094 Kind = StringLiteral::UTF8;
1095 else if (Literal.isUTF16())
1096 Kind = StringLiteral::UTF16;
1097 else if (Literal.isUTF32())
1098 Kind = StringLiteral::UTF32;
1099
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001100 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +00001101 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001102 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001103
Chris Lattner36fc8792008-02-11 00:02:17 +00001104 // Get an array type for the string, according to C99 6.4.5. This includes
1105 // the nul terminator character as well as the string length for pascal
1106 // strings.
1107 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001108 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001109 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001110
Chris Lattner5b183d82006-11-10 05:03:26 +00001111 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +00001112 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001113 Kind, Literal.Pascal, StrTy,
Alexis Hunt3b791862010-08-30 17:47:05 +00001114 &StringTokLocs[0],
1115 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +00001116}
1117
John McCallc63de662011-02-02 13:00:07 +00001118enum CaptureResult {
1119 /// No capture is required.
1120 CR_NoCapture,
1121
1122 /// A capture is required.
1123 CR_Capture,
1124
John McCall351762c2011-02-07 10:33:21 +00001125 /// A by-ref capture is required.
1126 CR_CaptureByRef,
1127
John McCallc63de662011-02-02 13:00:07 +00001128 /// An error occurred when trying to capture the given variable.
1129 CR_Error
1130};
1131
1132/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +00001133///
John McCallc63de662011-02-02 13:00:07 +00001134/// \param var - the variable referenced
1135/// \param DC - the context which we couldn't capture through
1136static CaptureResult
John McCall351762c2011-02-07 10:33:21 +00001137diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001138 VarDecl *var, DeclContext *DC) {
1139 switch (S.ExprEvalContexts.back().Context) {
1140 case Sema::Unevaluated:
1141 // The argument will never be evaluated, so don't complain.
1142 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +00001143
John McCallc63de662011-02-02 13:00:07 +00001144 case Sema::PotentiallyEvaluated:
1145 case Sema::PotentiallyEvaluatedIfUsed:
1146 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +00001147
John McCallc63de662011-02-02 13:00:07 +00001148 case Sema::PotentiallyPotentiallyEvaluated:
1149 // FIXME: delay these!
1150 break;
Chris Lattner497d7b02009-04-21 22:26:47 +00001151 }
Mike Stump11289f42009-09-09 15:08:12 +00001152
John McCallc63de662011-02-02 13:00:07 +00001153 // Don't diagnose about capture if we're not actually in code right
1154 // now; in general, there are more appropriate places that will
1155 // diagnose this.
1156 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1157
John McCall92d627e2011-03-22 23:15:50 +00001158 // Certain madnesses can happen with parameter declarations, which
1159 // we want to ignore.
1160 if (isa<ParmVarDecl>(var)) {
1161 // - If the parameter still belongs to the translation unit, then
1162 // we're actually just using one parameter in the declaration of
1163 // the next. This is useful in e.g. VLAs.
1164 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1165 return CR_NoCapture;
1166
1167 // - This particular madness can happen in ill-formed default
1168 // arguments; claim it's okay and let downstream code handle it.
1169 if (S.CurContext == var->getDeclContext()->getParent())
1170 return CR_NoCapture;
1171 }
John McCallc63de662011-02-02 13:00:07 +00001172
1173 DeclarationName functionName;
1174 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1175 functionName = fn->getDeclName();
1176 // FIXME: variable from enclosing block that we couldn't capture from!
1177
1178 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1179 << var->getIdentifier() << functionName;
1180 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1181 << var->getIdentifier();
1182
1183 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +00001184}
1185
John McCall351762c2011-02-07 10:33:21 +00001186/// There is a well-formed capture at a particular scope level;
1187/// propagate it through all the nested blocks.
Richard Trieuba63ce62011-09-09 01:45:06 +00001188static CaptureResult propagateCapture(Sema &S, unsigned ValidScopeIndex,
1189 const BlockDecl::Capture &Capture) {
1190 VarDecl *var = Capture.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001191
1192 // Update all the inner blocks with the capture information.
Richard Trieuba63ce62011-09-09 01:45:06 +00001193 for (unsigned i = ValidScopeIndex + 1, e = S.FunctionScopes.size();
John McCall351762c2011-02-07 10:33:21 +00001194 i != e; ++i) {
1195 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1196 innerBlock->Captures.push_back(
Richard Trieuba63ce62011-09-09 01:45:06 +00001197 BlockDecl::Capture(Capture.getVariable(), Capture.isByRef(),
1198 /*nested*/ true, Capture.getCopyExpr()));
John McCall351762c2011-02-07 10:33:21 +00001199 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1200 }
1201
Richard Trieuba63ce62011-09-09 01:45:06 +00001202 return Capture.isByRef() ? CR_CaptureByRef : CR_Capture;
John McCall351762c2011-02-07 10:33:21 +00001203}
1204
1205/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +00001206/// given value in the current context requires a variable capture.
1207///
1208/// This also keeps the captures set in the BlockScopeInfo records
1209/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +00001210static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00001211 ValueDecl *Value) {
John McCallc63de662011-02-02 13:00:07 +00001212 // Only variables ever require capture.
Richard Trieuba63ce62011-09-09 01:45:06 +00001213 VarDecl *var = dyn_cast<VarDecl>(Value);
John McCallf4cd4f92011-02-09 01:13:10 +00001214 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +00001215
1216 // Fast path: variables from the current context never require capture.
1217 DeclContext *DC = S.CurContext;
1218 if (var->getDeclContext() == DC) return CR_NoCapture;
1219
1220 // Only variables with local storage require capture.
1221 // FIXME: What about 'const' variables in C++?
1222 if (!var->hasLocalStorage()) return CR_NoCapture;
1223
1224 // Otherwise, we need to capture.
1225
1226 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +00001227 do {
1228 // Only blocks (and eventually C++0x closures) can capture; other
1229 // scopes don't work.
1230 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +00001231 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +00001232
1233 BlockScopeInfo *blockScope =
1234 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1235 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1236
John McCall351762c2011-02-07 10:33:21 +00001237 // Check whether we've already captured it in this block. If so,
1238 // we're done.
1239 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1240 return propagateCapture(S, functionScopesIndex,
1241 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +00001242
1243 functionScopesIndex--;
1244 DC = cast<BlockDecl>(DC)->getDeclContext();
1245 } while (var->getDeclContext() != DC);
1246
John McCall351762c2011-02-07 10:33:21 +00001247 // Okay, we descended all the way to the block that defines the variable.
1248 // Actually try to capture it.
1249 QualType type = var->getType();
1250
1251 // Prohibit variably-modified types.
1252 if (type->isVariablyModifiedType()) {
1253 S.Diag(loc, diag::err_ref_vm_type);
1254 S.Diag(var->getLocation(), diag::note_declared_at);
1255 return CR_Error;
1256 }
1257
1258 // Prohibit arrays, even in __block variables, but not references to
1259 // them.
1260 if (type->isArrayType()) {
1261 S.Diag(loc, diag::err_ref_array_type);
1262 S.Diag(var->getLocation(), diag::note_declared_at);
1263 return CR_Error;
1264 }
1265
1266 S.MarkDeclarationReferenced(loc, var);
1267
1268 // The BlocksAttr indicates the variable is bound by-reference.
1269 bool byRef = var->hasAttr<BlocksAttr>();
1270
1271 // Build a copy expression.
1272 Expr *copyExpr = 0;
John McCalla85af562011-04-28 02:15:35 +00001273 const RecordType *rtype;
1274 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1275 (rtype = type->getAs<RecordType>())) {
1276
1277 // The capture logic needs the destructor, so make sure we mark it.
1278 // Usually this is unnecessary because most local variables have
1279 // their destructors marked at declaration time, but parameters are
1280 // an exception because it's technically only the call site that
1281 // actually requires the destructor.
1282 if (isa<ParmVarDecl>(var))
1283 S.FinalizeVarWithDestructor(var, rtype);
1284
John McCall351762c2011-02-07 10:33:21 +00001285 // According to the blocks spec, the capture of a variable from
1286 // the stack requires a const copy constructor. This is not true
1287 // of the copy/move done to move a __block variable to the heap.
1288 type.addConst();
1289
1290 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1291 ExprResult result =
1292 S.PerformCopyInitialization(
1293 InitializedEntity::InitializeBlock(var->getLocation(),
1294 type, false),
1295 loc, S.Owned(declRef));
1296
1297 // Build a full-expression copy expression if initialization
1298 // succeeded and used a non-trivial constructor. Recover from
1299 // errors by pretending that the copy isn't necessary.
1300 if (!result.isInvalid() &&
1301 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1302 result = S.MaybeCreateExprWithCleanups(result);
1303 copyExpr = result.take();
1304 }
1305 }
1306
1307 // We're currently at the declarer; go back to the closure.
1308 functionScopesIndex++;
1309 BlockScopeInfo *blockScope =
1310 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1311
1312 // Build a valid capture in this scope.
1313 blockScope->Captures.push_back(
1314 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1315 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1316
1317 // Propagate that to inner captures if necessary.
1318 return propagateCapture(S, functionScopesIndex,
1319 blockScope->Captures.back());
1320}
1321
Richard Trieuba63ce62011-09-09 01:45:06 +00001322static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *VD,
John McCall351762c2011-02-07 10:33:21 +00001323 const DeclarationNameInfo &NameInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00001324 bool ByRef) {
1325 assert(isa<VarDecl>(VD) && "capturing non-variable");
John McCall351762c2011-02-07 10:33:21 +00001326
Richard Trieuba63ce62011-09-09 01:45:06 +00001327 VarDecl *var = cast<VarDecl>(VD);
John McCall351762c2011-02-07 10:33:21 +00001328 assert(var->hasLocalStorage() && "capturing non-local");
Richard Trieuba63ce62011-09-09 01:45:06 +00001329 assert(ByRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
John McCall351762c2011-02-07 10:33:21 +00001330
1331 QualType exprType = var->getType().getNonReferenceType();
1332
1333 BlockDeclRefExpr *BDRE;
Richard Trieuba63ce62011-09-09 01:45:06 +00001334 if (!ByRef) {
John McCall351762c2011-02-07 10:33:21 +00001335 // The variable will be bound by copy; make it const within the
1336 // closure, but record that this was done in the expression.
1337 bool constAdded = !exprType.isConstQualified();
1338 exprType.addConst();
1339
1340 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1341 NameInfo.getLoc(), false,
1342 constAdded);
1343 } else {
1344 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1345 NameInfo.getLoc(), true);
1346 }
1347
1348 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001349}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001350
John McCalldadc5752010-08-24 06:29:42 +00001351ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001352Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001353 SourceLocation Loc,
1354 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001355 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001356 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001357}
1358
John McCallf4cd4f92011-02-09 01:13:10 +00001359/// BuildDeclRefExpr - Build an expression that references a
1360/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001361ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001362Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001363 const DeclarationNameInfo &NameInfo,
1364 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001365 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001366
John McCall086a4642010-11-24 05:12:34 +00001367 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001368 SS? SS->getWithLocInContext(Context)
1369 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001370 D, NameInfo, Ty, VK);
1371
1372 // Just in case we're building an illegal pointer-to-member.
1373 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1374 E->setObjectKind(OK_BitField);
1375
1376 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001377}
1378
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001379/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001380/// possibly a list of template arguments.
1381///
1382/// If this produces template arguments, it is permitted to call
1383/// DecomposeTemplateName.
1384///
1385/// This actually loses a lot of source location information for
1386/// non-standard name kinds; we should consider preserving that in
1387/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001388void
1389Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1390 TemplateArgumentListInfo &Buffer,
1391 DeclarationNameInfo &NameInfo,
1392 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001393 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1394 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1395 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1396
Douglas Gregor5476205b2011-06-23 00:49:38 +00001397 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001398 Id.TemplateId->getTemplateArgs(),
1399 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001400 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001401 TemplateArgsPtr.release();
1402
John McCall3e56fd42010-08-23 07:28:44 +00001403 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001404 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001405 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001406 TemplateArgs = &Buffer;
1407 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001408 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001409 TemplateArgs = 0;
1410 }
1411}
1412
John McCalld681c392009-12-16 08:11:27 +00001413/// Diagnose an empty lookup.
1414///
1415/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001416bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001417 CorrectTypoContext CTC,
1418 TemplateArgumentListInfo *ExplicitTemplateArgs,
1419 Expr **Args, unsigned NumArgs) {
John McCalld681c392009-12-16 08:11:27 +00001420 DeclarationName Name = R.getLookupName();
1421
John McCalld681c392009-12-16 08:11:27 +00001422 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001423 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001424 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1425 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001426 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001427 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001428 diagnostic_suggest = diag::err_undeclared_use_suggest;
1429 }
John McCalld681c392009-12-16 08:11:27 +00001430
Douglas Gregor598b08f2009-12-31 05:20:13 +00001431 // If the original lookup was an unqualified lookup, fake an
1432 // unqualified lookup. This is useful when (for example) the
1433 // original lookup would not have found something because it was a
1434 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001435 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001436 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001437 if (isa<CXXRecordDecl>(DC)) {
1438 LookupQualifiedName(R, DC);
1439
1440 if (!R.empty()) {
1441 // Don't give errors about ambiguities in this lookup.
1442 R.suppressDiagnostics();
1443
1444 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1445 bool isInstance = CurMethod &&
1446 CurMethod->isInstance() &&
1447 DC == CurMethod->getParent();
1448
1449 // Give a code modification hint to insert 'this->'.
1450 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1451 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001452 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001453 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1454 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001455 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001456 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001457 if (DepMethod) {
Francois Pichet0706d202011-09-17 17:15:52 +00001458 if (getLangOptions().MicrosoftExt)
Francois Pichetbcf64712011-09-07 00:14:57 +00001459 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyfe712382010-08-20 20:54:15 +00001460 Diag(R.getNameLoc(), diagnostic) << Name
1461 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1462 QualType DepThisType = DepMethod->getThisType(Context);
1463 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1464 R.getNameLoc(), DepThisType, false);
1465 TemplateArgumentListInfo TList;
1466 if (ULE->hasExplicitTemplateArgs())
1467 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001468
Douglas Gregore16af532011-02-28 18:50:33 +00001469 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001470 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001471 CXXDependentScopeMemberExpr *DepExpr =
1472 CXXDependentScopeMemberExpr::Create(
1473 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001474 SS.getWithLocInContext(Context), NULL,
Francois Pichet4391c752011-09-04 23:00:48 +00001475 R.getLookupNameInfo(),
1476 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyfe712382010-08-20 20:54:15 +00001477 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001478 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001479 // FIXME: we should be able to handle this case too. It is correct
1480 // to add this-> here. This is a workaround for PR7947.
1481 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001482 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001483 } else {
John McCalld681c392009-12-16 08:11:27 +00001484 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001485 }
John McCalld681c392009-12-16 08:11:27 +00001486
1487 // Do we really want to note all of these?
1488 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1489 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1490
1491 // Tell the callee to try to recover.
1492 return false;
1493 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001494
1495 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001496 }
1497 }
1498
Douglas Gregor598b08f2009-12-31 05:20:13 +00001499 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001500 TypoCorrection Corrected;
1501 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1502 S, &SS, NULL, false, CTC))) {
1503 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1504 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1505 R.setLookupName(Corrected.getCorrection());
1506
Hans Wennborg38198de2011-07-12 08:45:31 +00001507 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001508 if (Corrected.isOverloaded()) {
1509 OverloadCandidateSet OCS(R.getNameLoc());
1510 OverloadCandidateSet::iterator Best;
1511 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1512 CDEnd = Corrected.end();
1513 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001514 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001515 dyn_cast<FunctionTemplateDecl>(*CD))
1516 AddTemplateOverloadCandidate(
1517 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1518 Args, NumArgs, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001519 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1520 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1521 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1522 Args, NumArgs, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001523 }
1524 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1525 case OR_Success:
1526 ND = Best->Function;
1527 break;
1528 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001529 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001530 }
1531 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001532 R.addDecl(ND);
1533 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001534 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001535 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1536 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001537 else
1538 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001539 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001540 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001541 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1542 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001543 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001544 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001545
1546 // Tell the callee to try to recover.
1547 return false;
1548 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001549
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001550 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001551 // FIXME: If we ended up with a typo for a type name or
1552 // Objective-C class name, we're in trouble because the parser
1553 // is in the wrong place to recover. Suggest the typo
1554 // correction, but don't make it a fix-it since we're not going
1555 // to recover well anyway.
1556 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001557 Diag(R.getNameLoc(), diagnostic_suggest)
1558 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001559 else
1560 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001561 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001562 << SS.getRange();
1563
1564 // Don't try to recover; it won't work.
1565 return true;
1566 }
1567 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001568 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001569 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001570 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001571 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001572 else
Douglas Gregor25363982010-01-01 00:15:04 +00001573 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001574 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001575 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001576 return true;
1577 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001578 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001579 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001580
1581 // Emit a special diagnostic for failed member lookups.
1582 // FIXME: computing the declaration context might fail here (?)
1583 if (!SS.isEmpty()) {
1584 Diag(R.getNameLoc(), diag::err_no_member)
1585 << Name << computeDeclContext(SS, false)
1586 << SS.getRange();
1587 return true;
1588 }
1589
John McCalld681c392009-12-16 08:11:27 +00001590 // Give up, we can't recover.
1591 Diag(R.getNameLoc(), diagnostic) << Name;
1592 return true;
1593}
1594
John McCalldadc5752010-08-24 06:29:42 +00001595ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001596 CXXScopeSpec &SS,
1597 UnqualifiedId &Id,
1598 bool HasTrailingLParen,
Richard Trieuba63ce62011-09-09 01:45:06 +00001599 bool IsAddressOfOperand) {
1600 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00001601 "cannot be direct & operand and have a trailing lparen");
1602
1603 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001604 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001605
John McCall10eae182009-11-30 22:42:35 +00001606 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001607
1608 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001609 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001610 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001611 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001612
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001613 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001614 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001615 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001616
John McCalle66edc12009-11-24 19:00:30 +00001617 // C++ [temp.dep.expr]p3:
1618 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001619 // -- an identifier that was declared with a dependent type,
1620 // (note: handled after lookup)
1621 // -- a template-id that is dependent,
1622 // (note: handled in BuildTemplateIdExpr)
1623 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001624 // -- a nested-name-specifier that contains a class-name that
1625 // names a dependent type.
1626 // Determine whether this is a member of an unknown specialization;
1627 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001628 bool DependentID = false;
1629 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1630 Name.getCXXNameType()->isDependentType()) {
1631 DependentID = true;
1632 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001633 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001634 if (RequireCompleteDeclContext(SS, DC))
1635 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001636 } else {
1637 DependentID = true;
1638 }
1639 }
1640
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001641 if (DependentID)
Richard Trieuba63ce62011-09-09 01:45:06 +00001642 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001643 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001644
Fariborz Jahanian86151342010-07-22 23:33:21 +00001645 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001646 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001647 LookupResult R(*this, NameInfo,
1648 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1649 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001650 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001651 // Lookup the template name again to correctly establish the context in
1652 // which it was found. This is really unfortunate as we already did the
1653 // lookup to determine that it was a template name in the first place. If
1654 // this becomes a performance hit, we can work harder to preserve those
1655 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001656 bool MemberOfUnknownSpecialization;
1657 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1658 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001659
1660 if (MemberOfUnknownSpecialization ||
1661 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Richard Trieuba63ce62011-09-09 01:45:06 +00001662 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregora5226932011-02-04 13:35:07 +00001663 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001664 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001665 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001666 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001667
Douglas Gregora5226932011-02-04 13:35:07 +00001668 // If the result might be in a dependent base class, this is a dependent
1669 // id-expression.
1670 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Richard Trieuba63ce62011-09-09 01:45:06 +00001671 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregora5226932011-02-04 13:35:07 +00001672 TemplateArgs);
1673
John McCalle66edc12009-11-24 19:00:30 +00001674 // If this reference is in an Objective-C method, then we need to do
1675 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001676 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001677 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001678 if (E.isInvalid())
1679 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001680
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001681 if (Expr *Ex = E.takeAs<Expr>())
1682 return Owned(Ex);
1683
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001684 // for further use, this must be set to false if in class method.
1685 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001686 }
Chris Lattner59a25942008-03-31 00:36:02 +00001687 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001688
John McCalle66edc12009-11-24 19:00:30 +00001689 if (R.isAmbiguous())
1690 return ExprError();
1691
Douglas Gregor171c45a2009-02-18 21:56:37 +00001692 // Determine whether this name might be a candidate for
1693 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001694 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001695
John McCalle66edc12009-11-24 19:00:30 +00001696 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001697 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001698 // in C90, extension in C99, forbidden in C++).
1699 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1700 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1701 if (D) R.addDecl(D);
1702 }
1703
1704 // If this name wasn't predeclared and if this is not a function
1705 // call, diagnose the problem.
1706 if (R.empty()) {
Francois Pichetd8e4e412011-09-24 10:38:05 +00001707
1708 // In Microsoft mode, if we are inside a template class member function
1709 // and we can't resolve an identifier then assume the identifier is type
1710 // dependent. The goal is to postpone name lookup to instantiation time
1711 // to be able to search into type dependent base classes.
1712 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
1713 isa<CXXMethodDecl>(CurContext))
1714 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
1715 TemplateArgs);
1716
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001717 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001718 return ExprError();
1719
1720 assert(!R.empty() &&
1721 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001722
1723 // If we found an Objective-C instance variable, let
1724 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001725 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001726 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1727 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001728 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanian44653702011-09-23 23:11:38 +00001729 // In a hopelessly buggy code, Objective-C instance variable
1730 // lookup fails and no expression will be built to reference it.
1731 if (!E.isInvalid() && !E.get())
1732 return ExprError();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001733 return move(E);
1734 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001735 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001736 }
Mike Stump11289f42009-09-09 15:08:12 +00001737
John McCalle66edc12009-11-24 19:00:30 +00001738 // This is guaranteed from this point on.
1739 assert(!R.empty() || ADL);
1740
John McCall2d74de92009-12-01 22:10:20 +00001741 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001742 // C++ [class.mfct.non-static]p3:
1743 // When an id-expression that is not part of a class member access
1744 // syntax and not used to form a pointer to member is used in the
1745 // body of a non-static member function of class X, if name lookup
1746 // resolves the name in the id-expression to a non-static non-type
1747 // member of some class C, the id-expression is transformed into a
1748 // class member access expression using (*this) as the
1749 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001750 //
1751 // But we don't actually need to do this for '&' operands if R
1752 // resolved to a function or overloaded function set, because the
1753 // expression is ill-formed if it actually works out to be a
1754 // non-static member function:
1755 //
1756 // C++ [expr.ref]p4:
1757 // Otherwise, if E1.E2 refers to a non-static member function. . .
1758 // [t]he expression can be used only as the left-hand operand of a
1759 // member function call.
1760 //
1761 // There are other safeguards against such uses, but it's important
1762 // to get this right here so that we don't end up making a
1763 // spuriously dependent expression if we're inside a dependent
1764 // instance method.
John McCall57500772009-12-16 12:17:52 +00001765 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001766 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00001767 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00001768 MightBeImplicitMember = true;
1769 else if (!SS.isEmpty())
1770 MightBeImplicitMember = false;
1771 else if (R.isOverloadedResult())
1772 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001773 else if (R.isUnresolvableResult())
1774 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001775 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001776 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1777 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001778
1779 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001780 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001781 }
1782
John McCalle66edc12009-11-24 19:00:30 +00001783 if (TemplateArgs)
1784 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001785
John McCalle66edc12009-11-24 19:00:30 +00001786 return BuildDeclarationNameExpr(SS, R, ADL);
1787}
1788
John McCall10eae182009-11-30 22:42:35 +00001789/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1790/// declaration name, generally during template instantiation.
1791/// There's a large number of things which don't need to be done along
1792/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001793ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001794Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001795 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001796 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001797 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001798 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001799
John McCall0b66eb32010-05-01 00:40:08 +00001800 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001801 return ExprError();
1802
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001803 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001804 LookupQualifiedName(R, DC);
1805
1806 if (R.isAmbiguous())
1807 return ExprError();
1808
1809 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001810 Diag(NameInfo.getLoc(), diag::err_no_member)
1811 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001812 return ExprError();
1813 }
1814
1815 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1816}
1817
1818/// LookupInObjCMethod - The parser has read a name in, and Sema has
1819/// detected that we're currently inside an ObjC method. Perform some
1820/// additional lookup.
1821///
1822/// Ideally, most of this would be done by lookup, but there's
1823/// actually quite a lot of extra work involved.
1824///
1825/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001826ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001827Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001828 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001829 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001830 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001831
John McCalle66edc12009-11-24 19:00:30 +00001832 // There are two cases to handle here. 1) scoped lookup could have failed,
1833 // in which case we should look for an ivar. 2) scoped lookup could have
1834 // found a decl, but that decl is outside the current instance method (i.e.
1835 // a global variable). In these two cases, we do a lookup for an ivar with
1836 // this name, if the lookup sucedes, we replace it our current decl.
1837
1838 // If we're in a class method, we don't normally want to look for
1839 // ivars. But if we don't find anything else, and there's an
1840 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001841 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001842
1843 bool LookForIvars;
1844 if (Lookup.empty())
1845 LookForIvars = true;
1846 else if (IsClassMethod)
1847 LookForIvars = false;
1848 else
1849 LookForIvars = (Lookup.isSingleResult() &&
1850 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001851 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001852 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001853 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001854 ObjCInterfaceDecl *ClassDeclared;
1855 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1856 // Diagnose using an ivar in a class method.
1857 if (IsClassMethod)
1858 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1859 << IV->getDeclName());
1860
1861 // If we're referencing an invalid decl, just return this as a silent
1862 // error node. The error diagnostic was already emitted on the decl.
1863 if (IV->isInvalidDecl())
1864 return ExprError();
1865
1866 // Check if referencing a field with __attribute__((deprecated)).
1867 if (DiagnoseUseOfDecl(IV, Loc))
1868 return ExprError();
1869
1870 // Diagnose the use of an ivar outside of the declaring class.
1871 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1872 ClassDeclared != IFace)
1873 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1874
1875 // FIXME: This should use a new expr for a direct reference, don't
1876 // turn this into Self->ivar, just return a BareIVarExpr or something.
1877 IdentifierInfo &II = Context.Idents.get("self");
1878 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001879 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001880 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001881 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001882 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001883 SelfName, false, false);
1884 if (SelfExpr.isInvalid())
1885 return ExprError();
1886
John Wiegley01296292011-04-08 18:41:53 +00001887 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1888 if (SelfExpr.isInvalid())
1889 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001890
John McCalle66edc12009-11-24 19:00:30 +00001891 MarkDeclarationReferenced(Loc, IV);
1892 return Owned(new (Context)
1893 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001894 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001895 }
Chris Lattner87313662010-04-12 05:10:17 +00001896 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001897 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001898 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001899 ObjCInterfaceDecl *ClassDeclared;
1900 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1901 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1902 IFace == ClassDeclared)
1903 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1904 }
1905 }
1906
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001907 if (Lookup.empty() && II && AllowBuiltinCreation) {
1908 // FIXME. Consolidate this with similar code in LookupName.
1909 if (unsigned BuiltinID = II->getBuiltinID()) {
1910 if (!(getLangOptions().CPlusPlus &&
1911 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1912 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1913 S, Lookup.isForRedeclaration(),
1914 Lookup.getNameLoc());
1915 if (D) Lookup.addDecl(D);
1916 }
1917 }
1918 }
John McCalle66edc12009-11-24 19:00:30 +00001919 // Sentinel value saying that we didn't do anything special.
1920 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001921}
John McCalld14a8642009-11-21 08:51:07 +00001922
John McCall16df1e52010-03-30 21:47:33 +00001923/// \brief Cast a base object to a member's actual type.
1924///
1925/// Logically this happens in three phases:
1926///
1927/// * First we cast from the base type to the naming class.
1928/// The naming class is the class into which we were looking
1929/// when we found the member; it's the qualifier type if a
1930/// qualifier was provided, and otherwise it's the base type.
1931///
1932/// * Next we cast from the naming class to the declaring class.
1933/// If the member we found was brought into a class's scope by
1934/// a using declaration, this is that class; otherwise it's
1935/// the class declaring the member.
1936///
1937/// * Finally we cast from the declaring class to the "true"
1938/// declaring class of the member. This conversion does not
1939/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001940ExprResult
1941Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001942 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001943 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001944 NamedDecl *Member) {
1945 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1946 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001947 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001948
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001949 QualType DestRecordType;
1950 QualType DestType;
1951 QualType FromRecordType;
1952 QualType FromType = From->getType();
1953 bool PointerConversions = false;
1954 if (isa<FieldDecl>(Member)) {
1955 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001956
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001957 if (FromType->getAs<PointerType>()) {
1958 DestType = Context.getPointerType(DestRecordType);
1959 FromRecordType = FromType->getPointeeType();
1960 PointerConversions = true;
1961 } else {
1962 DestType = DestRecordType;
1963 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001964 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001965 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1966 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00001967 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001968
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001969 DestType = Method->getThisType(Context);
1970 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001971
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001972 if (FromType->getAs<PointerType>()) {
1973 FromRecordType = FromType->getPointeeType();
1974 PointerConversions = true;
1975 } else {
1976 FromRecordType = FromType;
1977 DestType = DestRecordType;
1978 }
1979 } else {
1980 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00001981 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001982 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001983
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001984 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00001985 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001986
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001987 // If the unqualified types are the same, no conversion is necessary.
1988 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00001989 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001990
John McCall16df1e52010-03-30 21:47:33 +00001991 SourceRange FromRange = From->getSourceRange();
1992 SourceLocation FromLoc = FromRange.getBegin();
1993
Eli Friedmanbe4b3632011-09-27 21:58:52 +00001994 ExprValueKind VK = From->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001995
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001996 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001997 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001998 // class name.
1999 //
2000 // If the member was a qualified name and the qualified referred to a
2001 // specific base subobject type, we'll cast to that intermediate type
2002 // first and then to the object in which the member is declared. That allows
2003 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2004 //
2005 // class Base { public: int x; };
2006 // class Derived1 : public Base { };
2007 // class Derived2 : public Base { };
2008 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2009 //
2010 // void VeryDerived::f() {
2011 // x = 17; // error: ambiguous base subobjects
2012 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2013 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002014 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002015 QualType QType = QualType(Qualifier->getAsType(), 0);
2016 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2017 assert(QType->isRecordType() && "lookup done with non-record type");
2018
2019 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2020
2021 // In C++98, the qualifier type doesn't actually have to be a base
2022 // type of the object type, in which case we just ignore it.
2023 // Otherwise build the appropriate casts.
2024 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002025 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002026 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002027 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002028 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002029
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002030 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002031 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002032 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2033 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002034
2035 FromType = QType;
2036 FromRecordType = QRecordType;
2037
2038 // If the qualifier type was the same as the destination type,
2039 // we're done.
2040 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002041 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002042 }
2043 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002044
John McCall16df1e52010-03-30 21:47:33 +00002045 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002046
John McCall16df1e52010-03-30 21:47:33 +00002047 // If we actually found the member through a using declaration, cast
2048 // down to the using declaration's type.
2049 //
2050 // Pointer equality is fine here because only one declaration of a
2051 // class ever has member declarations.
2052 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2053 assert(isa<UsingShadowDecl>(FoundDecl));
2054 QualType URecordType = Context.getTypeDeclType(
2055 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2056
2057 // We only need to do this if the naming-class to declaring-class
2058 // conversion is non-trivial.
2059 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2060 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002061 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002062 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002063 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002064 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002065
John McCall16df1e52010-03-30 21:47:33 +00002066 QualType UType = URecordType;
2067 if (PointerConversions)
2068 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002069 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2070 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002071 FromType = UType;
2072 FromRecordType = URecordType;
2073 }
2074
2075 // We don't do access control for the conversion from the
2076 // declaring class to the true declaring class.
2077 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002078 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002079
John McCallcf142162010-08-07 06:22:56 +00002080 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002081 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2082 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002083 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002084 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002085
John Wiegley01296292011-04-08 18:41:53 +00002086 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2087 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002088}
Douglas Gregor3256d042009-06-30 15:47:41 +00002089
John McCalle66edc12009-11-24 19:00:30 +00002090bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002091 const LookupResult &R,
2092 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002093 // Only when used directly as the postfix-expression of a call.
2094 if (!HasTrailingLParen)
2095 return false;
2096
2097 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002098 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002099 return false;
2100
2101 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002102 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002103 return false;
2104
2105 // Turn off ADL when we find certain kinds of declarations during
2106 // normal lookup:
2107 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2108 NamedDecl *D = *I;
2109
2110 // C++0x [basic.lookup.argdep]p3:
2111 // -- a declaration of a class member
2112 // Since using decls preserve this property, we check this on the
2113 // original decl.
John McCall57500772009-12-16 12:17:52 +00002114 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002115 return false;
2116
2117 // C++0x [basic.lookup.argdep]p3:
2118 // -- a block-scope function declaration that is not a
2119 // using-declaration
2120 // NOTE: we also trigger this for function templates (in fact, we
2121 // don't check the decl type at all, since all other decl types
2122 // turn off ADL anyway).
2123 if (isa<UsingShadowDecl>(D))
2124 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2125 else if (D->getDeclContext()->isFunctionOrMethod())
2126 return false;
2127
2128 // C++0x [basic.lookup.argdep]p3:
2129 // -- a declaration that is neither a function or a function
2130 // template
2131 // And also for builtin functions.
2132 if (isa<FunctionDecl>(D)) {
2133 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2134
2135 // But also builtin functions.
2136 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2137 return false;
2138 } else if (!isa<FunctionTemplateDecl>(D))
2139 return false;
2140 }
2141
2142 return true;
2143}
2144
2145
John McCalld14a8642009-11-21 08:51:07 +00002146/// Diagnoses obvious problems with the use of the given declaration
2147/// as an expression. This is only actually called for lookups that
2148/// were not overloaded, and it doesn't promise that the declaration
2149/// will in fact be used.
2150static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002151 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002152 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2153 return true;
2154 }
2155
2156 if (isa<ObjCInterfaceDecl>(D)) {
2157 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2158 return true;
2159 }
2160
2161 if (isa<NamespaceDecl>(D)) {
2162 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2163 return true;
2164 }
2165
2166 return false;
2167}
2168
John McCalldadc5752010-08-24 06:29:42 +00002169ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002170Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002171 LookupResult &R,
2172 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002173 // If this is a single, fully-resolved result and we don't need ADL,
2174 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002175 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002176 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2177 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002178
2179 // We only need to check the declaration if there's exactly one
2180 // result, because in the overloaded case the results can only be
2181 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002182 if (R.isSingleResult() &&
2183 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002184 return ExprError();
2185
John McCall58cc69d2010-01-27 01:50:18 +00002186 // Otherwise, just build an unresolved lookup expression. Suppress
2187 // any lookup-related diagnostics; we'll hash these out later, when
2188 // we've picked a target.
2189 R.suppressDiagnostics();
2190
John McCalld14a8642009-11-21 08:51:07 +00002191 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002192 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002193 SS.getWithLocInContext(Context),
2194 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002195 NeedsADL, R.isOverloadedResult(),
2196 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002197
2198 return Owned(ULE);
2199}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002200
John McCalld14a8642009-11-21 08:51:07 +00002201/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002202ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002203Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002204 const DeclarationNameInfo &NameInfo,
2205 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002206 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002207 assert(!isa<FunctionTemplateDecl>(D) &&
2208 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002209
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002210 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002211 if (CheckDeclInExpr(*this, Loc, D))
2212 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002213
Douglas Gregore7488b92009-12-01 16:58:18 +00002214 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2215 // Specifically diagnose references to class templates that are missing
2216 // a template argument list.
2217 Diag(Loc, diag::err_template_decl_ref)
2218 << Template << SS.getRange();
2219 Diag(Template->getLocation(), diag::note_template_decl_here);
2220 return ExprError();
2221 }
2222
2223 // Make sure that we're referring to a value.
2224 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2225 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002226 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002227 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002228 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002229 return ExprError();
2230 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002231
Douglas Gregor171c45a2009-02-18 21:56:37 +00002232 // Check whether this declaration can be used. Note that we suppress
2233 // this check when we're going to perform argument-dependent lookup
2234 // on this function name, because this might not be the function
2235 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002236 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002237 return ExprError();
2238
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002239 // Only create DeclRefExpr's for valid Decl's.
2240 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002241 return ExprError();
2242
John McCallf3a88602011-02-03 08:15:49 +00002243 // Handle members of anonymous structs and unions. If we got here,
2244 // and the reference is to a class member indirect field, then this
2245 // must be the subject of a pointer-to-member expression.
2246 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2247 if (!indirectField->isCXXClassMember())
2248 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2249 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002250
Chris Lattner2a9d9892008-10-20 05:16:36 +00002251 // If the identifier reference is inside a block, and it refers to a value
2252 // that is outside the block, create a BlockDeclRefExpr instead of a
2253 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2254 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002255 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002256 // We do not do this for things like enum constants, global variables, etc,
2257 // as they do not get snapshotted.
2258 //
John McCall351762c2011-02-07 10:33:21 +00002259 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002260 case CR_Error:
2261 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002262
John McCallc63de662011-02-02 13:00:07 +00002263 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002264 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2265 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2266
2267 case CR_CaptureByRef:
2268 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2269 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002270
2271 case CR_NoCapture: {
2272 // If this reference is not in a block or if the referenced
2273 // variable is within the block, create a normal DeclRefExpr.
2274
2275 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002276 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002277
2278 switch (D->getKind()) {
2279 // Ignore all the non-ValueDecl kinds.
2280#define ABSTRACT_DECL(kind)
2281#define VALUE(type, base)
2282#define DECL(type, base) \
2283 case Decl::type:
2284#include "clang/AST/DeclNodes.inc"
2285 llvm_unreachable("invalid value decl kind");
2286 return ExprError();
2287
2288 // These shouldn't make it here.
2289 case Decl::ObjCAtDefsField:
2290 case Decl::ObjCIvar:
2291 llvm_unreachable("forming non-member reference to ivar?");
2292 return ExprError();
2293
2294 // Enum constants are always r-values and never references.
2295 // Unresolved using declarations are dependent.
2296 case Decl::EnumConstant:
2297 case Decl::UnresolvedUsingValue:
2298 valueKind = VK_RValue;
2299 break;
2300
2301 // Fields and indirect fields that got here must be for
2302 // pointer-to-member expressions; we just call them l-values for
2303 // internal consistency, because this subexpression doesn't really
2304 // exist in the high-level semantics.
2305 case Decl::Field:
2306 case Decl::IndirectField:
2307 assert(getLangOptions().CPlusPlus &&
2308 "building reference to field in C?");
2309
2310 // These can't have reference type in well-formed programs, but
2311 // for internal consistency we do this anyway.
2312 type = type.getNonReferenceType();
2313 valueKind = VK_LValue;
2314 break;
2315
2316 // Non-type template parameters are either l-values or r-values
2317 // depending on the type.
2318 case Decl::NonTypeTemplateParm: {
2319 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2320 type = reftype->getPointeeType();
2321 valueKind = VK_LValue; // even if the parameter is an r-value reference
2322 break;
2323 }
2324
2325 // For non-references, we need to strip qualifiers just in case
2326 // the template parameter was declared as 'const int' or whatever.
2327 valueKind = VK_RValue;
2328 type = type.getUnqualifiedType();
2329 break;
2330 }
2331
2332 case Decl::Var:
2333 // In C, "extern void blah;" is valid and is an r-value.
2334 if (!getLangOptions().CPlusPlus &&
2335 !type.hasQualifiers() &&
2336 type->isVoidType()) {
2337 valueKind = VK_RValue;
2338 break;
2339 }
2340 // fallthrough
2341
2342 case Decl::ImplicitParam:
2343 case Decl::ParmVar:
2344 // These are always l-values.
2345 valueKind = VK_LValue;
2346 type = type.getNonReferenceType();
2347 break;
2348
2349 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002350 const FunctionType *fty = type->castAs<FunctionType>();
2351
2352 // If we're referring to a function with an __unknown_anytype
2353 // result type, make the entire expression __unknown_anytype.
2354 if (fty->getResultType() == Context.UnknownAnyTy) {
2355 type = Context.UnknownAnyTy;
2356 valueKind = VK_RValue;
2357 break;
2358 }
2359
John McCallf4cd4f92011-02-09 01:13:10 +00002360 // Functions are l-values in C++.
2361 if (getLangOptions().CPlusPlus) {
2362 valueKind = VK_LValue;
2363 break;
2364 }
2365
2366 // C99 DR 316 says that, if a function type comes from a
2367 // function definition (without a prototype), that type is only
2368 // used for checking compatibility. Therefore, when referencing
2369 // the function, we pretend that we don't have the full function
2370 // type.
John McCall2979fe02011-04-12 00:42:48 +00002371 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2372 isa<FunctionProtoType>(fty))
2373 type = Context.getFunctionNoProtoType(fty->getResultType(),
2374 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002375
2376 // Functions are r-values in C.
2377 valueKind = VK_RValue;
2378 break;
2379 }
2380
2381 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002382 // If we're referring to a method with an __unknown_anytype
2383 // result type, make the entire expression __unknown_anytype.
2384 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002385 if (const FunctionProtoType *proto
2386 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002387 if (proto->getResultType() == Context.UnknownAnyTy) {
2388 type = Context.UnknownAnyTy;
2389 valueKind = VK_RValue;
2390 break;
2391 }
2392
John McCallf4cd4f92011-02-09 01:13:10 +00002393 // C++ methods are l-values if static, r-values if non-static.
2394 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2395 valueKind = VK_LValue;
2396 break;
2397 }
2398 // fallthrough
2399
2400 case Decl::CXXConversion:
2401 case Decl::CXXDestructor:
2402 case Decl::CXXConstructor:
2403 valueKind = VK_RValue;
2404 break;
2405 }
2406
2407 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2408 }
2409
John McCallc63de662011-02-02 13:00:07 +00002410 }
John McCall7decc9e2010-11-18 06:31:45 +00002411
John McCall351762c2011-02-07 10:33:21 +00002412 llvm_unreachable("unknown capture result");
2413 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002414}
Chris Lattnere168f762006-11-10 05:29:30 +00002415
John McCall2979fe02011-04-12 00:42:48 +00002416ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002417 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002418
Chris Lattnere168f762006-11-10 05:29:30 +00002419 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002420 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002421 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2422 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2423 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002424 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002425
Chris Lattnera81a0272008-01-12 08:14:25 +00002426 // Pre-defined identifiers are of type char[x], where x is the length of the
2427 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002428
Anders Carlsson2fb08242009-09-08 18:24:21 +00002429 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002430 if (!currentDecl && getCurBlock())
2431 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002432 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002433 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002434 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002435 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002436
Anders Carlsson0b209a82009-09-11 01:22:35 +00002437 QualType ResTy;
2438 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2439 ResTy = Context.DependentTy;
2440 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002441 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002442
Anders Carlsson0b209a82009-09-11 01:22:35 +00002443 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002444 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002445 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2446 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002447 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002448}
2449
John McCalldadc5752010-08-24 06:29:42 +00002450ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002451 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002452 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002453 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002454 if (Invalid)
2455 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002456
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002457 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002458 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002459 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002460 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002461
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002462 QualType Ty;
2463 if (!getLangOptions().CPlusPlus)
2464 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2465 else if (Literal.isWide())
2466 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002467 else if (Literal.isUTF16())
2468 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2469 else if (Literal.isUTF32())
2470 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002471 else if (Literal.isMultiChar())
2472 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002473 else
2474 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002475
Douglas Gregorfb65e592011-07-27 05:40:30 +00002476 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2477 if (Literal.isWide())
2478 Kind = CharacterLiteral::Wide;
2479 else if (Literal.isUTF16())
2480 Kind = CharacterLiteral::UTF16;
2481 else if (Literal.isUTF32())
2482 Kind = CharacterLiteral::UTF32;
2483
2484 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2485 Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002486}
2487
John McCalldadc5752010-08-24 06:29:42 +00002488ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002489 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002490 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2491 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002492 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Douglas Gregore8bbc122011-09-02 00:18:52 +00002493 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002494 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002495 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002496 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002497
Chris Lattner23b7eb62007-06-15 23:05:46 +00002498 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002499 // Add padding so that NumericLiteralParser can overread by one character.
2500 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002501 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002502
Chris Lattner67ca9252007-05-21 01:08:44 +00002503 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002504 bool Invalid = false;
2505 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2506 if (Invalid)
2507 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002508
Mike Stump11289f42009-09-09 15:08:12 +00002509 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002510 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002511 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002512 return ExprError();
2513
Chris Lattner1c20a172007-08-26 03:42:43 +00002514 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002515
Chris Lattner1c20a172007-08-26 03:42:43 +00002516 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002517 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002518 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002519 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002520 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002521 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002522 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002523 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002524
2525 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2526
John McCall53b93a02009-12-24 09:08:04 +00002527 using llvm::APFloat;
2528 APFloat Val(Format);
2529
2530 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002531
2532 // Overflow is always an error, but underflow is only an error if
2533 // we underflowed to zero (APFloat reports denormals as underflow).
2534 if ((result & APFloat::opOverflow) ||
2535 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002536 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002537 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002538 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002539 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002540 APFloat::getLargest(Format).toString(buffer);
2541 } else {
John McCall62abc942010-02-26 23:35:57 +00002542 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002543 APFloat::getSmallest(Format).toString(buffer);
2544 }
2545
2546 Diag(Tok.getLocation(), diagnostic)
2547 << Ty
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002548 << StringRef(buffer.data(), buffer.size());
John McCall53b93a02009-12-24 09:08:04 +00002549 }
2550
2551 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002552 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002553
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002554 if (Ty == Context.DoubleTy) {
2555 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002556 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002557 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2558 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002559 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002560 }
2561 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002562 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002563 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002564 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002565 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002566
Neil Boothac582c52007-08-29 22:00:19 +00002567 // long long is a C99 feature.
2568 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002569 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002570 Diag(Tok.getLocation(), diag::ext_longlong);
2571
Chris Lattner67ca9252007-05-21 01:08:44 +00002572 // Get the value in the widest-possible width.
Douglas Gregore8bbc122011-09-02 00:18:52 +00002573 llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002574
Chris Lattner67ca9252007-05-21 01:08:44 +00002575 if (Literal.GetIntegerValue(ResultVal)) {
2576 // If this value didn't fit into uintmax_t, warn and force to ull.
2577 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002578 Ty = Context.UnsignedLongLongTy;
2579 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002580 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002581 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002582 // If this value fits into a ULL, try to figure out what else it fits into
2583 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002584
Chris Lattner67ca9252007-05-21 01:08:44 +00002585 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2586 // be an unsigned int.
2587 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2588
2589 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002590 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002591 if (!Literal.isLong && !Literal.isLongLong) {
2592 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00002593 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002594
Chris Lattner67ca9252007-05-21 01:08:44 +00002595 // Does it fit in a unsigned int?
2596 if (ResultVal.isIntN(IntSize)) {
2597 // Does it fit in a signed int?
2598 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002599 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002600 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002601 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002602 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002603 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002604 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002605
Chris Lattner67ca9252007-05-21 01:08:44 +00002606 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002607 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002608 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002609
Chris Lattner67ca9252007-05-21 01:08:44 +00002610 // Does it fit in a unsigned long?
2611 if (ResultVal.isIntN(LongSize)) {
2612 // Does it fit in a signed long?
2613 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002614 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002615 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002616 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002617 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002618 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002619 }
2620
Chris Lattner67ca9252007-05-21 01:08:44 +00002621 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002622 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002623 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002624
Chris Lattner67ca9252007-05-21 01:08:44 +00002625 // Does it fit in a unsigned long long?
2626 if (ResultVal.isIntN(LongLongSize)) {
2627 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002628 // To be compatible with MSVC, hex integer literals ending with the
2629 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002630 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
Francois Pichet0706d202011-09-17 17:15:52 +00002631 (getLangOptions().MicrosoftExt && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002632 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002633 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002634 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002635 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002636 }
2637 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002638
Chris Lattner67ca9252007-05-21 01:08:44 +00002639 // If we still couldn't decide a type, we probably have something that
2640 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002641 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002642 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002643 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00002644 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002645 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002646
Chris Lattner55258cf2008-05-09 05:59:00 +00002647 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002648 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002649 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002650 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002651 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002652
Chris Lattner1c20a172007-08-26 03:42:43 +00002653 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2654 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002655 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002656 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002657
2658 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002659}
2660
Richard Trieuba63ce62011-09-09 01:45:06 +00002661ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002662 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002663 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002664}
2665
Chandler Carruth62da79c2011-05-26 08:53:12 +00002666static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2667 SourceLocation Loc,
2668 SourceRange ArgRange) {
2669 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2670 // scalar or vector data type argument..."
2671 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2672 // type (C99 6.2.5p18) or void.
2673 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2674 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2675 << T << ArgRange;
2676 return true;
2677 }
2678
2679 assert((T->isVoidType() || !T->isIncompleteType()) &&
2680 "Scalar types should always be complete");
2681 return false;
2682}
2683
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002684static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2685 SourceLocation Loc,
2686 SourceRange ArgRange,
2687 UnaryExprOrTypeTrait TraitKind) {
2688 // C99 6.5.3.4p1:
2689 if (T->isFunctionType()) {
2690 // alignof(function) is allowed as an extension.
2691 if (TraitKind == UETT_SizeOf)
2692 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2693 return false;
2694 }
2695
2696 // Allow sizeof(void)/alignof(void) as an extension.
2697 if (T->isVoidType()) {
2698 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2699 return false;
2700 }
2701
2702 return true;
2703}
2704
2705static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2706 SourceLocation Loc,
2707 SourceRange ArgRange,
2708 UnaryExprOrTypeTrait TraitKind) {
2709 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2710 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2711 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2712 << T << (TraitKind == UETT_SizeOf)
2713 << ArgRange;
2714 return true;
2715 }
2716
2717 return false;
2718}
2719
Chandler Carruth14502c22011-05-26 08:53:10 +00002720/// \brief Check the constrains on expression operands to unary type expression
2721/// and type traits.
2722///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002723/// Completes any types necessary and validates the constraints on the operand
2724/// expression. The logic mostly mirrors the type-based overload, but may modify
2725/// the expression as it completes the type for that expression through template
2726/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00002727bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00002728 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002729 QualType ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002730
2731 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2732 // the result is the size of the referenced type."
2733 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2734 // result shall be the alignment of the referenced type."
2735 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2736 ExprTy = Ref->getPointeeType();
2737
2738 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002739 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2740 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00002741
2742 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002743 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2744 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002745 return false;
2746
Richard Trieuba63ce62011-09-09 01:45:06 +00002747 if (RequireCompleteExprType(E,
Chandler Carruth7c430c02011-05-27 01:33:31 +00002748 PDiag(diag::err_sizeof_alignof_incomplete_type)
Richard Trieuba63ce62011-09-09 01:45:06 +00002749 << ExprKind << E->getSourceRange(),
Chandler Carruth7c430c02011-05-27 01:33:31 +00002750 std::make_pair(SourceLocation(), PDiag(0))))
2751 return true;
2752
2753 // Completeing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00002754 ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002755 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2756 ExprTy = Ref->getPointeeType();
2757
Richard Trieuba63ce62011-09-09 01:45:06 +00002758 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2759 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002760 return true;
2761
Nico Weber0870deb2011-06-15 02:47:03 +00002762 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002763 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00002764 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2765 QualType OType = PVD->getOriginalType();
2766 QualType Type = PVD->getType();
2767 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002768 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00002769 << Type << OType;
2770 Diag(PVD->getLocation(), diag::note_declared_at);
2771 }
2772 }
2773 }
2774 }
2775
Chandler Carruth7c430c02011-05-27 01:33:31 +00002776 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002777}
2778
2779/// \brief Check the constraints on operands to unary expression and type
2780/// traits.
2781///
2782/// This will complete any types necessary, and validate the various constraints
2783/// on those operands.
2784///
Steve Naroff71b59a92007-06-04 22:22:31 +00002785/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002786/// C99 6.3.2.1p[2-4] all state:
2787/// Except when it is the operand of the sizeof operator ...
2788///
2789/// C++ [expr.sizeof]p4
2790/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2791/// standard conversions are not applied to the operand of sizeof.
2792///
2793/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00002794bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00002795 SourceLocation OpLoc,
2796 SourceRange ExprRange,
2797 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002798 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002799 return false;
2800
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002801 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2802 // the result is the size of the referenced type."
2803 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2804 // result shall be the alignment of the referenced type."
Richard Trieuba63ce62011-09-09 01:45:06 +00002805 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
2806 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002807
Chandler Carruth62da79c2011-05-26 08:53:12 +00002808 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002809 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002810
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002811 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002812 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002813 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00002814 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002815
Richard Trieuba63ce62011-09-09 01:45:06 +00002816 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002817 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002818 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002819 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002820
Richard Trieuba63ce62011-09-09 01:45:06 +00002821 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002822 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002823 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002824
Chris Lattner62975a72009-04-24 00:30:45 +00002825 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002826}
2827
Chandler Carruth14502c22011-05-26 08:53:10 +00002828static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002829 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002830
Mike Stump11289f42009-09-09 15:08:12 +00002831 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002832 if (isa<DeclRefExpr>(E))
2833 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002834
2835 // Cannot know anything else if the expression is dependent.
2836 if (E->isTypeDependent())
2837 return false;
2838
Douglas Gregor71235ec2009-05-02 02:18:30 +00002839 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002840 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2841 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00002842 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002843 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002844
2845 // Alignment of a field access is always okay, so long as it isn't a
2846 // bit-field.
2847 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002848 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002849 return false;
2850
Chandler Carruth14502c22011-05-26 08:53:10 +00002851 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002852}
2853
Chandler Carruth14502c22011-05-26 08:53:10 +00002854bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002855 E = E->IgnoreParens();
2856
2857 // Cannot know anything else if the expression is dependent.
2858 if (E->isTypeDependent())
2859 return false;
2860
Chandler Carruth14502c22011-05-26 08:53:10 +00002861 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002862}
2863
Douglas Gregor0950e412009-03-13 21:01:28 +00002864/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002865ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002866Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2867 SourceLocation OpLoc,
2868 UnaryExprOrTypeTrait ExprKind,
2869 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002870 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002871 return ExprError();
2872
John McCallbcd03502009-12-07 02:54:59 +00002873 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002874
Douglas Gregor0950e412009-03-13 21:01:28 +00002875 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002876 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002877 return ExprError();
2878
2879 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002880 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2881 Context.getSizeType(),
2882 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002883}
2884
2885/// \brief Build a sizeof or alignof expression given an expression
2886/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002887ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00002888Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2889 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00002890 ExprResult PE = CheckPlaceholderExpr(E);
2891 if (PE.isInvalid())
2892 return ExprError();
2893
2894 E = PE.get();
2895
Douglas Gregor0950e412009-03-13 21:01:28 +00002896 // Verify that the operand is valid.
2897 bool isInvalid = false;
2898 if (E->isTypeDependent()) {
2899 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002900 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002901 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002902 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002903 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002904 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00002905 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00002906 isInvalid = true;
2907 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00002908 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002909 }
2910
2911 if (isInvalid)
2912 return ExprError();
2913
2914 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00002915 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00002916 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00002917 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002918}
2919
Peter Collingbournee190dee2011-03-11 19:24:49 +00002920/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2921/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00002922/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002923ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002924Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00002925 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00002926 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002927 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002928 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002929
Richard Trieuba63ce62011-09-09 01:45:06 +00002930 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00002931 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002932 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002933 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002934 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002935
Douglas Gregor0950e412009-03-13 21:01:28 +00002936 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00002937 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00002938 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002939}
2940
John Wiegley01296292011-04-08 18:41:53 +00002941static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00002942 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00002943 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002944 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002945
John McCall34376a62010-12-04 03:47:34 +00002946 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00002947 if (V.get()->getObjectKind() != OK_Ordinary) {
2948 V = S.DefaultLvalueConversion(V.take());
2949 if (V.isInvalid())
2950 return QualType();
2951 }
John McCall34376a62010-12-04 03:47:34 +00002952
Chris Lattnere267f5d2007-08-26 05:39:26 +00002953 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00002954 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002955 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002956
Chris Lattnere267f5d2007-08-26 05:39:26 +00002957 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00002958 if (V.get()->getType()->isArithmeticType())
2959 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002960
John McCall36226622010-10-12 02:09:17 +00002961 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00002962 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00002963 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00002964 if (PR.get() != V.get()) {
2965 V = move(PR);
Richard Trieuba63ce62011-09-09 01:45:06 +00002966 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00002967 }
2968
Chris Lattnere267f5d2007-08-26 05:39:26 +00002969 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00002970 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00002971 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002972 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002973}
2974
2975
Chris Lattnere168f762006-11-10 05:29:30 +00002976
John McCalldadc5752010-08-24 06:29:42 +00002977ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002978Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002979 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002980 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002981 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002982 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002983 case tok::plusplus: Opc = UO_PostInc; break;
2984 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002985 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002986
John McCallb268a282010-08-23 23:25:46 +00002987 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002988}
2989
John McCalldadc5752010-08-24 06:29:42 +00002990ExprResult
John McCallb268a282010-08-23 23:25:46 +00002991Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2992 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002993 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002994 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002995 if (Result.isInvalid()) return ExprError();
2996 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002997
John McCallb268a282010-08-23 23:25:46 +00002998 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002999
Douglas Gregor40412ac2008-11-19 17:17:41 +00003000 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003001 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003002 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003003 Context.DependentTy,
3004 VK_LValue, OK_Ordinary,
3005 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003006 }
3007
Mike Stump11289f42009-09-09 15:08:12 +00003008 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003009 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003010 LHSExp->getType()->isEnumeralType() ||
3011 RHSExp->getType()->isRecordType() ||
3012 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00003013 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003014 }
3015
John McCallb268a282010-08-23 23:25:46 +00003016 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003017}
3018
3019
John McCalldadc5752010-08-24 06:29:42 +00003020ExprResult
John McCallb268a282010-08-23 23:25:46 +00003021Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003022 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00003023 Expr *LHSExp = Base;
3024 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003025
Chris Lattner36d572b2007-07-16 00:14:47 +00003026 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003027 if (!LHSExp->getType()->getAs<VectorType>()) {
3028 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3029 if (Result.isInvalid())
3030 return ExprError();
3031 LHSExp = Result.take();
3032 }
3033 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3034 if (Result.isInvalid())
3035 return ExprError();
3036 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003037
Chris Lattner36d572b2007-07-16 00:14:47 +00003038 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003039 ExprValueKind VK = VK_LValue;
3040 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003041
Steve Naroffc1aadb12007-03-28 21:49:40 +00003042 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003043 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003044 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003045 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003046 Expr *BaseExpr, *IndexExpr;
3047 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003048 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3049 BaseExpr = LHSExp;
3050 IndexExpr = RHSExp;
3051 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003052 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003053 BaseExpr = LHSExp;
3054 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003055 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003056 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003057 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003058 BaseExpr = RHSExp;
3059 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003060 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003061 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003062 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003063 BaseExpr = LHSExp;
3064 IndexExpr = RHSExp;
3065 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003066 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003067 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003068 // Handle the uncommon case of "123[Ptr]".
3069 BaseExpr = RHSExp;
3070 IndexExpr = LHSExp;
3071 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003072 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003073 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003074 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003075 VK = LHSExp->getValueKind();
3076 if (VK != VK_RValue)
3077 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003078
Chris Lattner36d572b2007-07-16 00:14:47 +00003079 // FIXME: need to deal with const...
3080 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003081 } else if (LHSTy->isArrayType()) {
3082 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003083 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003084 // wasn't promoted because of the C90 rule that doesn't
3085 // allow promoting non-lvalue arrays. Warn, then
3086 // force the promotion here.
3087 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3088 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003089 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3090 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003091 LHSTy = LHSExp->getType();
3092
3093 BaseExpr = LHSExp;
3094 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003095 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003096 } else if (RHSTy->isArrayType()) {
3097 // Same as previous, except for 123[f().a] case
3098 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3099 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003100 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3101 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003102 RHSTy = RHSExp->getType();
3103
3104 BaseExpr = RHSExp;
3105 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003106 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003107 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003108 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3109 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003110 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003111 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003112 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003113 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3114 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003115
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003116 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003117 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3118 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003119 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3120
Douglas Gregorac1fb652009-03-24 19:52:54 +00003121 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003122 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3123 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003124 // incomplete types are not object types.
3125 if (ResultType->isFunctionType()) {
3126 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3127 << ResultType << BaseExpr->getSourceRange();
3128 return ExprError();
3129 }
Mike Stump11289f42009-09-09 15:08:12 +00003130
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003131 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3132 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003133 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3134 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003135
3136 // C forbids expressions of unqualified void type from being l-values.
3137 // See IsCForbiddenLValueType.
3138 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003139 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003140 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003141 PDiag(diag::err_subscript_incomplete_type)
3142 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003143 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003144
Chris Lattner62975a72009-04-24 00:30:45 +00003145 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003146 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003147 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3148 << ResultType << BaseExpr->getSourceRange();
3149 return ExprError();
3150 }
Mike Stump11289f42009-09-09 15:08:12 +00003151
John McCall4bc41ae2010-11-18 19:01:18 +00003152 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003153 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003154
Mike Stump4e1f26a2009-02-19 03:04:26 +00003155 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003156 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003157}
3158
John McCalldadc5752010-08-24 06:29:42 +00003159ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003160 FunctionDecl *FD,
3161 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003162 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003163 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003164 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003165 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003166 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003167 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003168 return ExprError();
3169 }
3170
3171 if (Param->hasUninstantiatedDefaultArg()) {
3172 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003173
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003174 // Instantiate the expression.
3175 MultiLevelTemplateArgumentList ArgList
3176 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003177
Nico Weber44887f62010-11-29 18:19:25 +00003178 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003179 = ArgList.getInnermost();
3180 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3181 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003182
Nico Weber44887f62010-11-29 18:19:25 +00003183 ExprResult Result;
3184 {
3185 // C++ [dcl.fct.default]p5:
3186 // The names in the [default argument] expression are bound, and
3187 // the semantic constraints are checked, at the point where the
3188 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003189 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00003190 Result = SubstExpr(UninstExpr, ArgList);
3191 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003192 if (Result.isInvalid())
3193 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003194
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003195 // Check the expression as an initializer for the parameter.
3196 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003197 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003198 InitializationKind Kind
3199 = InitializationKind::CreateCopy(Param->getLocation(),
3200 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3201 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003202
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003203 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3204 Result = InitSeq.Perform(*this, Entity, Kind,
3205 MultiExprArg(*this, &ResultE, 1));
3206 if (Result.isInvalid())
3207 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003208
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003209 // Build the default argument expression.
3210 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3211 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003212 }
3213
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003214 // If the default expression creates temporaries, we need to
3215 // push them to the current stack of expression temporaries so they'll
3216 // be properly destroyed.
3217 // FIXME: We should really be rebuilding the default argument with new
3218 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003219 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3220 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3221 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3222 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3223 ExprTemporaries.push_back(Temporary);
John McCall31168b02011-06-15 23:02:42 +00003224 ExprNeedsCleanups = true;
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003225 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003226
3227 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003228 // Just mark all of the declarations in this potentially-evaluated expression
3229 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003230 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00003231 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003232}
3233
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003234/// ConvertArgumentsForCall - Converts the arguments specified in
3235/// Args/NumArgs to the parameter types of the function FDecl with
3236/// function prototype Proto. Call is the call expression itself, and
3237/// Fn is the function expression. For a C++ member function, this
3238/// routine does not attempt to convert the object argument. Returns
3239/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003240bool
3241Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003242 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003243 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003244 Expr **Args, unsigned NumArgs,
3245 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00003246 // Bail out early if calling a builtin with custom typechecking.
3247 // We don't need to do this in the
3248 if (FDecl)
3249 if (unsigned ID = FDecl->getBuiltinID())
3250 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3251 return false;
3252
Mike Stump4e1f26a2009-02-19 03:04:26 +00003253 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003254 // assignment, to the types of the corresponding parameter, ...
3255 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003256 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003257
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003258 // If too few arguments are available (and we don't have default
3259 // arguments for the remaining parameters), don't make the call.
3260 if (NumArgs < NumArgsInProto) {
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003261 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) {
3262 Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003263 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00003264 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003265
3266 // Emit the location of the prototype.
3267 if (FDecl && !FDecl->getBuiltinID())
3268 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3269 << FDecl;
3270
3271 return true;
3272 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003273 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003274 }
3275
3276 // If too many are passed and not variadic, error on the extras and drop
3277 // them.
3278 if (NumArgs > NumArgsInProto) {
3279 if (!Proto->isVariadic()) {
3280 Diag(Args[NumArgsInProto]->getLocStart(),
3281 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00003282 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003283 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003284 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3285 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003286
3287 // Emit the location of the prototype.
3288 if (FDecl && !FDecl->getBuiltinID())
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003289 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3290 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003291
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003292 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003293 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003294 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003295 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003296 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003297 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003298 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003299 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3300 if (Fn->getType()->isBlockPointerType())
3301 CallType = VariadicBlock; // Block
3302 else if (isa<MemberExpr>(Fn))
3303 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003304 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003305 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003306 if (Invalid)
3307 return true;
3308 unsigned TotalNumArgs = AllArgs.size();
3309 for (unsigned i = 0; i < TotalNumArgs; ++i)
3310 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003311
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003312 return false;
3313}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003314
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003315bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3316 FunctionDecl *FDecl,
3317 const FunctionProtoType *Proto,
3318 unsigned FirstProtoArg,
3319 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003320 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003321 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003322 unsigned NumArgsInProto = Proto->getNumArgs();
3323 unsigned NumArgsToCheck = NumArgs;
3324 bool Invalid = false;
3325 if (NumArgs != NumArgsInProto)
3326 // Use default arguments for missing arguments
3327 NumArgsToCheck = NumArgsInProto;
3328 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003329 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003330 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003331 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003332
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003333 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003334 if (ArgIx < NumArgs) {
3335 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003336
Eli Friedman3164fb12009-03-22 22:00:50 +00003337 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3338 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003339 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003340 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003341 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003342
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003343 // Pass the argument
3344 ParmVarDecl *Param = 0;
3345 if (FDecl && i < FDecl->getNumParams())
3346 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003347
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003348 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003349 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003350 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3351 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003352 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003353 SourceLocation(),
3354 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003355 if (ArgE.isInvalid())
3356 return true;
3357
3358 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003359 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003360 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003361
John McCalldadc5752010-08-24 06:29:42 +00003362 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003363 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003364 if (ArgExpr.isInvalid())
3365 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003366
Anders Carlsson355933d2009-08-25 03:49:14 +00003367 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003368 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003369
3370 // Check for array bounds violations for each argument to the call. This
3371 // check only triggers warnings when the argument isn't a more complex Expr
3372 // with its own checking, such as a BinaryOperator.
3373 CheckArrayAccess(Arg);
3374
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003375 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003376 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003377
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003378 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003379 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003380
3381 // Assume that extern "C" functions with variadic arguments that
3382 // return __unknown_anytype aren't *really* variadic.
3383 if (Proto->getResultType() == Context.UnknownAnyTy &&
3384 FDecl && FDecl->isExternC()) {
3385 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3386 ExprResult arg;
3387 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3388 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3389 else
3390 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3391 Invalid |= arg.isInvalid();
3392 AllArgs.push_back(arg.take());
3393 }
3394
3395 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3396 } else {
3397 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003398 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3399 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003400 Invalid |= Arg.isInvalid();
3401 AllArgs.push_back(Arg.take());
3402 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003403 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00003404
3405 // Check for array bounds violations.
3406 for (unsigned i = ArgIx; i != NumArgs; ++i)
3407 CheckArrayAccess(Args[i]);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003408 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003409 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003410}
3411
John McCall2979fe02011-04-12 00:42:48 +00003412/// Given a function expression of unknown-any type, try to rebuild it
3413/// to have a function type.
3414static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3415
Steve Naroff83895f72007-09-16 03:34:24 +00003416/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003417/// This provides the location of the left/right parens and a list of comma
3418/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003419ExprResult
John McCallb268a282010-08-23 23:25:46 +00003420Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003421 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003422 Expr *ExecConfig) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003423 unsigned NumArgs = ArgExprs.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003424
3425 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003426 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003427 if (Result.isInvalid()) return ExprError();
3428 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003429
Richard Trieuba63ce62011-09-09 01:45:06 +00003430 Expr **Args = ArgExprs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003431
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003432 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003433 // If this is a pseudo-destructor expression, build the call immediately.
3434 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3435 if (NumArgs > 0) {
3436 // Pseudo-destructor calls should not have any arguments.
3437 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003438 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003439 SourceRange(Args[0]->getLocStart(),
3440 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003441
Douglas Gregorad8a3362009-09-04 17:36:40 +00003442 NumArgs = 0;
3443 }
Mike Stump11289f42009-09-09 15:08:12 +00003444
Douglas Gregorad8a3362009-09-04 17:36:40 +00003445 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003446 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003447 }
Mike Stump11289f42009-09-09 15:08:12 +00003448
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003449 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003450 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003451 // FIXME: Will need to cache the results of name lookup (including ADL) in
3452 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003453 bool Dependent = false;
3454 if (Fn->isTypeDependent())
3455 Dependent = true;
3456 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3457 Dependent = true;
3458
Peter Collingbourne41f85462011-02-09 21:07:24 +00003459 if (Dependent) {
3460 if (ExecConfig) {
3461 return Owned(new (Context) CUDAKernelCallExpr(
3462 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3463 Context.DependentTy, VK_RValue, RParenLoc));
3464 } else {
3465 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3466 Context.DependentTy, VK_RValue,
3467 RParenLoc));
3468 }
3469 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003470
3471 // Determine whether this is a call to an object (C++ [over.call.object]).
3472 if (Fn->getType()->isRecordType())
3473 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003474 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003475
John McCall2979fe02011-04-12 00:42:48 +00003476 if (Fn->getType() == Context.UnknownAnyTy) {
3477 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3478 if (result.isInvalid()) return ExprError();
3479 Fn = result.take();
3480 }
3481
John McCall0009fcc2011-04-26 20:42:42 +00003482 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003483 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003484 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003485 }
John McCall0009fcc2011-04-26 20:42:42 +00003486 }
John McCall10eae182009-11-30 22:42:35 +00003487
John McCall0009fcc2011-04-26 20:42:42 +00003488 // Check for overloaded calls. This can happen even in C due to extensions.
3489 if (Fn->getType() == Context.OverloadTy) {
3490 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3491
3492 // We aren't supposed to apply this logic if there's an '&' involved.
3493 if (!find.IsAddressOfOperand) {
3494 OverloadExpr *ovl = find.Expression;
3495 if (isa<UnresolvedLookupExpr>(ovl)) {
3496 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3497 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3498 RParenLoc, ExecConfig);
3499 } else {
John McCall2d74de92009-12-01 22:10:20 +00003500 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003501 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003502 }
3503 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003504 }
3505
Douglas Gregore254f902009-02-04 00:32:51 +00003506 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003507
Eli Friedmane14b1992009-12-26 03:35:45 +00003508 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003509
John McCall57500772009-12-16 12:17:52 +00003510 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003511 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3512 if (UnOp->getOpcode() == UO_AddrOf)
3513 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3514
John McCall57500772009-12-16 12:17:52 +00003515 if (isa<DeclRefExpr>(NakedFn))
3516 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003517 else if (isa<MemberExpr>(NakedFn))
3518 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003519
Peter Collingbourne41f85462011-02-09 21:07:24 +00003520 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3521 ExecConfig);
3522}
3523
3524ExprResult
3525Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003526 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbourne41f85462011-02-09 21:07:24 +00003527 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3528 if (!ConfigDecl)
3529 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3530 << "cudaConfigureCall");
3531 QualType ConfigQTy = ConfigDecl->getType();
3532
3533 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3534 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3535
Richard Trieuba63ce62011-09-09 01:45:06 +00003536 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00003537}
3538
Tanya Lattner55808c12011-06-04 00:47:47 +00003539/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3540///
3541/// __builtin_astype( value, dst type )
3542///
Richard Trieuba63ce62011-09-09 01:45:06 +00003543ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00003544 SourceLocation BuiltinLoc,
3545 SourceLocation RParenLoc) {
3546 ExprValueKind VK = VK_RValue;
3547 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00003548 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3549 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00003550 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3551 return ExprError(Diag(BuiltinLoc,
3552 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003553 << DstTy
3554 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00003555 << E->getSourceRange());
3556 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieucfc491d2011-08-02 04:35:43 +00003557 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003558}
3559
John McCall57500772009-12-16 12:17:52 +00003560/// BuildResolvedCallExpr - Build a call to a resolved expression,
3561/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003562/// unary-convert to an expression of function-pointer or
3563/// block-pointer type.
3564///
3565/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003566ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003567Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3568 SourceLocation LParenLoc,
3569 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003570 SourceLocation RParenLoc,
3571 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00003572 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3573
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003574 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003575 ExprResult Result = UsualUnaryConversions(Fn);
3576 if (Result.isInvalid())
3577 return ExprError();
3578 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003579
Chris Lattner08464942007-12-28 05:29:59 +00003580 // Make the call expr early, before semantic checks. This guarantees cleanup
3581 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003582 CallExpr *TheCall;
3583 if (Config) {
3584 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3585 cast<CallExpr>(Config),
3586 Args, NumArgs,
3587 Context.BoolTy,
3588 VK_RValue,
3589 RParenLoc);
3590 } else {
3591 TheCall = new (Context) CallExpr(Context, Fn,
3592 Args, NumArgs,
3593 Context.BoolTy,
3594 VK_RValue,
3595 RParenLoc);
3596 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003597
John McCallbebede42011-02-26 05:39:39 +00003598 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3599
3600 // Bail out early if calling a builtin with custom typechecking.
3601 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3602 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3603
John McCall31996342011-04-07 08:22:57 +00003604 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003605 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003606 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003607 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3608 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003609 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003610 if (FuncT == 0)
3611 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3612 << Fn->getType() << Fn->getSourceRange());
3613 } else if (const BlockPointerType *BPT =
3614 Fn->getType()->getAs<BlockPointerType>()) {
3615 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3616 } else {
John McCall31996342011-04-07 08:22:57 +00003617 // Handle calls to expressions of unknown-any type.
3618 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003619 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003620 if (rewrite.isInvalid()) return ExprError();
3621 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003622 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003623 goto retry;
3624 }
3625
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003626 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3627 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003628 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003629
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003630 if (getLangOptions().CUDA) {
3631 if (Config) {
3632 // CUDA: Kernel calls must be to global functions
3633 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3634 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3635 << FDecl->getName() << Fn->getSourceRange());
3636
3637 // CUDA: Kernel function must have 'void' return type
3638 if (!FuncT->getResultType()->isVoidType())
3639 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3640 << Fn->getType() << Fn->getSourceRange());
3641 }
3642 }
3643
Eli Friedman3164fb12009-03-22 22:00:50 +00003644 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003645 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00003646 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003647 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003648 return ExprError();
3649
Chris Lattner08464942007-12-28 05:29:59 +00003650 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003651 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003652 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003653
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003654 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003655 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003656 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003657 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003658 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003659 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003660
Douglas Gregord8e97de2009-04-02 15:37:10 +00003661 if (FDecl) {
3662 // Check if we have too few/too many template arguments, based
3663 // on our knowledge of the function definition.
3664 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003665 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003666 const FunctionProtoType *Proto
3667 = Def->getType()->getAs<FunctionProtoType>();
3668 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003669 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3670 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003671 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003672
3673 // If the function we're calling isn't a function prototype, but we have
3674 // a function prototype from a prior declaratiom, use that prototype.
3675 if (!FDecl->hasPrototype())
3676 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003677 }
3678
Steve Naroff0b661582007-08-28 23:30:39 +00003679 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003680 for (unsigned i = 0; i != NumArgs; i++) {
3681 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003682
3683 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003684 InitializedEntity Entity
3685 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003686 Proto->getArgType(i),
3687 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003688 ExprResult ArgE = PerformCopyInitialization(Entity,
3689 SourceLocation(),
3690 Owned(Arg));
3691 if (ArgE.isInvalid())
3692 return true;
3693
3694 Arg = ArgE.takeAs<Expr>();
3695
3696 } else {
John Wiegley01296292011-04-08 18:41:53 +00003697 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3698
3699 if (ArgE.isInvalid())
3700 return true;
3701
3702 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003703 }
3704
Douglas Gregor83025412010-10-26 05:45:40 +00003705 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3706 Arg->getType(),
3707 PDiag(diag::err_call_incomplete_argument)
3708 << Arg->getSourceRange()))
3709 return ExprError();
3710
Chris Lattner08464942007-12-28 05:29:59 +00003711 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003712 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003713 }
Chris Lattner08464942007-12-28 05:29:59 +00003714
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003715 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3716 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003717 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3718 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003719
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003720 // Check for sentinels
3721 if (NDecl)
3722 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003723
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003724 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003725 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003726 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003727 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003728
John McCallbebede42011-02-26 05:39:39 +00003729 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003730 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003731 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003732 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003733 return ExprError();
3734 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003735
John McCallb268a282010-08-23 23:25:46 +00003736 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003737}
3738
John McCalldadc5752010-08-24 06:29:42 +00003739ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003740Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003741 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003742 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003743 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003744 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003745
3746 TypeSourceInfo *TInfo;
3747 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3748 if (!TInfo)
3749 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3750
John McCallb268a282010-08-23 23:25:46 +00003751 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003752}
3753
John McCalldadc5752010-08-24 06:29:42 +00003754ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003755Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00003756 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003757 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003758
Eli Friedman37a186d2008-05-20 05:22:08 +00003759 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003760 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3761 PDiag(diag::err_illegal_decl_array_incomplete_type)
3762 << SourceRange(LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003763 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003764 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00003765 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003766 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00003767 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003768 } else if (!literalType->isDependentType() &&
3769 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003770 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003771 << SourceRange(LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003772 LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003773 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003774
Douglas Gregor85dabae2009-12-16 01:38:02 +00003775 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003776 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003777 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00003778 = InitializationKind::CreateCStyleCast(LParenLoc,
3779 SourceRange(LParenLoc, RParenLoc));
Richard Trieuba63ce62011-09-09 01:45:06 +00003780 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003781 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuba63ce62011-09-09 01:45:06 +00003782 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003783 &literalType);
3784 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003785 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00003786 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003787
Chris Lattner79413952008-12-04 23:50:19 +00003788 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003789 if (isFileScope) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00003790 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003791 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003792 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003793
John McCall7decc9e2010-11-18 06:31:45 +00003794 // In C, compound literals are l-values for some reason.
3795 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3796
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00003797 return MaybeBindToTemporary(
3798 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00003799 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003800}
3801
John McCalldadc5752010-08-24 06:29:42 +00003802ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00003803Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003804 SourceLocation RBraceLoc) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003805 unsigned NumInit = InitArgList.size();
3806 Expr **InitList = InitArgList.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00003807
Steve Naroff30d242c2007-09-15 18:49:24 +00003808 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003809 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003810
Ted Kremenekac034612010-04-13 23:39:13 +00003811 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3812 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003813 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003814 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003815}
3816
John McCallcd78e802011-09-10 01:16:55 +00003817/// Do an explicit extend of the given block pointer if we're in ARC.
3818static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
3819 assert(E.get()->getType()->isBlockPointerType());
3820 assert(E.get()->isRValue());
3821
3822 // Only do this in an r-value context.
3823 if (!S.getLangOptions().ObjCAutoRefCount) return;
3824
3825 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00003826 CK_ARCExtendBlockObject, E.get(),
John McCallcd78e802011-09-10 01:16:55 +00003827 /*base path*/ 0, VK_RValue);
3828 S.ExprNeedsCleanups = true;
3829}
3830
3831/// Prepare a conversion of the given expression to an ObjC object
3832/// pointer type.
3833CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
3834 QualType type = E.get()->getType();
3835 if (type->isObjCObjectPointerType()) {
3836 return CK_BitCast;
3837 } else if (type->isBlockPointerType()) {
3838 maybeExtendBlockObject(*this, E);
3839 return CK_BlockPointerToObjCPointerCast;
3840 } else {
3841 assert(type->isPointerType());
3842 return CK_CPointerToObjCPointerCast;
3843 }
3844}
3845
John McCalld7646252010-11-14 08:17:51 +00003846/// Prepares for a scalar cast, performing all the necessary stages
3847/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00003848static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00003849 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3850 // Also, callers should have filtered out the invalid cases with
3851 // pointers. Everything else should be possible.
3852
John Wiegley01296292011-04-08 18:41:53 +00003853 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00003854 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00003855 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00003856
John McCall9320b872011-09-09 05:25:32 +00003857 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00003858 case Type::STK_MemberPointer:
3859 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00003860
John McCall9320b872011-09-09 05:25:32 +00003861 case Type::STK_CPointer:
3862 case Type::STK_BlockPointer:
3863 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00003864 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00003865 case Type::STK_CPointer:
3866 return CK_BitCast;
3867 case Type::STK_BlockPointer:
3868 return (SrcKind == Type::STK_BlockPointer
3869 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
3870 case Type::STK_ObjCObjectPointer:
3871 if (SrcKind == Type::STK_ObjCObjectPointer)
3872 return CK_BitCast;
3873 else if (SrcKind == Type::STK_CPointer)
3874 return CK_CPointerToObjCPointerCast;
John McCallcd78e802011-09-10 01:16:55 +00003875 else {
3876 maybeExtendBlockObject(S, Src);
John McCall9320b872011-09-09 05:25:32 +00003877 return CK_BlockPointerToObjCPointerCast;
John McCallcd78e802011-09-10 01:16:55 +00003878 }
John McCall8cb679e2010-11-15 09:13:47 +00003879 case Type::STK_Bool:
3880 return CK_PointerToBoolean;
3881 case Type::STK_Integral:
3882 return CK_PointerToIntegral;
3883 case Type::STK_Floating:
3884 case Type::STK_FloatingComplex:
3885 case Type::STK_IntegralComplex:
3886 case Type::STK_MemberPointer:
3887 llvm_unreachable("illegal cast from pointer");
3888 }
3889 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003890
John McCall8cb679e2010-11-15 09:13:47 +00003891 case Type::STK_Bool: // casting from bool is like casting from an integer
3892 case Type::STK_Integral:
3893 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00003894 case Type::STK_CPointer:
3895 case Type::STK_ObjCObjectPointer:
3896 case Type::STK_BlockPointer:
Richard Trieucfc491d2011-08-02 04:35:43 +00003897 if (Src.get()->isNullPointerConstant(S.Context,
3898 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00003899 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00003900 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00003901 case Type::STK_Bool:
3902 return CK_IntegralToBoolean;
3903 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00003904 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00003905 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003906 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003907 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003908 Src = S.ImpCastExprToType(Src.take(),
3909 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003910 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00003911 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003912 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003913 Src = S.ImpCastExprToType(Src.take(),
3914 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003915 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00003916 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003917 case Type::STK_MemberPointer:
3918 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003919 }
3920 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003921
John McCall8cb679e2010-11-15 09:13:47 +00003922 case Type::STK_Floating:
3923 switch (DestTy->getScalarTypeKind()) {
3924 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003925 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00003926 case Type::STK_Bool:
3927 return CK_FloatingToBoolean;
3928 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00003929 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003930 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003931 Src = S.ImpCastExprToType(Src.take(),
3932 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003933 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00003934 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003935 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003936 Src = S.ImpCastExprToType(Src.take(),
3937 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003938 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00003939 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00003940 case Type::STK_CPointer:
3941 case Type::STK_ObjCObjectPointer:
3942 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00003943 llvm_unreachable("valid float->pointer cast?");
3944 case Type::STK_MemberPointer:
3945 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003946 }
3947 break;
3948
John McCall8cb679e2010-11-15 09:13:47 +00003949 case Type::STK_FloatingComplex:
3950 switch (DestTy->getScalarTypeKind()) {
3951 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003952 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00003953 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003954 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00003955 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003956 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003957 if (S.Context.hasSameType(ET, DestTy))
3958 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003959 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003960 return CK_FloatingCast;
3961 }
John McCall8cb679e2010-11-15 09:13:47 +00003962 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003963 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003964 case Type::STK_Integral:
Richard Trieucfc491d2011-08-02 04:35:43 +00003965 Src = S.ImpCastExprToType(Src.take(),
3966 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003967 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003968 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00003969 case Type::STK_CPointer:
3970 case Type::STK_ObjCObjectPointer:
3971 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00003972 llvm_unreachable("valid complex float->pointer cast?");
3973 case Type::STK_MemberPointer:
3974 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003975 }
3976 break;
3977
John McCall8cb679e2010-11-15 09:13:47 +00003978 case Type::STK_IntegralComplex:
3979 switch (DestTy->getScalarTypeKind()) {
3980 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003981 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003982 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003983 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00003984 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003985 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003986 if (S.Context.hasSameType(ET, DestTy))
3987 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003988 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003989 return CK_IntegralCast;
3990 }
John McCall8cb679e2010-11-15 09:13:47 +00003991 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003992 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003993 case Type::STK_Floating:
Richard Trieucfc491d2011-08-02 04:35:43 +00003994 Src = S.ImpCastExprToType(Src.take(),
3995 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003996 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003997 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00003998 case Type::STK_CPointer:
3999 case Type::STK_ObjCObjectPointer:
4000 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004001 llvm_unreachable("valid complex int->pointer cast?");
4002 case Type::STK_MemberPointer:
4003 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004004 }
4005 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00004006 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004007
John McCalld7646252010-11-14 08:17:51 +00004008 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00004009}
4010
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004011/// CheckCastTypes - Check type constraints for casting between types.
Richard Trieuba63ce62011-09-09 01:45:06 +00004012ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc,
4013 SourceRange TypeRange, QualType CastType,
4014 Expr *CastExpr, CastKind &Kind,
4015 ExprValueKind &VK, CXXCastPath &BasePath,
4016 bool FunctionalStyle) {
4017 if (CastExpr->getType() == Context.UnknownAnyTy)
4018 return checkUnknownAnyCast(TypeRange, CastType, CastExpr, Kind, VK,
4019 BasePath);
John McCall31996342011-04-07 08:22:57 +00004020
Sebastian Redl9f831db2009-07-25 15:41:38 +00004021 if (getLangOptions().CPlusPlus)
John McCall31168b02011-06-15 23:02:42 +00004022 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004023 CastExpr->getLocEnd()),
4024 CastType, VK, CastExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00004025 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00004026
Richard Trieuba63ce62011-09-09 01:45:06 +00004027 assert(!CastExpr->getType()->isPlaceholderType());
John McCall3aef3d82011-04-10 19:13:55 +00004028
John McCall7decc9e2010-11-18 06:31:45 +00004029 // We only support r-value casts in C.
4030 VK = VK_RValue;
4031
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004032 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4033 // type needs to be scalar.
Richard Trieuba63ce62011-09-09 01:45:06 +00004034 if (CastType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00004035 // We don't necessarily do lvalue-to-rvalue conversions on this.
Richard Trieuba63ce62011-09-09 01:45:06 +00004036 ExprResult castExprRes = IgnoredValueConversions(CastExpr);
John Wiegley01296292011-04-08 18:41:53 +00004037 if (castExprRes.isInvalid())
4038 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004039 CastExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00004040
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004041 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00004042 Kind = CK_ToVoid;
Richard Trieuba63ce62011-09-09 01:45:06 +00004043 return Owned(CastExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00004044 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004045
Richard Trieuba63ce62011-09-09 01:45:06 +00004046 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(CastExpr);
John Wiegley01296292011-04-08 18:41:53 +00004047 if (castExprRes.isInvalid())
4048 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004049 CastExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00004050
Richard Trieuba63ce62011-09-09 01:45:06 +00004051 if (RequireCompleteType(TypeRange.getBegin(), CastType,
Eli Friedmane98194d2010-07-17 20:43:49 +00004052 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00004053 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00004054
Richard Trieuba63ce62011-09-09 01:45:06 +00004055 if (!CastType->isScalarType() && !CastType->isVectorType()) {
4056 if (Context.hasSameUnqualifiedType(CastType, CastExpr->getType()) &&
4057 (CastType->isStructureType() || CastType->isUnionType())) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004058 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00004059 // FIXME: Check that the cast destination type is complete.
Richard Trieuba63ce62011-09-09 01:45:06 +00004060 Diag(TypeRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
4061 << CastType << CastExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004062 Kind = CK_NoOp;
Richard Trieuba63ce62011-09-09 01:45:06 +00004063 return Owned(CastExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00004064 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004065
Richard Trieuba63ce62011-09-09 01:45:06 +00004066 if (CastType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004067 // GCC cast to union extension
Richard Trieuba63ce62011-09-09 01:45:06 +00004068 RecordDecl *RD = CastType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004069 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004070 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004071 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004072 if (Context.hasSameUnqualifiedType(Field->getType(),
Richard Trieuba63ce62011-09-09 01:45:06 +00004073 CastExpr->getType()) &&
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00004074 !Field->isUnnamedBitfield()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004075 Diag(TypeRange.getBegin(), diag::ext_typecheck_cast_to_union)
4076 << CastExpr->getSourceRange();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004077 break;
4078 }
4079 }
John Wiegley01296292011-04-08 18:41:53 +00004080 if (Field == FieldEnd) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004081 Diag(TypeRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
4082 << CastExpr->getType() << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004083 return ExprError();
4084 }
John McCalle3027922010-08-25 11:45:40 +00004085 Kind = CK_ToUnion;
Richard Trieuba63ce62011-09-09 01:45:06 +00004086 return Owned(CastExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004087 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004088
Anders Carlsson525b76b2009-10-16 02:48:28 +00004089 // Reject any other conversions to non-scalar types.
Richard Trieuba63ce62011-09-09 01:45:06 +00004090 Diag(TypeRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
4091 << CastType << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004092 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004093 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004094
John McCalld7646252010-11-14 08:17:51 +00004095 // The type we're casting to is known to be a scalar or vector.
4096
4097 // Require the operand to be a scalar or vector.
Richard Trieuba63ce62011-09-09 01:45:06 +00004098 if (!CastExpr->getType()->isScalarType() &&
4099 !CastExpr->getType()->isVectorType()) {
4100 Diag(CastExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004101 diag::err_typecheck_expect_scalar_operand)
Richard Trieuba63ce62011-09-09 01:45:06 +00004102 << CastExpr->getType() << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004103 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004104 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004105
Richard Trieuba63ce62011-09-09 01:45:06 +00004106 if (CastType->isExtVectorType())
4107 return CheckExtVectorCast(TypeRange, CastType, CastExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004108
Richard Trieuba63ce62011-09-09 01:45:06 +00004109 if (CastType->isVectorType()) {
4110 if (CastType->getAs<VectorType>()->getVectorKind() ==
Anton Yartsev28ccef72011-03-27 09:32:40 +00004111 VectorType::AltiVecVector &&
Richard Trieuba63ce62011-09-09 01:45:06 +00004112 (CastExpr->getType()->isIntegerType() ||
4113 CastExpr->getType()->isFloatingType())) {
Anton Yartsev28ccef72011-03-27 09:32:40 +00004114 Kind = CK_VectorSplat;
Richard Trieuba63ce62011-09-09 01:45:06 +00004115 return Owned(CastExpr);
4116 } else if (CheckVectorCast(TypeRange, CastType, CastExpr->getType(),
4117 Kind)) {
John Wiegley01296292011-04-08 18:41:53 +00004118 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00004119 } else
Richard Trieuba63ce62011-09-09 01:45:06 +00004120 return Owned(CastExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00004121 }
Richard Trieuba63ce62011-09-09 01:45:06 +00004122 if (CastExpr->getType()->isVectorType()) {
4123 if (CheckVectorCast(TypeRange, CastExpr->getType(), CastType, Kind))
John Wiegley01296292011-04-08 18:41:53 +00004124 return ExprError();
4125 else
Richard Trieuba63ce62011-09-09 01:45:06 +00004126 return Owned(CastExpr);
John Wiegley01296292011-04-08 18:41:53 +00004127 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00004128
John McCalld7646252010-11-14 08:17:51 +00004129 // The source and target types are both scalars, i.e.
4130 // - arithmetic types (fundamental, enum, and complex)
4131 // - all kinds of pointers
4132 // Note that member pointers were filtered out with C++, above.
4133
Richard Trieuba63ce62011-09-09 01:45:06 +00004134 if (isa<ObjCSelectorExpr>(CastExpr)) {
4135 Diag(CastExpr->getLocStart(), diag::err_cast_selector_expr);
John Wiegley01296292011-04-08 18:41:53 +00004136 return ExprError();
4137 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004138
John McCalld7646252010-11-14 08:17:51 +00004139 // If either type is a pointer, the other type has to be either an
4140 // integer or a pointer.
Richard Trieuba63ce62011-09-09 01:45:06 +00004141 QualType CastExprType = CastExpr->getType();
4142 if (!CastType->isArithmeticType()) {
4143 if (!CastExprType->isIntegralType(Context) &&
4144 CastExprType->isArithmeticType()) {
4145 Diag(CastExpr->getLocStart(),
John Wiegley01296292011-04-08 18:41:53 +00004146 diag::err_cast_pointer_from_non_pointer_int)
Richard Trieuba63ce62011-09-09 01:45:06 +00004147 << CastExprType << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004148 return ExprError();
4149 }
Richard Trieuba63ce62011-09-09 01:45:06 +00004150 } else if (!CastExpr->getType()->isArithmeticType()) {
4151 if (!CastType->isIntegralType(Context) && CastType->isArithmeticType()) {
4152 Diag(CastExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
4153 << CastType << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004154 return ExprError();
4155 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004156 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004157
John McCall31168b02011-06-15 23:02:42 +00004158 if (getLangOptions().ObjCAutoRefCount) {
4159 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
Richard Trieuba63ce62011-09-09 01:45:06 +00004160 CheckObjCARCConversion(SourceRange(CastStartLoc, CastExpr->getLocEnd()),
4161 CastType, CastExpr, CCK_CStyleCast);
John McCall31168b02011-06-15 23:02:42 +00004162
Richard Trieuba63ce62011-09-09 01:45:06 +00004163 if (const PointerType *CastPtr = CastType->getAs<PointerType>()) {
4164 if (const PointerType *ExprPtr = CastExprType->getAs<PointerType>()) {
John McCall31168b02011-06-15 23:02:42 +00004165 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4166 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4167 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4168 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4169 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004170 Diag(CastExpr->getLocStart(),
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004171 diag::err_typecheck_incompatible_ownership)
Richard Trieuba63ce62011-09-09 01:45:06 +00004172 << CastExprType << CastType << AA_Casting
4173 << CastExpr->getSourceRange();
John McCall31168b02011-06-15 23:02:42 +00004174
4175 return ExprError();
4176 }
4177 }
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004178 }
Richard Trieuba63ce62011-09-09 01:45:06 +00004179 else if (!CheckObjCARCUnavailableWeakConversion(CastType, CastExprType)) {
4180 Diag(CastExpr->getLocStart(),
Fariborz Jahanianf2913402011-07-08 17:41:42 +00004181 diag::err_arc_convesion_of_weak_unavailable) << 1
Richard Trieuba63ce62011-09-09 01:45:06 +00004182 << CastExprType << CastType
4183 << CastExpr->getSourceRange();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004184 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00004185 }
4186 }
4187
Richard Trieuba63ce62011-09-09 01:45:06 +00004188 castExprRes = Owned(CastExpr);
4189 Kind = PrepareScalarCast(*this, castExprRes, CastType);
John Wiegley01296292011-04-08 18:41:53 +00004190 if (castExprRes.isInvalid())
4191 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004192 CastExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00004193
John McCalld7646252010-11-14 08:17:51 +00004194 if (Kind == CK_BitCast)
Richard Trieuba63ce62011-09-09 01:45:06 +00004195 CheckCastAlign(CastExpr, CastType, TypeRange);
John McCall2b5c1b22010-08-12 21:44:57 +00004196
Richard Trieuba63ce62011-09-09 01:45:06 +00004197 return Owned(CastExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004198}
4199
Anders Carlsson525b76b2009-10-16 02:48:28 +00004200bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004201 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004202 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004203
Anders Carlssonde71adf2007-11-27 05:51:55 +00004204 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004205 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004206 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004207 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004208 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004209 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004210 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004211 } else
4212 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004213 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004214 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004215
John McCalle3027922010-08-25 11:45:40 +00004216 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004217 return false;
4218}
4219
John Wiegley01296292011-04-08 18:41:53 +00004220ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4221 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004222 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004223
Anders Carlsson43d70f82009-10-16 05:23:41 +00004224 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004225
Nate Begemanc8961a42009-06-27 22:05:55 +00004226 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4227 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00004228 // In OpenCL, casts between vectors of different types are not allowed.
4229 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00004230 if (SrcTy->isVectorType()) {
Tobias Grosser766bcc22011-09-22 13:03:14 +00004231 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4232 || (getLangOptions().OpenCL &&
4233 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004234 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004235 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004236 return ExprError();
4237 }
John McCalle3027922010-08-25 11:45:40 +00004238 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004239 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004240 }
4241
Nate Begemanbd956c42009-06-28 02:36:38 +00004242 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004243 // conversion will take place first from scalar to elt type, and then
4244 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004245 if (SrcTy->isPointerType())
4246 return Diag(R.getBegin(),
4247 diag::err_invalid_conversion_between_vector_and_scalar)
4248 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004249
4250 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004251 ExprResult CastExprRes = Owned(CastExpr);
4252 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4253 if (CastExprRes.isInvalid())
4254 return ExprError();
4255 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004256
John McCalle3027922010-08-25 11:45:40 +00004257 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004258 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004259}
4260
John McCalldadc5752010-08-24 06:29:42 +00004261ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004262Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4263 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004264 SourceLocation RParenLoc, Expr *CastExpr) {
4265 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004266 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004267
Richard Trieuba63ce62011-09-09 01:45:06 +00004268 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004269 if (D.isInvalidType())
4270 return ExprError();
4271
4272 if (getLangOptions().CPlusPlus) {
4273 // Check that there are no default arguments (C++ only).
4274 CheckExtraCXXDefaultArguments(D);
4275 }
4276
4277 QualType castType = castTInfo->getType();
4278 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004279
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004280 bool isVectorLiteral = false;
4281
4282 // Check for an altivec or OpenCL literal,
4283 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00004284 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4285 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00004286 if ((getLangOptions().AltiVec || getLangOptions().OpenCL)
4287 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004288 if (PLE && PLE->getNumExprs() == 0) {
4289 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4290 return ExprError();
4291 }
4292 if (PE || PLE->getNumExprs() == 1) {
4293 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4294 if (!E->getType()->isVectorType())
4295 isVectorLiteral = true;
4296 }
4297 else
4298 isVectorLiteral = true;
4299 }
4300
4301 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4302 // then handle it as such.
4303 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00004304 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004305
Nate Begeman5ec4b312009-08-10 23:49:36 +00004306 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004307 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4308 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00004309 if (isa<ParenListExpr>(CastExpr)) {
4310 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004311 if (Result.isInvalid()) return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004312 CastExpr = Result.take();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004313 }
John McCallebe54742010-01-15 18:56:44 +00004314
Richard Trieuba63ce62011-09-09 01:45:06 +00004315 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00004316}
4317
John McCalldadc5752010-08-24 06:29:42 +00004318ExprResult
John McCallebe54742010-01-15 18:56:44 +00004319Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004320 SourceLocation RParenLoc, Expr *CastExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00004321 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00004322 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00004323 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00004324 ExprResult CastResult =
John McCall31168b02011-06-15 23:02:42 +00004325 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
Richard Trieuba63ce62011-09-09 01:45:06 +00004326 CastExpr, Kind, VK, BasePath);
John Wiegley01296292011-04-08 18:41:53 +00004327 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004328 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004329 CastExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00004330
Richard Trieucfc491d2011-08-02 04:35:43 +00004331 return Owned(CStyleCastExpr::Create(
Richard Trieuba63ce62011-09-09 01:45:06 +00004332 Context, Ty->getType().getNonLValueExprType(Context), VK, Kind, CastExpr,
Richard Trieucfc491d2011-08-02 04:35:43 +00004333 &BasePath, Ty, LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004334}
4335
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004336ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4337 SourceLocation RParenLoc, Expr *E,
4338 TypeSourceInfo *TInfo) {
4339 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4340 "Expected paren or paren list expression");
4341
4342 Expr **exprs;
4343 unsigned numExprs;
4344 Expr *subExpr;
4345 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4346 exprs = PE->getExprs();
4347 numExprs = PE->getNumExprs();
4348 } else {
4349 subExpr = cast<ParenExpr>(E)->getSubExpr();
4350 exprs = &subExpr;
4351 numExprs = 1;
4352 }
4353
4354 QualType Ty = TInfo->getType();
4355 assert(Ty->isVectorType() && "Expected vector type");
4356
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004357 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004358 const VectorType *VTy = Ty->getAs<VectorType>();
4359 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4360
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004361 // '(...)' form of vector initialization in AltiVec: the number of
4362 // initializers must be one or must match the size of the vector.
4363 // If a single value is specified in the initializer then it will be
4364 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004365 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004366 // The number of initializers must be one or must match the size of the
4367 // vector. If a single value is specified in the initializer then it will
4368 // be replicated to all the components of the vector
4369 if (numExprs == 1) {
4370 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4371 ExprResult Literal = Owned(exprs[0]);
4372 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4373 PrepareScalarCast(*this, Literal, ElemTy));
4374 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4375 }
4376 else if (numExprs < numElems) {
4377 Diag(E->getExprLoc(),
4378 diag::err_incorrect_number_of_vector_initializers);
4379 return ExprError();
4380 }
4381 else
4382 for (unsigned i = 0, e = numExprs; i != e; ++i)
4383 initExprs.push_back(exprs[i]);
4384 }
Tanya Lattner83559382011-07-15 23:07:01 +00004385 else {
4386 // For OpenCL, when the number of initializers is a single value,
4387 // it will be replicated to all components of the vector.
4388 if (getLangOptions().OpenCL &&
4389 VTy->getVectorKind() == VectorType::GenericVector &&
4390 numExprs == 1) {
4391 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4392 ExprResult Literal = Owned(exprs[0]);
4393 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4394 PrepareScalarCast(*this, Literal, ElemTy));
4395 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4396 }
4397
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004398 for (unsigned i = 0, e = numExprs; i != e; ++i)
4399 initExprs.push_back(exprs[i]);
Tanya Lattner83559382011-07-15 23:07:01 +00004400 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004401 // FIXME: This means that pretty-printing the final AST will produce curly
4402 // braces instead of the original commas.
4403 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4404 &initExprs[0],
4405 initExprs.size(), RParenLoc);
4406 initE->setType(Ty);
4407 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4408}
4409
Nate Begeman5ec4b312009-08-10 23:49:36 +00004410/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4411/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004412ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004413Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4414 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004415 if (!E)
Richard Trieuba63ce62011-09-09 01:45:06 +00004416 return Owned(OrigExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004417
John McCalldadc5752010-08-24 06:29:42 +00004418 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004419
Nate Begeman5ec4b312009-08-10 23:49:36 +00004420 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004421 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4422 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004423
John McCallb268a282010-08-23 23:25:46 +00004424 if (Result.isInvalid()) return ExprError();
4425
4426 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004427}
4428
John McCalldadc5752010-08-24 06:29:42 +00004429ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Richard Trieuba63ce62011-09-09 01:45:06 +00004430 SourceLocation R,
4431 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004432 unsigned nexprs = Val.size();
4433 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004434 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4435 Expr *expr;
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004436 if (nexprs == 1)
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004437 expr = new (Context) ParenExpr(L, R, exprs[0]);
4438 else
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004439 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4440 exprs[nexprs-1]->getType());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004441 return Owned(expr);
4442}
4443
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004444/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004445/// constant and the other is not a pointer. Returns true if a diagnostic is
4446/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00004447bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004448 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004449 Expr *NullExpr = LHSExpr;
4450 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004451 Expr::NullPointerConstantKind NullKind =
4452 NullExpr->isNullPointerConstant(Context,
4453 Expr::NPC_ValueDependentIsNotNull);
4454
4455 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004456 NullExpr = RHSExpr;
4457 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004458 NullKind =
4459 NullExpr->isNullPointerConstant(Context,
4460 Expr::NPC_ValueDependentIsNotNull);
4461 }
4462
4463 if (NullKind == Expr::NPCK_NotNull)
4464 return false;
4465
4466 if (NullKind == Expr::NPCK_ZeroInteger) {
4467 // In this case, check to make sure that we got here from a "NULL"
4468 // string in the source code.
4469 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004470 SourceLocation loc = NullExpr->getExprLoc();
4471 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004472 return false;
4473 }
4474
4475 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4476 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4477 << NonPointerExpr->getType() << DiagType
4478 << NonPointerExpr->getSourceRange();
4479 return true;
4480}
4481
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004482/// \brief Return false if the condition expression is valid, true otherwise.
4483static bool checkCondition(Sema &S, Expr *Cond) {
4484 QualType CondTy = Cond->getType();
4485
4486 // C99 6.5.15p2
4487 if (CondTy->isScalarType()) return false;
4488
4489 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4490 if (S.getLangOptions().OpenCL && CondTy->isVectorType())
4491 return false;
4492
4493 // Emit the proper error message.
4494 S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ?
4495 diag::err_typecheck_cond_expect_scalar :
4496 diag::err_typecheck_cond_expect_scalar_or_vector)
4497 << CondTy;
4498 return true;
4499}
4500
4501/// \brief Return false if the two expressions can be converted to a vector,
4502/// true otherwise
4503static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4504 ExprResult &RHS,
4505 QualType CondTy) {
4506 // Both operands should be of scalar type.
4507 if (!LHS.get()->getType()->isScalarType()) {
4508 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4509 << CondTy;
4510 return true;
4511 }
4512 if (!RHS.get()->getType()->isScalarType()) {
4513 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4514 << CondTy;
4515 return true;
4516 }
4517
4518 // Implicity convert these scalars to the type of the condition.
4519 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4520 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4521 return false;
4522}
4523
4524/// \brief Handle when one or both operands are void type.
4525static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4526 ExprResult &RHS) {
4527 Expr *LHSExpr = LHS.get();
4528 Expr *RHSExpr = RHS.get();
4529
4530 if (!LHSExpr->getType()->isVoidType())
4531 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4532 << RHSExpr->getSourceRange();
4533 if (!RHSExpr->getType()->isVoidType())
4534 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4535 << LHSExpr->getSourceRange();
4536 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4537 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4538 return S.Context.VoidTy;
4539}
4540
4541/// \brief Return false if the NullExpr can be promoted to PointerTy,
4542/// true otherwise.
4543static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4544 QualType PointerTy) {
4545 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4546 !NullExpr.get()->isNullPointerConstant(S.Context,
4547 Expr::NPC_ValueDependentIsNull))
4548 return true;
4549
4550 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4551 return false;
4552}
4553
4554/// \brief Checks compatibility between two pointers and return the resulting
4555/// type.
4556static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4557 ExprResult &RHS,
4558 SourceLocation Loc) {
4559 QualType LHSTy = LHS.get()->getType();
4560 QualType RHSTy = RHS.get()->getType();
4561
4562 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4563 // Two identical pointers types are always compatible.
4564 return LHSTy;
4565 }
4566
4567 QualType lhptee, rhptee;
4568
4569 // Get the pointee types.
John McCall9320b872011-09-09 05:25:32 +00004570 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4571 lhptee = LHSBTy->getPointeeType();
4572 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004573 } else {
John McCall9320b872011-09-09 05:25:32 +00004574 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4575 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004576 }
4577
4578 if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4579 rhptee.getUnqualifiedType())) {
4580 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4581 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4582 << RHS.get()->getSourceRange();
4583 // In this situation, we assume void* type. No especially good
4584 // reason, but this is what gcc does, and we do have to pick
4585 // to get a consistent AST.
4586 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4587 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4588 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4589 return incompatTy;
4590 }
4591
4592 // The pointer types are compatible.
4593 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4594 // differently qualified versions of compatible types, the result type is
4595 // a pointer to an appropriately qualified version of the *composite*
4596 // type.
4597 // FIXME: Need to calculate the composite type.
4598 // FIXME: Need to add qualifiers
4599
4600 LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4601 RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4602 return LHSTy;
4603}
4604
4605/// \brief Return the resulting type when the operands are both block pointers.
4606static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4607 ExprResult &LHS,
4608 ExprResult &RHS,
4609 SourceLocation Loc) {
4610 QualType LHSTy = LHS.get()->getType();
4611 QualType RHSTy = RHS.get()->getType();
4612
4613 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4614 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4615 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4616 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4617 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4618 return destType;
4619 }
4620 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4621 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4622 << RHS.get()->getSourceRange();
4623 return QualType();
4624 }
4625
4626 // We have 2 block pointer types.
4627 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4628}
4629
4630/// \brief Return the resulting type when the operands are both pointers.
4631static QualType
4632checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4633 ExprResult &RHS,
4634 SourceLocation Loc) {
4635 // get the pointer types
4636 QualType LHSTy = LHS.get()->getType();
4637 QualType RHSTy = RHS.get()->getType();
4638
4639 // get the "pointed to" types
4640 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4641 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4642
4643 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4644 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4645 // Figure out necessary qualifiers (C99 6.5.15p6)
4646 QualType destPointee
4647 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4648 QualType destType = S.Context.getPointerType(destPointee);
4649 // Add qualifiers if necessary.
4650 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4651 // Promote to void*.
4652 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4653 return destType;
4654 }
4655 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4656 QualType destPointee
4657 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4658 QualType destType = S.Context.getPointerType(destPointee);
4659 // Add qualifiers if necessary.
4660 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4661 // Promote to void*.
4662 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4663 return destType;
4664 }
4665
4666 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4667}
4668
4669/// \brief Return false if the first expression is not an integer and the second
4670/// expression is not a pointer, true otherwise.
4671static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4672 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004673 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004674 if (!PointerExpr->getType()->isPointerType() ||
4675 !Int.get()->getType()->isIntegerType())
4676 return false;
4677
Richard Trieuba63ce62011-09-09 01:45:06 +00004678 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4679 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004680
4681 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4682 << Expr1->getType() << Expr2->getType()
4683 << Expr1->getSourceRange() << Expr2->getSourceRange();
4684 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4685 CK_IntegralToPointer);
4686 return true;
4687}
4688
Richard Trieud33e46e2011-09-06 20:06:39 +00004689/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4690/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004691/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004692QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4693 ExprResult &RHS, ExprValueKind &VK,
4694 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004695 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004696
Richard Trieud33e46e2011-09-06 20:06:39 +00004697 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4698 if (!LHSResult.isUsable()) return QualType();
4699 LHS = move(LHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004700
Richard Trieud33e46e2011-09-06 20:06:39 +00004701 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4702 if (!RHSResult.isUsable()) return QualType();
4703 RHS = move(RHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004704
Sebastian Redl1a99f442009-04-16 17:51:27 +00004705 // C++ is sufficiently different to merit its own checker.
4706 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004707 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004708
4709 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004710 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004711
John Wiegley01296292011-04-08 18:41:53 +00004712 Cond = UsualUnaryConversions(Cond.take());
4713 if (Cond.isInvalid())
4714 return QualType();
4715 LHS = UsualUnaryConversions(LHS.take());
4716 if (LHS.isInvalid())
4717 return QualType();
4718 RHS = UsualUnaryConversions(RHS.take());
4719 if (RHS.isInvalid())
4720 return QualType();
4721
4722 QualType CondTy = Cond.get()->getType();
4723 QualType LHSTy = LHS.get()->getType();
4724 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004725
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004726 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004727 if (checkCondition(*this, Cond.get()))
4728 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004729
Chris Lattnere2949f42008-01-06 22:42:25 +00004730 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004731 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004732 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004733
Nate Begemanabb5a732010-09-20 22:41:17 +00004734 // OpenCL: If the condition is a vector, and both operands are scalar,
4735 // attempt to implicity convert them to the vector type to act like the
4736 // built in select.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004737 if (getLangOptions().OpenCL && CondTy->isVectorType())
4738 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00004739 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00004740
Chris Lattnere2949f42008-01-06 22:42:25 +00004741 // If both operands have arithmetic type, do the usual arithmetic conversions
4742 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004743 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4744 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004745 if (LHS.isInvalid() || RHS.isInvalid())
4746 return QualType();
4747 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004748 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004749
Chris Lattnere2949f42008-01-06 22:42:25 +00004750 // If both operands are the same structure or union type, the result is that
4751 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004752 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4753 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004754 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004755 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004756 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004757 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004758 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004759 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004760
Chris Lattnere2949f42008-01-06 22:42:25 +00004761 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004762 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004763 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004764 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00004765 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004766
Steve Naroff039ad3c2008-01-08 01:11:38 +00004767 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4768 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004769 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4770 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004771
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004772 // All objective-c pointer type analysis is done here.
4773 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4774 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004775 if (LHS.isInvalid() || RHS.isInvalid())
4776 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004777 if (!compositeType.isNull())
4778 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004779
4780
Steve Naroff05efa972009-07-01 14:36:47 +00004781 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004782 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4783 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4784 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004785
Steve Naroff05efa972009-07-01 14:36:47 +00004786 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004787 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4788 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4789 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004790
John McCalle84af4e2010-11-13 01:35:44 +00004791 // GCC compatibility: soften pointer/integer mismatch. Note that
4792 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004793 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4794 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00004795 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004796 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4797 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00004798 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00004799
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004800 // Emit a better diagnostic if one of the expressions is a null pointer
4801 // constant and the other is not a pointer type. In this case, the user most
4802 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004803 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004804 return QualType();
4805
Chris Lattnere2949f42008-01-06 22:42:25 +00004806 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004807 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004808 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4809 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004810 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004811}
4812
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004813/// FindCompositeObjCPointerType - Helper method to find composite type of
4814/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004815QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00004816 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004817 QualType LHSTy = LHS.get()->getType();
4818 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004819
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004820 // Handle things like Class and struct objc_class*. Here we case the result
4821 // to the pseudo-builtin, because that will be implicitly cast back to the
4822 // redefinition type if an attempt is made to access its fields.
4823 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004824 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004825 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004826 return LHSTy;
4827 }
4828 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004829 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004830 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004831 return RHSTy;
4832 }
4833 // And the same for struct objc_object* / id
4834 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004835 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004836 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004837 return LHSTy;
4838 }
4839 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004840 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004841 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004842 return RHSTy;
4843 }
4844 // And the same for struct objc_selector* / SEL
4845 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004846 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004847 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004848 return LHSTy;
4849 }
4850 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004851 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004852 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004853 return RHSTy;
4854 }
4855 // Check constraints for Objective-C object pointers types.
4856 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004857
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004858 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4859 // Two identical object pointer types are always compatible.
4860 return LHSTy;
4861 }
John McCall9320b872011-09-09 05:25:32 +00004862 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
4863 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004864 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004865
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004866 // If both operands are interfaces and either operand can be
4867 // assigned to the other, use that type as the composite
4868 // type. This allows
4869 // xxx ? (A*) a : (B*) b
4870 // where B is a subclass of A.
4871 //
4872 // Additionally, as for assignment, if either type is 'id'
4873 // allow silent coercion. Finally, if the types are
4874 // incompatible then make sure to use 'id' as the composite
4875 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004876
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004877 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4878 // It could return the composite type.
4879 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4880 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4881 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4882 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4883 } else if ((LHSTy->isObjCQualifiedIdType() ||
4884 RHSTy->isObjCQualifiedIdType()) &&
4885 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4886 // Need to handle "id<xx>" explicitly.
4887 // GCC allows qualified id and any Objective-C type to devolve to
4888 // id. Currently localizing to here until clear this should be
4889 // part of ObjCQualifiedIdTypesAreCompatible.
4890 compositeType = Context.getObjCIdType();
4891 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4892 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004893 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004894 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4895 ;
4896 else {
4897 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4898 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004899 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004900 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004901 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4902 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004903 return incompatTy;
4904 }
4905 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004906 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4907 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004908 return compositeType;
4909 }
4910 // Check Objective-C object pointer types and 'void *'
4911 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4912 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4913 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4914 QualType destPointee
4915 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4916 QualType destType = Context.getPointerType(destPointee);
4917 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004918 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004919 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004920 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004921 return destType;
4922 }
4923 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4924 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4925 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4926 QualType destPointee
4927 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4928 QualType destType = Context.getPointerType(destPointee);
4929 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004930 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004931 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004932 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004933 return destType;
4934 }
4935 return QualType();
4936}
4937
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004938/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004939/// ParenRange in parentheses.
4940static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004941 const PartialDiagnostic &Note,
4942 SourceRange ParenRange) {
4943 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4944 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4945 EndLoc.isValid()) {
4946 Self.Diag(Loc, Note)
4947 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4948 << FixItHint::CreateInsertion(EndLoc, ")");
4949 } else {
4950 // We can't display the parentheses, so just show the bare note.
4951 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004952 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004953}
4954
4955static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4956 return Opc >= BO_Mul && Opc <= BO_Shr;
4957}
4958
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004959/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4960/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00004961/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
4962/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004963static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00004964 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00004965 // Don't strip parenthesis: we should not warn if E is in parenthesis.
4966 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004967 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00004968 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004969
4970 // Built-in binary operator.
4971 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4972 if (IsArithmeticOp(OP->getOpcode())) {
4973 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00004974 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004975 return true;
4976 }
4977 }
4978
4979 // Overloaded operator.
4980 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4981 if (Call->getNumArgs() != 2)
4982 return false;
4983
4984 // Make sure this is really a binary operator that is safe to pass into
4985 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4986 OverloadedOperatorKind OO = Call->getOperator();
4987 if (OO < OO_Plus || OO > OO_Arrow)
4988 return false;
4989
4990 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4991 if (IsArithmeticOp(OpKind)) {
4992 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00004993 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004994 return true;
4995 }
4996 }
4997
4998 return false;
4999}
5000
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005001static bool IsLogicOp(BinaryOperatorKind Opc) {
5002 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5003}
5004
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005005/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5006/// or is a logical expression such as (x==y) which has int type, but is
5007/// commonly interpreted as boolean.
5008static bool ExprLooksBoolean(Expr *E) {
5009 E = E->IgnoreParenImpCasts();
5010
5011 if (E->getType()->isBooleanType())
5012 return true;
5013 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5014 return IsLogicOp(OP->getOpcode());
5015 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5016 return OP->getOpcode() == UO_LNot;
5017
5018 return false;
5019}
5020
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005021/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5022/// and binary operator are mixed in a way that suggests the programmer assumed
5023/// the conditional operator has higher precedence, for example:
5024/// "int x = a + someBinaryCondition ? 1 : 2".
5025static void DiagnoseConditionalPrecedence(Sema &Self,
5026 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005027 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00005028 Expr *LHSExpr,
5029 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005030 BinaryOperatorKind CondOpcode;
5031 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005032
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005033 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005034 return;
5035 if (!ExprLooksBoolean(CondRHS))
5036 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005037
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005038 // The condition is an arithmetic binary expression, with a right-
5039 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005040
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005041 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005042 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005043 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005044
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005045 SuggestParentheses(Self, OpLoc,
5046 Self.PDiag(diag::note_precedence_conditional_silence)
5047 << BinaryOperator::getOpcodeStr(CondOpcode),
5048 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00005049
5050 SuggestParentheses(Self, OpLoc,
5051 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00005052 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005053}
5054
Steve Naroff83895f72007-09-16 03:34:24 +00005055/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005056/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005057ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005058 SourceLocation ColonLoc,
5059 Expr *CondExpr, Expr *LHSExpr,
5060 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005061 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5062 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005063 OpaqueValueExpr *opaqueValue = 0;
5064 Expr *commonExpr = 0;
5065 if (LHSExpr == 0) {
5066 commonExpr = CondExpr;
5067
5068 // We usually want to apply unary conversions *before* saving, except
5069 // in the special case of a C++ l-value conditional.
5070 if (!(getLangOptions().CPlusPlus
5071 && !commonExpr->isTypeDependent()
5072 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5073 && commonExpr->isGLValue()
5074 && commonExpr->isOrdinaryOrBitFieldObject()
5075 && RHSExpr->isOrdinaryOrBitFieldObject()
5076 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005077 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5078 if (commonRes.isInvalid())
5079 return ExprError();
5080 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005081 }
5082
5083 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5084 commonExpr->getType(),
5085 commonExpr->getValueKind(),
5086 commonExpr->getObjectKind());
5087 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005088 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005089
John McCall7decc9e2010-11-18 06:31:45 +00005090 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005091 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005092 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5093 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005094 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005095 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5096 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005097 return ExprError();
5098
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005099 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5100 RHS.get());
5101
John McCallc07a0c72011-02-17 10:25:35 +00005102 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005103 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5104 LHS.take(), ColonLoc,
5105 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005106
5107 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005108 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005109 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5110 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005111}
5112
John McCallaba90822011-01-31 23:13:11 +00005113// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005114// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005115// routine is it effectively iqnores the qualifiers on the top level pointee.
5116// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5117// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005118static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005119checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5120 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5121 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005122
Steve Naroff1f4d7272007-05-11 04:00:31 +00005123 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005124 const Type *lhptee, *rhptee;
5125 Qualifiers lhq, rhq;
Richard Trieua871b972011-09-06 20:21:22 +00005126 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5127 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005128
John McCallaba90822011-01-31 23:13:11 +00005129 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005130
5131 // C99 6.5.16.1p1: This following citation is common to constraints
5132 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5133 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005134 Qualifiers lq;
5135
John McCall31168b02011-06-15 23:02:42 +00005136 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5137 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5138 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5139 // Ignore lifetime for further calculation.
5140 lhq.removeObjCLifetime();
5141 rhq.removeObjCLifetime();
5142 }
5143
John McCall4fff8f62011-02-01 00:10:29 +00005144 if (!lhq.compatiblyIncludes(rhq)) {
5145 // Treat address-space mismatches as fatal. TODO: address subspaces
5146 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5147 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5148
John McCall31168b02011-06-15 23:02:42 +00005149 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005150 // and from void*.
John McCall31168b02011-06-15 23:02:42 +00005151 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5152 .compatiblyIncludes(
5153 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall78535952011-03-26 02:56:45 +00005154 && (lhptee->isVoidType() || rhptee->isVoidType()))
5155 ; // keep old
5156
John McCall31168b02011-06-15 23:02:42 +00005157 // Treat lifetime mismatches as fatal.
5158 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5159 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5160
John McCall4fff8f62011-02-01 00:10:29 +00005161 // For GCC compatibility, other qualifier mismatches are treated
5162 // as still compatible in C.
5163 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5164 }
Steve Naroff3f597292007-05-11 22:18:03 +00005165
Mike Stump4e1f26a2009-02-19 03:04:26 +00005166 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5167 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005168 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005169 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005170 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005171 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005172
Chris Lattner0a788432008-01-03 22:56:36 +00005173 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005174 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005175 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005176 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005177
Chris Lattner0a788432008-01-03 22:56:36 +00005178 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005179 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005180 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005181
5182 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005183 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005184 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005185 }
John McCall4fff8f62011-02-01 00:10:29 +00005186
Mike Stump4e1f26a2009-02-19 03:04:26 +00005187 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005188 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005189 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5190 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005191 // Check if the pointee types are compatible ignoring the sign.
5192 // We explicitly check for char so that we catch "char" vs
5193 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005194 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005195 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005196 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005197 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005198
Chris Lattnerec3a1562009-10-17 20:33:28 +00005199 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005200 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005201 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005202 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005203
John McCall4fff8f62011-02-01 00:10:29 +00005204 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005205 // Types are compatible ignoring the sign. Qualifier incompatibility
5206 // takes priority over sign incompatibility because the sign
5207 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005208 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005209 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005210
John McCallaba90822011-01-31 23:13:11 +00005211 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005212 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005213
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005214 // If we are a multi-level pointer, it's possible that our issue is simply
5215 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5216 // the eventual target type is the same and the pointers have the same
5217 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005218 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005219 do {
John McCall4fff8f62011-02-01 00:10:29 +00005220 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5221 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005222 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005223
John McCall4fff8f62011-02-01 00:10:29 +00005224 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005225 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005226 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005227
Eli Friedman80160bd2009-03-22 23:59:44 +00005228 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005229 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005230 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005231 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005232}
5233
John McCallaba90822011-01-31 23:13:11 +00005234/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005235/// block pointer types are compatible or whether a block and normal pointer
5236/// are compatible. It is more restrict than comparing two function pointer
5237// types.
John McCallaba90822011-01-31 23:13:11 +00005238static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005239checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5240 QualType RHSType) {
5241 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5242 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005243
Steve Naroff081c7422008-09-04 15:10:53 +00005244 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005245
Steve Naroff081c7422008-09-04 15:10:53 +00005246 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00005247 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5248 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005249
John McCallaba90822011-01-31 23:13:11 +00005250 // In C++, the types have to match exactly.
5251 if (S.getLangOptions().CPlusPlus)
5252 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005253
John McCallaba90822011-01-31 23:13:11 +00005254 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005255
Steve Naroff081c7422008-09-04 15:10:53 +00005256 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005257 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5258 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005259
Richard Trieua871b972011-09-06 20:21:22 +00005260 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005261 return Sema::IncompatibleBlockPointer;
5262
Steve Naroff081c7422008-09-04 15:10:53 +00005263 return ConvTy;
5264}
5265
John McCallaba90822011-01-31 23:13:11 +00005266/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005267/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005268static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005269checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5270 QualType RHSType) {
5271 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5272 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005273
Richard Trieua871b972011-09-06 20:21:22 +00005274 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005275 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005276 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5277 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005278 return Sema::IncompatiblePointer;
5279 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005280 }
Richard Trieua871b972011-09-06 20:21:22 +00005281 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00005282 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5283 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00005284 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00005285 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005286 }
Richard Trieua871b972011-09-06 20:21:22 +00005287 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5288 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005289
John McCallaba90822011-01-31 23:13:11 +00005290 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5291 return Sema::CompatiblePointerDiscardsQualifiers;
5292
Richard Trieua871b972011-09-06 20:21:22 +00005293 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005294 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00005295 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005296 return Sema::IncompatibleObjCQualifiedId;
5297 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005298}
5299
John McCall29600e12010-11-16 02:32:08 +00005300Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005301Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00005302 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00005303 // Fake up an opaque expression. We don't actually care about what
5304 // cast operations are required, so if CheckAssignmentConstraints
5305 // adds casts to this they'll be wasted, but fortunately that doesn't
5306 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00005307 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5308 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00005309 CastKind K = CK_Invalid;
5310
Richard Trieua871b972011-09-06 20:21:22 +00005311 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall29600e12010-11-16 02:32:08 +00005312}
5313
Mike Stump4e1f26a2009-02-19 03:04:26 +00005314/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5315/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005316/// pointers. Here are some objectionable examples that GCC considers warnings:
5317///
5318/// int a, *pint;
5319/// short *pshort;
5320/// struct foo *pfoo;
5321///
5322/// pint = pshort; // warning: assignment from incompatible pointer type
5323/// a = pint; // warning: assignment makes integer from pointer without a cast
5324/// pint = a; // warning: assignment makes pointer from integer without a cast
5325/// pint = pfoo; // warning: assignment from incompatible pointer type
5326///
5327/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005328/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005329///
John McCall8cb679e2010-11-15 09:13:47 +00005330/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005331Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00005332Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCall8cb679e2010-11-15 09:13:47 +00005333 CastKind &Kind) {
Richard Trieude4958f2011-09-06 20:30:53 +00005334 QualType RHSType = RHS.get()->getType();
5335 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00005336
Chris Lattnera52c2f22008-01-04 23:18:45 +00005337 // Get canonical types. We're not formatting these types, just comparing
5338 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00005339 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5340 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005341
John McCalle5255932011-01-31 22:28:28 +00005342 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00005343 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00005344 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005345 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005346 }
5347
Douglas Gregor6b754842008-10-28 00:22:11 +00005348 // If the left-hand side is a reference type, then we are in a
5349 // (rare!) case where we've allowed the use of references in C,
5350 // e.g., as a parameter type in a built-in function. In this case,
5351 // just make sure that the type referenced is compatible with the
5352 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00005353 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00005354 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00005355 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5356 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005357 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005358 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005359 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005360 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005361 }
John McCalle5255932011-01-31 22:28:28 +00005362
Nate Begemanbd956c42009-06-28 02:36:38 +00005363 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5364 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005365 if (LHSType->isExtVectorType()) {
5366 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005367 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00005368 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005369 // CK_VectorSplat does T -> vector T, so first cast to the
5370 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00005371 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5372 if (elType != RHSType) {
5373 Kind = PrepareScalarCast(*this, RHS, elType);
5374 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005375 }
5376 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005377 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005378 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005379 }
Mike Stump11289f42009-09-09 15:08:12 +00005380
John McCalle5255932011-01-31 22:28:28 +00005381 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005382 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5383 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005384 // Allow assignments of an AltiVec vector type to an equivalent GCC
5385 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00005386 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00005387 Kind = CK_BitCast;
5388 return Compatible;
5389 }
5390
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005391 // If we are allowing lax vector conversions, and LHS and RHS are both
5392 // vectors, the total size only needs to be the same. This is a bitcast;
5393 // no bits are changed but the result type is different.
5394 if (getLangOptions().LaxVectorConversions &&
Richard Trieude4958f2011-09-06 20:30:53 +00005395 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall3065d042010-11-15 10:08:00 +00005396 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005397 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005398 }
Chris Lattner881a2122008-01-04 23:32:24 +00005399 }
5400 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005401 }
Eli Friedman3360d892008-05-30 18:07:22 +00005402
John McCalle5255932011-01-31 22:28:28 +00005403 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00005404 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5405 !(getLangOptions().CPlusPlus && LHSType->isEnumeralType())) {
5406 Kind = PrepareScalarCast(*this, RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005407 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005408 }
Eli Friedman3360d892008-05-30 18:07:22 +00005409
John McCalle5255932011-01-31 22:28:28 +00005410 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005411 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005412 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005413 if (isa<PointerType>(RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005414 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005415 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005416 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005417
John McCalle5255932011-01-31 22:28:28 +00005418 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005419 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00005420 Kind = CK_IntegralToPointer; // FIXME: null?
5421 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005422 }
John McCalle5255932011-01-31 22:28:28 +00005423
5424 // C pointers are not compatible with ObjC object pointers,
5425 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005426 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005427 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00005428 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00005429 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00005430 return Compatible;
5431 }
5432
5433 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005434 if (RHSType->isObjCClassType() &&
5435 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005436 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005437 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005438 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005439 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00005440
John McCalle5255932011-01-31 22:28:28 +00005441 Kind = CK_BitCast;
5442 return IncompatiblePointer;
5443 }
5444
5445 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00005446 if (RHSType->getAs<BlockPointerType>()) {
5447 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00005448 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005449 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005450 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005451 }
John McCalle5255932011-01-31 22:28:28 +00005452
Steve Naroff081c7422008-09-04 15:10:53 +00005453 return Incompatible;
5454 }
5455
John McCalle5255932011-01-31 22:28:28 +00005456 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005457 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005458 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005459 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00005460 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005461 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00005462 }
5463
5464 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005465 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005466 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005467 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005468 }
5469
John McCalle5255932011-01-31 22:28:28 +00005470 // id -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005471 if (getLangOptions().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00005472 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005473 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005474 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005475
John McCalle5255932011-01-31 22:28:28 +00005476 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005477 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005478 if (RHSPT->getPointeeType()->isVoidType()) {
5479 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005480 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005481 }
John McCall8cb679e2010-11-15 09:13:47 +00005482
Chris Lattnera52c2f22008-01-04 23:18:45 +00005483 return Incompatible;
5484 }
5485
John McCalle5255932011-01-31 22:28:28 +00005486 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005487 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005488 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00005489 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005490 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005491 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00005492 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005493 if (getLangOptions().ObjCAutoRefCount &&
5494 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00005495 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005496 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005497 return result;
John McCalle5255932011-01-31 22:28:28 +00005498 }
5499
5500 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005501 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005502 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005503 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005504 }
5505
John McCalle5255932011-01-31 22:28:28 +00005506 // In general, C pointers are not compatible with ObjC object pointers,
5507 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005508 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00005509 Kind = CK_CPointerToObjCPointerCast;
5510
John McCalle5255932011-01-31 22:28:28 +00005511 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00005512 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005513 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005514 }
5515
5516 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005517 if (LHSType->isObjCClassType() &&
5518 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005519 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005520 return Compatible;
5521 }
5522
Steve Naroffaccc4882009-07-20 17:56:53 +00005523 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005524 }
John McCalle5255932011-01-31 22:28:28 +00005525
5526 // T^ -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005527 if (RHSType->isBlockPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00005528 maybeExtendBlockObject(*this, RHS);
John McCall9320b872011-09-09 05:25:32 +00005529 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005530 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005531 }
5532
Steve Naroff7cae42b2009-07-10 23:34:53 +00005533 return Incompatible;
5534 }
John McCalle5255932011-01-31 22:28:28 +00005535
5536 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005537 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005538 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005539 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005540 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005541 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005542 }
Eli Friedman3360d892008-05-30 18:07:22 +00005543
John McCalle5255932011-01-31 22:28:28 +00005544 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005545 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005546 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005547 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005548 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005549
Chris Lattnera52c2f22008-01-04 23:18:45 +00005550 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005551 }
John McCalle5255932011-01-31 22:28:28 +00005552
5553 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005554 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005555 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005556 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005557 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005558 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005559 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005560
John McCalle5255932011-01-31 22:28:28 +00005561 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005562 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005563 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005564 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005565 }
5566
Steve Naroff7cae42b2009-07-10 23:34:53 +00005567 return Incompatible;
5568 }
Eli Friedman3360d892008-05-30 18:07:22 +00005569
John McCalle5255932011-01-31 22:28:28 +00005570 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00005571 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5572 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005573 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005574 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005575 }
Bill Wendling216423b2007-05-30 06:30:29 +00005576 }
John McCalle5255932011-01-31 22:28:28 +00005577
Steve Naroff98cf3e92007-06-06 18:38:38 +00005578 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005579}
5580
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005581/// \brief Constructs a transparent union from an expression that is
5582/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005583static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5584 ExprResult &EResult, QualType UnionType,
5585 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005586 // Build an initializer list that designates the appropriate member
5587 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005588 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005589 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005590 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005591 SourceLocation());
5592 Initializer->setType(UnionType);
5593 Initializer->setInitializedFieldInUnion(Field);
5594
5595 // Build a compound literal constructing a value of the transparent
5596 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005597 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005598 EResult = S.Owned(
5599 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5600 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005601}
5602
5603Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005604Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00005605 ExprResult &RHS) {
5606 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005607
Mike Stump11289f42009-09-09 15:08:12 +00005608 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005609 // transparent_union GCC extension.
5610 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005611 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005612 return Incompatible;
5613
5614 // The field to initialize within the transparent union.
5615 RecordDecl *UD = UT->getDecl();
5616 FieldDecl *InitField = 0;
5617 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005618 for (RecordDecl::field_iterator it = UD->field_begin(),
5619 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005620 it != itend; ++it) {
5621 if (it->getType()->isPointerType()) {
5622 // If the transparent union contains a pointer type, we allow:
5623 // 1) void pointer
5624 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00005625 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00005626 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieueb299142011-09-06 20:40:12 +00005627 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005628 InitField = *it;
5629 break;
5630 }
Mike Stump11289f42009-09-09 15:08:12 +00005631
Richard Trieueb299142011-09-06 20:40:12 +00005632 if (RHS.get()->isNullPointerConstant(Context,
5633 Expr::NPC_ValueDependentIsNull)) {
5634 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5635 CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005636 InitField = *it;
5637 break;
5638 }
5639 }
5640
John McCall8cb679e2010-11-15 09:13:47 +00005641 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00005642 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005643 == Compatible) {
Richard Trieueb299142011-09-06 20:40:12 +00005644 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005645 InitField = *it;
5646 break;
5647 }
5648 }
5649
5650 if (!InitField)
5651 return Incompatible;
5652
Richard Trieueb299142011-09-06 20:40:12 +00005653 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005654 return Compatible;
5655}
5656
Chris Lattner9bad62c2008-01-04 18:04:52 +00005657Sema::AssignConvertType
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005658Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5659 bool Diagnose) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005660 if (getLangOptions().CPlusPlus) {
Richard Trieueb299142011-09-06 20:40:12 +00005661 if (!LHSType->isRecordType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005662 // C++ 5.17p3: If the left operand is not of class type, the
5663 // expression is implicitly converted (C++ 4) to the
5664 // cv-unqualified type of the left operand.
Richard Trieueb299142011-09-06 20:40:12 +00005665 ExprResult Res = PerformImplicitConversion(RHS.get(),
5666 LHSType.getUnqualifiedType(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005667 AA_Assigning, Diagnose);
John Wiegley01296292011-04-08 18:41:53 +00005668 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005669 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005670 Sema::AssignConvertType result = Compatible;
5671 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00005672 !CheckObjCARCUnavailableWeakConversion(LHSType,
5673 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005674 result = IncompatibleObjCWeakRef;
Richard Trieueb299142011-09-06 20:40:12 +00005675 RHS = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005676 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005677 }
5678
5679 // FIXME: Currently, we fall through and treat C++ classes like C
5680 // structures.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005681 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005682
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005683 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5684 // a null pointer constant.
Richard Trieueb299142011-09-06 20:40:12 +00005685 if ((LHSType->isPointerType() ||
5686 LHSType->isObjCObjectPointerType() ||
5687 LHSType->isBlockPointerType())
5688 && RHS.get()->isNullPointerConstant(Context,
5689 Expr::NPC_ValueDependentIsNull)) {
5690 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005691 return Compatible;
5692 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005693
Chris Lattnere6dcd502007-10-16 02:55:40 +00005694 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005695 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005696 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005697 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005698 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005699 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00005700 if (!LHSType->isReferenceType()) {
5701 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5702 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005703 return Incompatible;
5704 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005705
John McCall8cb679e2010-11-15 09:13:47 +00005706 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005707 Sema::AssignConvertType result =
Richard Trieueb299142011-09-06 20:40:12 +00005708 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005709
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005710 // C99 6.5.16.1p2: The value of the right operand is converted to the
5711 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005712 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5713 // so that we can use references in built-in functions even in C.
5714 // The getNonReferenceType() call makes sure that the resulting expression
5715 // does not have reference type.
Richard Trieueb299142011-09-06 20:40:12 +00005716 if (result != Incompatible && RHS.get()->getType() != LHSType)
5717 RHS = ImpCastExprToType(RHS.take(),
5718 LHSType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005719 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005720}
5721
Richard Trieueb299142011-09-06 20:40:12 +00005722QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5723 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005724 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00005725 << LHS.get()->getType() << RHS.get()->getType()
5726 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005727 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005728}
5729
Richard Trieu859d23f2011-09-06 21:01:04 +00005730QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00005731 SourceLocation Loc, bool IsCompAssign) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005732 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005733 // For example, "const float" and "float" are equivalent.
Richard Trieu859d23f2011-09-06 21:01:04 +00005734 QualType LHSType =
5735 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5736 QualType RHSType =
5737 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005738
Nate Begeman191a6b12008-07-14 18:02:46 +00005739 // If the vector types are identical, return.
Richard Trieu859d23f2011-09-06 21:01:04 +00005740 if (LHSType == RHSType)
5741 return LHSType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005742
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005743 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu859d23f2011-09-06 21:01:04 +00005744 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5745 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5746 if (LHSType->isExtVectorType()) {
5747 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5748 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005749 }
5750
Richard Trieuba63ce62011-09-09 01:45:06 +00005751 if (!IsCompAssign)
Richard Trieu859d23f2011-09-06 21:01:04 +00005752 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5753 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005754 }
5755
Eli Friedman1408bc92011-06-23 18:10:35 +00005756 if (getLangOptions().LaxVectorConversions &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005757 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005758 // If we are allowing lax vector conversions, and LHS and RHS are both
5759 // vectors, the total size only needs to be the same. This is a
5760 // bitcast; no bits are changed but the result type is different.
5761 // FIXME: Should we really be allowing this?
Richard Trieu859d23f2011-09-06 21:01:04 +00005762 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5763 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005764 }
5765
Nate Begemanbd956c42009-06-28 02:36:38 +00005766 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5767 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5768 bool swapped = false;
Richard Trieuba63ce62011-09-09 01:45:06 +00005769 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005770 swapped = true;
Richard Trieu859d23f2011-09-06 21:01:04 +00005771 std::swap(RHS, LHS);
5772 std::swap(RHSType, LHSType);
Nate Begemanbd956c42009-06-28 02:36:38 +00005773 }
Mike Stump11289f42009-09-09 15:08:12 +00005774
Nate Begeman886448d2009-06-28 19:12:57 +00005775 // Handle the case of an ext vector and scalar.
Richard Trieu859d23f2011-09-06 21:01:04 +00005776 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005777 QualType EltTy = LV->getElementType();
Richard Trieu859d23f2011-09-06 21:01:04 +00005778 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5779 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005780 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005781 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005782 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005783 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5784 if (swapped) std::swap(RHS, LHS);
5785 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005786 }
5787 }
Richard Trieu859d23f2011-09-06 21:01:04 +00005788 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5789 RHSType->isRealFloatingType()) {
5790 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005791 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005792 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005793 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005794 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5795 if (swapped) std::swap(RHS, LHS);
5796 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005797 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005798 }
5799 }
Mike Stump11289f42009-09-09 15:08:12 +00005800
Nate Begeman886448d2009-06-28 19:12:57 +00005801 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu859d23f2011-09-06 21:01:04 +00005802 if (swapped) std::swap(RHS, LHS);
Chris Lattner377d1f82008-11-18 22:52:51 +00005803 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu859d23f2011-09-06 21:01:04 +00005804 << LHS.get()->getType() << RHS.get()->getType()
5805 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005806 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005807}
5808
Richard Trieuf8916e12011-09-16 00:53:10 +00005809// checkArithmeticNull - Detect when a NULL constant is used improperly in an
5810// expression. These are mainly cases where the null pointer is used as an
5811// integer instead of a pointer.
5812static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
5813 SourceLocation Loc, bool IsCompare) {
5814 // The canonical way to check for a GNU null is with isNullPointerConstant,
5815 // but we use a bit of a hack here for speed; this is a relatively
5816 // hot path, and isNullPointerConstant is slow.
5817 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
5818 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
5819
5820 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
5821
5822 // Avoid analyzing cases where the result will either be invalid (and
5823 // diagnosed as such) or entirely valid and not something to warn about.
5824 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
5825 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
5826 return;
5827
5828 // Comparison operations would not make sense with a null pointer no matter
5829 // what the other expression is.
5830 if (!IsCompare) {
5831 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
5832 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
5833 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
5834 return;
5835 }
5836
5837 // The rest of the operations only make sense with a null pointer
5838 // if the other expression is a pointer.
5839 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
5840 NonNullType->canDecayToPointerType())
5841 return;
5842
5843 S.Diag(Loc, diag::warn_null_in_comparison_operation)
5844 << LHSNull /* LHS is NULL */ << NonNullType
5845 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5846}
5847
Richard Trieu859d23f2011-09-06 21:01:04 +00005848QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00005849 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00005850 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005851 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5852
Richard Trieu859d23f2011-09-06 21:01:04 +00005853 if (LHS.get()->getType()->isVectorType() ||
5854 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00005855 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005856
Richard Trieuba63ce62011-09-09 01:45:06 +00005857 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005858 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005859 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005860
Richard Trieu859d23f2011-09-06 21:01:04 +00005861 if (!LHS.get()->getType()->isArithmeticType() ||
5862 !RHS.get()->getType()->isArithmeticType())
5863 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005864
Chris Lattnerfaa54172010-01-12 21:23:57 +00005865 // Check for division by zero.
Richard Trieuba63ce62011-09-09 01:45:06 +00005866 if (IsDiv &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005867 RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005868 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005869 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
5870 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005871
Chris Lattnerfaa54172010-01-12 21:23:57 +00005872 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005873}
5874
Chris Lattnerfaa54172010-01-12 21:23:57 +00005875QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00005876 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005877 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5878
Richard Trieu859d23f2011-09-06 21:01:04 +00005879 if (LHS.get()->getType()->isVectorType() ||
5880 RHS.get()->getType()->isVectorType()) {
5881 if (LHS.get()->getType()->hasIntegerRepresentation() &&
5882 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00005883 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005884 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005885 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005886
Richard Trieuba63ce62011-09-09 01:45:06 +00005887 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005888 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005889 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005890
Richard Trieu859d23f2011-09-06 21:01:04 +00005891 if (!LHS.get()->getType()->isIntegerType() ||
5892 !RHS.get()->getType()->isIntegerType())
5893 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005894
Chris Lattnerfaa54172010-01-12 21:23:57 +00005895 // Check for remainder by zero.
Richard Trieu859d23f2011-09-06 21:01:04 +00005896 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005897 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005898 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
5899 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005900
Chris Lattnerfaa54172010-01-12 21:23:57 +00005901 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005902}
5903
Chandler Carruthc9332212011-06-27 08:02:19 +00005904/// \brief Diagnose invalid arithmetic on two void pointers.
5905static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00005906 Expr *LHSExpr, Expr *RHSExpr) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005907 S.Diag(Loc, S.getLangOptions().CPlusPlus
5908 ? diag::err_typecheck_pointer_arith_void_type
5909 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00005910 << 1 /* two pointers */ << LHSExpr->getSourceRange()
5911 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00005912}
5913
5914/// \brief Diagnose invalid arithmetic on a void pointer.
5915static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5916 Expr *Pointer) {
5917 S.Diag(Loc, S.getLangOptions().CPlusPlus
5918 ? diag::err_typecheck_pointer_arith_void_type
5919 : diag::ext_gnu_void_ptr)
5920 << 0 /* one pointer */ << Pointer->getSourceRange();
5921}
5922
5923/// \brief Diagnose invalid arithmetic on two function pointers.
5924static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5925 Expr *LHS, Expr *RHS) {
5926 assert(LHS->getType()->isAnyPointerType());
5927 assert(RHS->getType()->isAnyPointerType());
5928 S.Diag(Loc, S.getLangOptions().CPlusPlus
5929 ? diag::err_typecheck_pointer_arith_function_type
5930 : diag::ext_gnu_ptr_func_arith)
5931 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5932 // We only show the second type if it differs from the first.
5933 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5934 RHS->getType())
5935 << RHS->getType()->getPointeeType()
5936 << LHS->getSourceRange() << RHS->getSourceRange();
5937}
5938
5939/// \brief Diagnose invalid arithmetic on a function pointer.
5940static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5941 Expr *Pointer) {
5942 assert(Pointer->getType()->isAnyPointerType());
5943 S.Diag(Loc, S.getLangOptions().CPlusPlus
5944 ? diag::err_typecheck_pointer_arith_function_type
5945 : diag::ext_gnu_ptr_func_arith)
5946 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5947 << 0 /* one pointer, so only one type */
5948 << Pointer->getSourceRange();
5949}
5950
Richard Trieu993f3ab2011-09-12 18:08:02 +00005951/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00005952///
5953/// \returns True if pointer has incomplete type
5954static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
5955 Expr *Operand) {
5956 if ((Operand->getType()->isPointerType() &&
5957 !Operand->getType()->isDependentType()) ||
5958 Operand->getType()->isObjCObjectPointerType()) {
5959 QualType PointeeTy = Operand->getType()->getPointeeType();
5960 if (S.RequireCompleteType(
5961 Loc, PointeeTy,
5962 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5963 << PointeeTy << Operand->getSourceRange()))
5964 return true;
5965 }
5966 return false;
5967}
5968
Chandler Carruthc9332212011-06-27 08:02:19 +00005969/// \brief Check the validity of an arithmetic pointer operand.
5970///
5971/// If the operand has pointer type, this code will check for pointer types
5972/// which are invalid in arithmetic operations. These will be diagnosed
5973/// appropriately, including whether or not the use is supported as an
5974/// extension.
5975///
5976/// \returns True when the operand is valid to use (even if as an extension).
5977static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5978 Expr *Operand) {
5979 if (!Operand->getType()->isAnyPointerType()) return true;
5980
5981 QualType PointeeTy = Operand->getType()->getPointeeType();
5982 if (PointeeTy->isVoidType()) {
5983 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5984 return !S.getLangOptions().CPlusPlus;
5985 }
5986 if (PointeeTy->isFunctionType()) {
5987 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5988 return !S.getLangOptions().CPlusPlus;
5989 }
5990
Richard Trieuaba22802011-09-02 02:15:37 +00005991 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00005992
5993 return true;
5994}
5995
5996/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5997/// operands.
5998///
5999/// This routine will diagnose any invalid arithmetic on pointer operands much
6000/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6001/// for emitting a single diagnostic even for operations where both LHS and RHS
6002/// are (potentially problematic) pointers.
6003///
6004/// \returns True when the operand is valid to use (even if as an extension).
6005static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006006 Expr *LHSExpr, Expr *RHSExpr) {
6007 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6008 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006009 if (!isLHSPointer && !isRHSPointer) return true;
6010
6011 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00006012 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6013 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006014
6015 // Check for arithmetic on pointers to incomplete types.
6016 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6017 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6018 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006019 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6020 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6021 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006022
6023 return !S.getLangOptions().CPlusPlus;
6024 }
6025
6026 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6027 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6028 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006029 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6030 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6031 RHSExpr);
6032 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006033
6034 return !S.getLangOptions().CPlusPlus;
6035 }
6036
Richard Trieu4ae7e972011-09-06 21:13:51 +00006037 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
6038 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
Richard Trieuaba22802011-09-02 02:15:37 +00006039
Chandler Carruthc9332212011-06-27 08:02:19 +00006040 return true;
6041}
6042
Richard Trieub10c6312011-09-01 22:53:23 +00006043/// \brief Check bad cases where we step over interface counts.
6044static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
6045 SourceLocation OpLoc,
6046 Expr *Op) {
6047 assert(Op->getType()->isAnyPointerType());
6048 QualType PointeeTy = Op->getType()->getPointeeType();
6049 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
6050 return true;
6051
6052 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6053 << PointeeTy << Op->getSourceRange();
6054 return false;
6055}
6056
Richard Trieu993f3ab2011-09-12 18:08:02 +00006057/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00006058static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006059 Expr *LHSExpr, Expr *RHSExpr) {
6060 assert(LHSExpr->getType()->isAnyPointerType());
6061 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00006062 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006063 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6064 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00006065}
6066
Chris Lattnerfaa54172010-01-12 21:23:57 +00006067QualType Sema::CheckAdditionOperands( // C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006068 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006069 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6070
Richard Trieu4ae7e972011-09-06 21:13:51 +00006071 if (LHS.get()->getType()->isVectorType() ||
6072 RHS.get()->getType()->isVectorType()) {
6073 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006074 if (CompLHSTy) *CompLHSTy = compType;
6075 return compType;
6076 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006077
Richard Trieu4ae7e972011-09-06 21:13:51 +00006078 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6079 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006080 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006081
Steve Naroffe4718892007-04-27 18:30:00 +00006082 // handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006083 if (LHS.get()->getType()->isArithmeticType() &&
6084 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006085 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006086 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006087 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006088
Eli Friedman8e122982008-05-18 18:08:51 +00006089 // Put any potential pointer into PExp
Richard Trieu4ae7e972011-09-06 21:13:51 +00006090 Expr* PExp = LHS.get(), *IExp = RHS.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00006091 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006092 std::swap(PExp, IExp);
6093
Richard Trieub420bca2011-09-12 18:37:54 +00006094 if (!PExp->getType()->isAnyPointerType())
6095 return InvalidOperands(Loc, LHS, RHS);
Chandler Carruthc9332212011-06-27 08:02:19 +00006096
Richard Trieub420bca2011-09-12 18:37:54 +00006097 if (!IExp->getType()->isIntegerType())
6098 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006099
Richard Trieub420bca2011-09-12 18:37:54 +00006100 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6101 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006102
Richard Trieub420bca2011-09-12 18:37:54 +00006103 // Diagnose bad cases where we step over interface counts.
6104 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6105 return QualType();
6106
6107 // Check array bounds for pointer arithemtic
6108 CheckArrayAccess(PExp, IExp);
6109
6110 if (CompLHSTy) {
6111 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6112 if (LHSTy.isNull()) {
6113 LHSTy = LHS.get()->getType();
6114 if (LHSTy->isPromotableIntegerType())
6115 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006116 }
Richard Trieub420bca2011-09-12 18:37:54 +00006117 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00006118 }
6119
Richard Trieub420bca2011-09-12 18:37:54 +00006120 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006121}
6122
Chris Lattner2a3569b2008-04-07 05:30:13 +00006123// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006124QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006125 SourceLocation Loc,
6126 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006127 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6128
Richard Trieu4ae7e972011-09-06 21:13:51 +00006129 if (LHS.get()->getType()->isVectorType() ||
6130 RHS.get()->getType()->isVectorType()) {
6131 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006132 if (CompLHSTy) *CompLHSTy = compType;
6133 return compType;
6134 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006135
Richard Trieu4ae7e972011-09-06 21:13:51 +00006136 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6137 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006138 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006139
Chris Lattner4d62f422007-12-09 21:53:25 +00006140 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006141
Chris Lattner4d62f422007-12-09 21:53:25 +00006142 // Handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006143 if (LHS.get()->getType()->isArithmeticType() &&
6144 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006145 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006146 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006147 }
Mike Stump11289f42009-09-09 15:08:12 +00006148
Chris Lattner4d62f422007-12-09 21:53:25 +00006149 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006150 if (LHS.get()->getType()->isAnyPointerType()) {
6151 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006152
Chris Lattner12bdebb2009-04-24 23:50:08 +00006153 // Diagnose bad cases where we step over interface counts.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006154 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006155 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006156
Chris Lattner4d62f422007-12-09 21:53:25 +00006157 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006158 if (RHS.get()->getType()->isIntegerType()) {
6159 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006160 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006161
Richard Trieu4ae7e972011-09-06 21:13:51 +00006162 Expr *IExpr = RHS.get()->IgnoreParenCasts();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006163 UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6164 OK_Ordinary, IExpr->getExprLoc());
6165 // Check array bounds for pointer arithemtic
Richard Trieu4ae7e972011-09-06 21:13:51 +00006166 CheckArrayAccess(LHS.get()->IgnoreParenCasts(), &negRex);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006167
Richard Trieu4ae7e972011-09-06 21:13:51 +00006168 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6169 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006170 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006171
Chris Lattner4d62f422007-12-09 21:53:25 +00006172 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006173 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00006174 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006175 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006176
Eli Friedman168fe152009-05-16 13:54:38 +00006177 if (getLangOptions().CPlusPlus) {
6178 // Pointee types must be the same: C++ [expr.add]
6179 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006180 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006181 }
6182 } else {
6183 // Pointee types must be compatible C99 6.5.6p3
6184 if (!Context.typesAreCompatible(
6185 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6186 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006187 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006188 return QualType();
6189 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006190 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006191
Chandler Carruthc9332212011-06-27 08:02:19 +00006192 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006193 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006194 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006195
Richard Trieu4ae7e972011-09-06 21:13:51 +00006196 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006197 return Context.getPointerDiffType();
6198 }
6199 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006200
Richard Trieu4ae7e972011-09-06 21:13:51 +00006201 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006202}
6203
Douglas Gregor0bf31402010-10-08 23:50:27 +00006204static bool isScopedEnumerationType(QualType T) {
6205 if (const EnumType *ET = dyn_cast<EnumType>(T))
6206 return ET->getDecl()->isScoped();
6207 return false;
6208}
6209
Richard Trieue4a19fb2011-09-06 21:21:28 +00006210static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006211 SourceLocation Loc, unsigned Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00006212 QualType LHSType) {
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006213 llvm::APSInt Right;
6214 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00006215 if (RHS.get()->isValueDependent() ||
6216 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006217 return;
6218
6219 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006220 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006221 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006222 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006223 return;
6224 }
6225 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00006226 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006227 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006228 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006229 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006230 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006231 return;
6232 }
6233 if (Opc != BO_Shl)
6234 return;
6235
6236 // When left shifting an ICE which is signed, we can check for overflow which
6237 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6238 // integers have defined behavior modulo one more than the maximum value
6239 // representable in the result type, so never warn for those.
6240 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00006241 if (LHS.get()->isValueDependent() ||
6242 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6243 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006244 return;
6245 llvm::APInt ResultBits =
6246 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6247 if (LeftBits.uge(ResultBits))
6248 return;
6249 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6250 Result = Result.shl(Right);
6251
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006252 // Print the bit representation of the signed integer as an unsigned
6253 // hexadecimal number.
6254 llvm::SmallString<40> HexResult;
6255 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6256
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006257 // If we are only missing a sign bit, this is less likely to result in actual
6258 // bugs -- if the result is cast back to an unsigned type, it will have the
6259 // expected value. Thus we place this behind a different warning that can be
6260 // turned off separately if needed.
6261 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006262 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006263 << HexResult.str() << LHSType
6264 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006265 return;
6266 }
6267
6268 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006269 << HexResult.str() << Result.getMinSignedBits() << LHSType
6270 << Left.getBitWidth() << LHS.get()->getSourceRange()
6271 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006272}
6273
Chris Lattner2a3569b2008-04-07 05:30:13 +00006274// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00006275QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006276 SourceLocation Loc, unsigned Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006277 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006278 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6279
Chris Lattner5c11c412007-12-12 05:47:28 +00006280 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006281 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6282 !RHS.get()->getType()->hasIntegerRepresentation())
6283 return InvalidOperands(Loc, LHS, RHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006284
Douglas Gregor0bf31402010-10-08 23:50:27 +00006285 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6286 // hasIntegerRepresentation() above instead of this.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006287 if (isScopedEnumerationType(LHS.get()->getType()) ||
6288 isScopedEnumerationType(RHS.get()->getType())) {
6289 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006290 }
6291
Nate Begemane46ee9a2009-10-25 02:26:48 +00006292 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006293 if (LHS.get()->getType()->isVectorType() ||
6294 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006295 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006296
Chris Lattner5c11c412007-12-12 05:47:28 +00006297 // Shifts don't perform usual arithmetic conversions, they just do integer
6298 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006299
John McCall57cdd882010-12-16 19:28:59 +00006300 // For the LHS, do usual unary conversions, but then reset them away
6301 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006302 ExprResult OldLHS = LHS;
6303 LHS = UsualUnaryConversions(LHS.take());
6304 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006305 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00006306 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00006307 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00006308
6309 // The RHS is simpler.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006310 RHS = UsualUnaryConversions(RHS.take());
6311 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006312 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006313
Ryan Flynnf53fab82009-08-07 16:20:20 +00006314 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00006315 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006316
Chris Lattner5c11c412007-12-12 05:47:28 +00006317 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00006318 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006319}
6320
Chandler Carruth17773fc2010-07-10 12:30:03 +00006321static bool IsWithinTemplateSpecialization(Decl *D) {
6322 if (DeclContext *DC = D->getDeclContext()) {
6323 if (isa<ClassTemplateSpecializationDecl>(DC))
6324 return true;
6325 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6326 return FD->isFunctionTemplateSpecialization();
6327 }
6328 return false;
6329}
6330
Richard Trieueea56f72011-09-02 03:48:46 +00006331/// If two different enums are compared, raise a warning.
Richard Trieu1762d7c2011-09-06 21:27:33 +00006332static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6333 ExprResult &RHS) {
6334 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6335 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00006336
6337 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6338 if (!LHSEnumType)
6339 return;
6340 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6341 if (!RHSEnumType)
6342 return;
6343
6344 // Ignore anonymous enums.
6345 if (!LHSEnumType->getDecl()->getIdentifier())
6346 return;
6347 if (!RHSEnumType->getDecl()->getIdentifier())
6348 return;
6349
6350 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6351 return;
6352
6353 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6354 << LHSStrippedType << RHSStrippedType
Richard Trieu1762d7c2011-09-06 21:27:33 +00006355 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00006356}
6357
Richard Trieudd82a5c2011-09-02 02:55:45 +00006358/// \brief Diagnose bad pointer comparisons.
6359static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006360 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006361 bool IsError) {
6362 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00006363 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006364 << LHS.get()->getType() << RHS.get()->getType()
6365 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006366}
6367
6368/// \brief Returns false if the pointers are converted to a composite type,
6369/// true otherwise.
6370static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006371 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006372 // C++ [expr.rel]p2:
6373 // [...] Pointer conversions (4.10) and qualification
6374 // conversions (4.4) are performed on pointer operands (or on
6375 // a pointer operand and a null pointer constant) to bring
6376 // them to their composite pointer type. [...]
6377 //
6378 // C++ [expr.eq]p1 uses the same notion for (in)equality
6379 // comparisons of pointers.
6380
6381 // C++ [expr.eq]p2:
6382 // In addition, pointers to members can be compared, or a pointer to
6383 // member and a null pointer constant. Pointer to member conversions
6384 // (4.11) and qualification conversions (4.4) are performed to bring
6385 // them to a common type. If one operand is a null pointer constant,
6386 // the common type is the type of the other operand. Otherwise, the
6387 // common type is a pointer to member type similar (4.4) to the type
6388 // of one of the operands, with a cv-qualification signature (4.4)
6389 // that is the union of the cv-qualification signatures of the operand
6390 // types.
6391
Richard Trieu1762d7c2011-09-06 21:27:33 +00006392 QualType LHSType = LHS.get()->getType();
6393 QualType RHSType = RHS.get()->getType();
6394 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6395 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00006396
6397 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00006398 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00006399 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006400 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00006401 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006402 return true;
6403 }
6404
6405 if (NonStandardCompositeType)
6406 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006407 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6408 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006409
Richard Trieu1762d7c2011-09-06 21:27:33 +00006410 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6411 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006412 return false;
6413}
6414
6415static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006416 ExprResult &LHS,
6417 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006418 bool IsError) {
6419 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6420 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006421 << LHS.get()->getType() << RHS.get()->getType()
6422 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006423}
6424
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006425// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00006426QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006427 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006428 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006429 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6430
John McCalle3027922010-08-25 11:45:40 +00006431 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006432
Chris Lattner9a152e22009-12-05 05:40:13 +00006433 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00006434 if (LHS.get()->getType()->isVectorType() ||
6435 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006436 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006437
Richard Trieub80728f2011-09-06 21:43:51 +00006438 QualType LHSType = LHS.get()->getType();
6439 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00006440
Richard Trieub80728f2011-09-06 21:43:51 +00006441 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6442 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006443
Richard Trieub80728f2011-09-06 21:43:51 +00006444 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth712563b2011-02-17 08:37:06 +00006445
Richard Trieub80728f2011-09-06 21:43:51 +00006446 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00006447 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00006448 !LHS.get()->getLocStart().isMacroID() &&
6449 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006450 // For non-floating point types, check for self-comparisons of the form
6451 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6452 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006453 //
6454 // NOTE: Don't warn about comparison expressions resulting from macro
6455 // expansion. Also don't warn about comparisons which are only self
6456 // comparisons within a template specialization. The warnings should catch
6457 // obvious cases in the definition of the template anyways. The idea is to
6458 // warn when the typed comparison operator will always evaluate to the same
6459 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006460 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006461 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006462 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006463 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006464 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006465 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006466 << (Opc == BO_EQ
6467 || Opc == BO_LE
6468 || Opc == BO_GE));
Richard Trieub80728f2011-09-06 21:43:51 +00006469 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregorec170db2010-06-08 19:50:34 +00006470 !DRL->getDecl()->getType()->isReferenceType() &&
6471 !DRR->getDecl()->getType()->isReferenceType()) {
6472 // what is it always going to eval to?
6473 char always_evals_to;
6474 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006475 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006476 always_evals_to = 0; // false
6477 break;
John McCalle3027922010-08-25 11:45:40 +00006478 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006479 always_evals_to = 1; // true
6480 break;
6481 default:
6482 // best we can say is 'a constant'
6483 always_evals_to = 2; // e.g. array1 <= array2
6484 break;
6485 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006486 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006487 << 1 // array
6488 << always_evals_to);
6489 }
6490 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006491 }
Mike Stump11289f42009-09-09 15:08:12 +00006492
Chris Lattner222b8bd2009-03-08 19:39:53 +00006493 if (isa<CastExpr>(LHSStripped))
6494 LHSStripped = LHSStripped->IgnoreParenCasts();
6495 if (isa<CastExpr>(RHSStripped))
6496 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006497
Chris Lattner222b8bd2009-03-08 19:39:53 +00006498 // Warn about comparisons against a string constant (unless the other
6499 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006500 Expr *literalString = 0;
6501 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006502 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006503 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006504 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006505 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006506 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006507 } else if ((isa<StringLiteral>(RHSStripped) ||
6508 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006509 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006510 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006511 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006512 literalStringStripped = RHSStripped;
6513 }
6514
6515 if (literalString) {
6516 std::string resultComparison;
6517 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006518 case BO_LT: resultComparison = ") < 0"; break;
6519 case BO_GT: resultComparison = ") > 0"; break;
6520 case BO_LE: resultComparison = ") <= 0"; break;
6521 case BO_GE: resultComparison = ") >= 0"; break;
6522 case BO_EQ: resultComparison = ") == 0"; break;
6523 case BO_NE: resultComparison = ") != 0"; break;
David Blaikie83d382b2011-09-23 05:06:16 +00006524 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006525 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006526
Ted Kremenek3427fac2011-02-23 01:52:04 +00006527 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006528 PDiag(diag::warn_stringcompare)
6529 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006530 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006531 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006532 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006533
Douglas Gregorec170db2010-06-08 19:50:34 +00006534 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieub80728f2011-09-06 21:43:51 +00006535 if (LHS.get()->getType()->isArithmeticType() &&
6536 RHS.get()->getType()->isArithmeticType()) {
6537 UsualArithmeticConversions(LHS, RHS);
6538 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006539 return QualType();
6540 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006541 else {
Richard Trieub80728f2011-09-06 21:43:51 +00006542 LHS = UsualUnaryConversions(LHS.take());
6543 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006544 return QualType();
6545
Richard Trieub80728f2011-09-06 21:43:51 +00006546 RHS = UsualUnaryConversions(RHS.take());
6547 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006548 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006549 }
6550
Richard Trieub80728f2011-09-06 21:43:51 +00006551 LHSType = LHS.get()->getType();
6552 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006553
Douglas Gregorca63811b2008-11-19 03:25:36 +00006554 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006555 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006556
Richard Trieuba63ce62011-09-09 01:45:06 +00006557 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00006558 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006559 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006560 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006561 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00006562 if (LHSType->hasFloatingRepresentation())
6563 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006564
Richard Trieub80728f2011-09-06 21:43:51 +00006565 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006566 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006567 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006568
Richard Trieub80728f2011-09-06 21:43:51 +00006569 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006570 Expr::NPC_ValueDependentIsNull);
Richard Trieub80728f2011-09-06 21:43:51 +00006571 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006572 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006573
Douglas Gregorf267edd2010-06-15 21:38:40 +00006574 // All of the following pointer-related warnings are GCC extensions, except
6575 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00006576 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006577 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006578 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00006579 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006580 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006581
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006582 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006583 if (LCanPointeeTy == RCanPointeeTy)
6584 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00006585 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006586 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6587 // Valid unless comparison between non-null pointer and function pointer
6588 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006589 // In a SFINAE context, we treat this as a hard error to maintain
6590 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006591 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6592 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006593 diagnoseFunctionPointerToVoidComparison(
Richard Trieub80728f2011-09-06 21:43:51 +00006594 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00006595
6596 if (isSFINAEContext())
6597 return QualType();
6598
Richard Trieub80728f2011-09-06 21:43:51 +00006599 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006600 return ResultTy;
6601 }
6602 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006603
Richard Trieub80728f2011-09-06 21:43:51 +00006604 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006605 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006606 else
6607 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006608 }
Eli Friedman16c209612009-08-23 00:27:47 +00006609 // C99 6.5.9p2 and C99 6.5.8p2
6610 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6611 RCanPointeeTy.getUnqualifiedType())) {
6612 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00006613 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00006614 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00006615 << LHSType << RHSType << LHS.get()->getSourceRange()
6616 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006617 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006618 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00006619 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6620 // Valid unless comparison between non-null pointer and function pointer
6621 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00006622 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006623 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006624 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00006625 } else {
6626 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00006627 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00006628 }
John McCall7684dde2011-03-11 04:25:25 +00006629 if (LCanPointeeTy != RCanPointeeTy) {
6630 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006631 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006632 else
Richard Trieub80728f2011-09-06 21:43:51 +00006633 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006634 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006635 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006636 }
Mike Stump11289f42009-09-09 15:08:12 +00006637
Sebastian Redl576fd422009-05-10 18:38:11 +00006638 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006639 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00006640 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00006641 return ResultTy;
6642
Mike Stump11289f42009-09-09 15:08:12 +00006643 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006644 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006645 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006646 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006647 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006648 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
6649 RHS = ImpCastExprToType(RHS.take(), LHSType,
6650 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006651 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006652 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006653 return ResultTy;
6654 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006655 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006656 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006657 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006658 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
6659 LHS = ImpCastExprToType(LHS.take(), RHSType,
6660 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006661 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006662 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006663 return ResultTy;
6664 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006665
6666 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006667 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006668 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
6669 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006670 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006671 else
6672 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006673 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006674
6675 // Handle scoped enumeration types specifically, since they don't promote
6676 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00006677 if (LHS.get()->getType()->isEnumeralType() &&
6678 Context.hasSameUnqualifiedType(LHS.get()->getType(),
6679 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006680 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00006681 }
Mike Stump11289f42009-09-09 15:08:12 +00006682
Steve Naroff081c7422008-09-04 15:10:53 +00006683 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00006684 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00006685 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00006686 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
6687 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006688
Steve Naroff081c7422008-09-04 15:10:53 +00006689 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006690 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006691 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006692 << LHSType << RHSType << LHS.get()->getSourceRange()
6693 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006694 }
Richard Trieub80728f2011-09-06 21:43:51 +00006695 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006696 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006697 }
John Wiegley01296292011-04-08 18:41:53 +00006698
Steve Naroffe18f94c2008-09-28 01:11:11 +00006699 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00006700 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00006701 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
6702 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006703 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00006704 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006705 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00006706 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006707 ->getPointeeType()->isVoidType())))
6708 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006709 << LHSType << RHSType << LHS.get()->getSourceRange()
6710 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006711 }
John McCall7684dde2011-03-11 04:25:25 +00006712 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006713 LHS = ImpCastExprToType(LHS.take(), RHSType,
6714 RHSType->isPointerType() ? CK_BitCast
6715 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006716 else
John McCall9320b872011-09-09 05:25:32 +00006717 RHS = ImpCastExprToType(RHS.take(), LHSType,
6718 LHSType->isPointerType() ? CK_BitCast
6719 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006720 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006721 }
Steve Naroff081c7422008-09-04 15:10:53 +00006722
Richard Trieub80728f2011-09-06 21:43:51 +00006723 if (LHSType->isObjCObjectPointerType() ||
6724 RHSType->isObjCObjectPointerType()) {
6725 const PointerType *LPT = LHSType->getAs<PointerType>();
6726 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00006727 if (LPT || RPT) {
6728 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6729 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006730
Steve Naroff753567f2008-11-17 19:49:16 +00006731 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00006732 !Context.typesAreCompatible(LHSType, RHSType)) {
6733 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006734 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006735 }
John McCall7684dde2011-03-11 04:25:25 +00006736 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006737 LHS = ImpCastExprToType(LHS.take(), RHSType,
6738 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006739 else
John McCall9320b872011-09-09 05:25:32 +00006740 RHS = ImpCastExprToType(RHS.take(), LHSType,
6741 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006742 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006743 }
Richard Trieub80728f2011-09-06 21:43:51 +00006744 if (LHSType->isObjCObjectPointerType() &&
6745 RHSType->isObjCObjectPointerType()) {
6746 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
6747 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006748 /*isError*/false);
John McCall7684dde2011-03-11 04:25:25 +00006749 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006750 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006751 else
Richard Trieub80728f2011-09-06 21:43:51 +00006752 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006753 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006754 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006755 }
Richard Trieub80728f2011-09-06 21:43:51 +00006756 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
6757 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006758 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006759 bool isError = false;
Richard Trieub80728f2011-09-06 21:43:51 +00006760 if ((LHSIsNull && LHSType->isIntegerType()) ||
6761 (RHSIsNull && RHSType->isIntegerType())) {
Richard Trieuba63ce62011-09-09 01:45:06 +00006762 if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006763 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Richard Trieuba63ce62011-09-09 01:45:06 +00006764 } else if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006765 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006766 else if (getLangOptions().CPlusPlus) {
6767 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6768 isError = true;
6769 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006770 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006771
Chris Lattnerd99bd522009-08-23 00:03:44 +00006772 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006773 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00006774 << LHSType << RHSType << LHS.get()->getSourceRange()
6775 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006776 if (isError)
6777 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006778 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006779
Richard Trieub80728f2011-09-06 21:43:51 +00006780 if (LHSType->isIntegerType())
6781 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006782 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006783 else
Richard Trieub80728f2011-09-06 21:43:51 +00006784 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006785 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006786 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006787 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006788
Steve Naroff4b191572008-09-04 16:56:14 +00006789 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006790 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006791 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
6792 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006793 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006794 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006795 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006796 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
6797 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006798 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006799 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006800
Richard Trieub80728f2011-09-06 21:43:51 +00006801 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006802}
6803
Nate Begeman191a6b12008-07-14 18:02:46 +00006804/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006805/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006806/// like a scalar comparison, a vector comparison produces a vector of integer
6807/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00006808QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00006809 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006810 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006811 // Check to make sure we're operating on vectors of the same type and width,
6812 // Allowing one side to be a scalar of element type.
Richard Trieubcce2f72011-09-07 01:19:57 +00006813 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00006814 if (vType.isNull())
6815 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006816
Richard Trieubcce2f72011-09-07 01:19:57 +00006817 QualType LHSType = LHS.get()->getType();
6818 QualType RHSType = RHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006819
Anton Yartsev530deb92011-03-27 15:36:07 +00006820 // If AltiVec, the comparison results in a numeric type, i.e.
6821 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00006822 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00006823 return Context.getLogicalOperationType();
6824
Nate Begeman191a6b12008-07-14 18:02:46 +00006825 // For non-floating point types, check for self-comparisons of the form
6826 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6827 // often indicate logic errors in the program.
Richard Trieubcce2f72011-09-07 01:19:57 +00006828 if (!LHSType->hasFloatingRepresentation()) {
6829 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
6830 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00006831 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00006832 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00006833 PDiag(diag::warn_comparison_always)
6834 << 0 // self-
6835 << 2 // "a constant"
6836 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006837 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006838
Nate Begeman191a6b12008-07-14 18:02:46 +00006839 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00006840 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
Richard Trieubcce2f72011-09-07 01:19:57 +00006841 assert (RHSType->hasFloatingRepresentation());
6842 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00006843 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006844
Nate Begeman191a6b12008-07-14 18:02:46 +00006845 // Return the type for the comparison, which is the same as vector type for
6846 // integer vectors, or an integer type of identical size and number of
6847 // elements for floating point vectors.
Richard Trieubcce2f72011-09-07 01:19:57 +00006848 if (LHSType->hasIntegerRepresentation())
6849 return LHSType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006850
Richard Trieubcce2f72011-09-07 01:19:57 +00006851 const VectorType *VTy = LHSType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006852 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006853 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006854 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006855 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006856 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6857
Mike Stump4e1f26a2009-02-19 03:04:26 +00006858 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006859 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006860 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6861}
6862
Steve Naroff218bc2b2007-05-04 21:54:46 +00006863inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00006864 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006865 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6866
Richard Trieubcce2f72011-09-07 01:19:57 +00006867 if (LHS.get()->getType()->isVectorType() ||
6868 RHS.get()->getType()->isVectorType()) {
6869 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6870 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00006871 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006872
Richard Trieubcce2f72011-09-07 01:19:57 +00006873 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006874 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006875
Richard Trieubcce2f72011-09-07 01:19:57 +00006876 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
6877 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00006878 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00006879 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006880 return QualType();
Richard Trieubcce2f72011-09-07 01:19:57 +00006881 LHS = LHSResult.take();
6882 RHS = RHSResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006883
Richard Trieubcce2f72011-09-07 01:19:57 +00006884 if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6885 RHS.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006886 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00006887 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006888}
6889
Steve Naroff218bc2b2007-05-04 21:54:46 +00006890inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieubcce2f72011-09-07 01:19:57 +00006891 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00006892
6893 // Diagnose cases where the user write a logical and/or but probably meant a
6894 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6895 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00006896 if (LHS.get()->getType()->isIntegerType() &&
6897 !LHS.get()->getType()->isBooleanType() &&
6898 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00006899 // Don't warn in macros or template instantiations.
6900 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00006901 // If the RHS can be constant folded, and if it constant folds to something
6902 // that isn't 0 or 1 (which indicate a potential logical operation that
6903 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006904 // Parens on the RHS are ignored.
Chris Lattner938533d2010-07-24 01:10:11 +00006905 Expr::EvalResult Result;
Richard Trieubcce2f72011-09-07 01:19:57 +00006906 if (RHS.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6907 if ((getLangOptions().Bool && !RHS.get()->getType()->isBooleanType()) ||
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006908 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6909 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00006910 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006911 << (Opc == BO_LAnd ? "&&" : "||");
6912 // Suggest replacing the logical operator with the bitwise version
6913 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6914 << (Opc == BO_LAnd ? "&" : "|")
6915 << FixItHint::CreateReplacement(SourceRange(
6916 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6917 getLangOptions())),
6918 Opc == BO_LAnd ? "&" : "|");
6919 if (Opc == BO_LAnd)
6920 // Suggest replacing "Foo() && kNonZero" with "Foo()"
6921 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6922 << FixItHint::CreateRemoval(
6923 SourceRange(
Richard Trieubcce2f72011-09-07 01:19:57 +00006924 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006925 0, getSourceManager(),
6926 getLangOptions()),
Richard Trieubcce2f72011-09-07 01:19:57 +00006927 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006928 }
Chris Lattner938533d2010-07-24 01:10:11 +00006929 }
Chris Lattner8406c512010-07-13 19:41:32 +00006930
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006931 if (!Context.getLangOptions().CPlusPlus) {
Richard Trieubcce2f72011-09-07 01:19:57 +00006932 LHS = UsualUnaryConversions(LHS.take());
6933 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006934 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006935
Richard Trieubcce2f72011-09-07 01:19:57 +00006936 RHS = UsualUnaryConversions(RHS.take());
6937 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006938 return QualType();
6939
Richard Trieubcce2f72011-09-07 01:19:57 +00006940 if (!LHS.get()->getType()->isScalarType() ||
6941 !RHS.get()->getType()->isScalarType())
6942 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006943
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006944 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006945 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006946
John McCall4a2429a2010-06-04 00:29:51 +00006947 // The following is safe because we only use this method for
6948 // non-overloadable operands.
6949
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006950 // C++ [expr.log.and]p1
6951 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006952 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00006953 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
6954 if (LHSRes.isInvalid())
6955 return InvalidOperands(Loc, LHS, RHS);
6956 LHS = move(LHSRes);
John Wiegley01296292011-04-08 18:41:53 +00006957
Richard Trieubcce2f72011-09-07 01:19:57 +00006958 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
6959 if (RHSRes.isInvalid())
6960 return InvalidOperands(Loc, LHS, RHS);
6961 RHS = move(RHSRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006962
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006963 // C++ [expr.log.and]p2
6964 // C++ [expr.log.or]p2
6965 // The result is a bool.
6966 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006967}
6968
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006969/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6970/// is a read-only property; return true if so. A readonly property expression
6971/// depends on various declarations and thus must be treated specially.
6972///
Mike Stump11289f42009-09-09 15:08:12 +00006973static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006974 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6975 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00006976 if (PropExpr->isImplicitProperty()) return false;
6977
6978 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6979 QualType BaseType = PropExpr->isSuperReceiver() ?
6980 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00006981 PropExpr->getBase()->getType();
6982
John McCallb7bd14f2010-12-02 01:19:52 +00006983 if (const ObjCObjectPointerType *OPT =
6984 BaseType->getAsObjCInterfacePointerType())
6985 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6986 if (S.isPropertyReadonly(PDecl, IFace))
6987 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006988 }
6989 return false;
6990}
6991
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00006992static bool IsConstProperty(Expr *E, Sema &S) {
6993 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6994 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6995 if (PropExpr->isImplicitProperty()) return false;
6996
6997 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6998 QualType T = PDecl->getType();
6999 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00007000 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007001 CanQualType CT = S.Context.getCanonicalType(T);
7002 return CT.isConstQualified();
7003 }
7004 return false;
7005}
7006
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007007static bool IsReadonlyMessage(Expr *E, Sema &S) {
7008 if (E->getStmtClass() != Expr::MemberExprClass)
7009 return false;
7010 const MemberExpr *ME = cast<MemberExpr>(E);
7011 NamedDecl *Member = ME->getMemberDecl();
7012 if (isa<FieldDecl>(Member)) {
7013 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
7014 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
7015 return false;
7016 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
7017 }
7018 return false;
7019}
7020
Chris Lattner30bd3272008-11-18 01:22:49 +00007021/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7022/// emit an error and return true. If so, return false.
7023static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007024 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007025 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007026 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007027 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7028 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007029 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7030 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007031 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7032 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007033 if (IsLV == Expr::MLV_Valid)
7034 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007035
Chris Lattner30bd3272008-11-18 01:22:49 +00007036 unsigned Diag = 0;
7037 bool NeedType = false;
7038 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00007039 case Expr::MLV_ConstQualified:
7040 Diag = diag::err_typecheck_assign_const;
7041
John McCalld4631322011-06-17 06:42:21 +00007042 // In ARC, use some specialized diagnostics for occasions where we
7043 // infer 'const'. These are always pseudo-strong variables.
John McCall31168b02011-06-15 23:02:42 +00007044 if (S.getLangOptions().ObjCAutoRefCount) {
7045 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7046 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7047 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7048
John McCalld4631322011-06-17 06:42:21 +00007049 // Use the normal diagnostic if it's pseudo-__strong but the
7050 // user actually wrote 'const'.
7051 if (var->isARCPseudoStrong() &&
7052 (!var->getTypeSourceInfo() ||
7053 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7054 // There are two pseudo-strong cases:
7055 // - self
John McCall31168b02011-06-15 23:02:42 +00007056 ObjCMethodDecl *method = S.getCurMethodDecl();
7057 if (method && var == method->getSelfDecl())
7058 Diag = diag::err_typecheck_arr_assign_self;
John McCalld4631322011-06-17 06:42:21 +00007059
7060 // - fast enumeration variables
7061 else
John McCall31168b02011-06-15 23:02:42 +00007062 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00007063
John McCall31168b02011-06-15 23:02:42 +00007064 SourceRange Assign;
7065 if (Loc != OrigLoc)
7066 Assign = SourceRange(OrigLoc, OrigLoc);
7067 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7068 // We need to preserve the AST regardless, so migration tool
7069 // can do its job.
7070 return false;
7071 }
7072 }
7073 }
7074
7075 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007076 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007077 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7078 NeedType = true;
7079 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007080 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007081 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7082 NeedType = true;
7083 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007084 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007085 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7086 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007087 case Expr::MLV_Valid:
7088 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007089 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007090 case Expr::MLV_MemberFunction:
7091 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007092 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7093 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007094 case Expr::MLV_IncompleteType:
7095 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007096 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007097 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00007098 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00007099 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007100 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7101 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00007102 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00007103 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7104 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007105 case Expr::MLV_ReadonlyProperty:
7106 Diag = diag::error_readonly_property_assignment;
7107 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007108 case Expr::MLV_NoSetterProperty:
7109 Diag = diag::error_nosetter_property_assignment;
7110 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007111 case Expr::MLV_InvalidMessageExpression:
7112 Diag = diag::error_readonly_message_assignment;
7113 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007114 case Expr::MLV_SubObjCPropertySetting:
7115 Diag = diag::error_no_subobject_property_setting;
7116 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007117 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007118
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007119 SourceRange Assign;
7120 if (Loc != OrigLoc)
7121 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007122 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007123 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007124 else
Mike Stump11289f42009-09-09 15:08:12 +00007125 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007126 return true;
7127}
7128
7129
7130
7131// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00007132QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007133 SourceLocation Loc,
7134 QualType CompoundType) {
7135 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007136 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007137 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007138
Richard Trieuda4f43a62011-09-07 01:33:52 +00007139 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00007140 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7141 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007142 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007143 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007144 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007145 // Simple assignment "x = y".
Richard Trieuda4f43a62011-09-07 01:33:52 +00007146 if (LHSExpr->getObjectKind() == OK_ObjCProperty) {
7147 ExprResult LHSResult = Owned(LHSExpr);
John Wiegley01296292011-04-08 18:41:53 +00007148 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7149 if (LHSResult.isInvalid())
7150 return QualType();
Richard Trieuda4f43a62011-09-07 01:33:52 +00007151 LHSExpr = LHSResult.take();
John Wiegley01296292011-04-08 18:41:53 +00007152 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007153 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007154 if (RHS.isInvalid())
7155 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007156 // Special case of NSObject attributes on c-style pointer types.
7157 if (ConvTy == IncompatiblePointer &&
7158 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007159 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007160 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007161 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007162 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007163
John McCall7decc9e2010-11-18 06:31:45 +00007164 if (ConvTy == Compatible &&
7165 getLangOptions().ObjCNonFragileABI &&
7166 LHSType->isObjCObjectType())
7167 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7168 << LHSType;
7169
Chris Lattnerea714382008-08-21 18:04:13 +00007170 // If the RHS is a unary plus or minus, check to see if they = and + are
7171 // right next to each other. If so, the user may have typo'd "x =+ 4"
7172 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00007173 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00007174 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7175 RHSCheck = ICE->getSubExpr();
7176 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007177 if ((UO->getOpcode() == UO_Plus ||
7178 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007179 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007180 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007181 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00007182 // And there is a space or other character before the subexpr of the
7183 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007184 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00007185 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007186 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007187 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007188 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007189 }
Chris Lattnerea714382008-08-21 18:04:13 +00007190 }
John McCall31168b02011-06-15 23:02:42 +00007191
7192 if (ConvTy == Compatible) {
7193 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007194 checkRetainCycles(LHSExpr, RHS.get());
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007195 else if (getLangOptions().ObjCAutoRefCount)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007196 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00007197 }
Chris Lattnerea714382008-08-21 18:04:13 +00007198 } else {
7199 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007200 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007201 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007202
Chris Lattner326f7572008-11-18 01:30:42 +00007203 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007204 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007205 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007206
Richard Trieuda4f43a62011-09-07 01:33:52 +00007207 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007208
Steve Naroff98cf3e92007-06-06 18:38:38 +00007209 // C99 6.5.16p3: The type of an assignment expression is the type of the
7210 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007211 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007212 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7213 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007214 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007215 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007216 return (getLangOptions().CPlusPlus
7217 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007218}
7219
Chris Lattner326f7572008-11-18 01:30:42 +00007220// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007221static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007222 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00007223 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007224
John McCall3aef3d82011-04-10 19:13:55 +00007225 LHS = S.CheckPlaceholderExpr(LHS.take());
7226 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007227 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007228 return QualType();
7229
John McCall73d36182010-10-12 07:14:40 +00007230 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7231 // operands, but not unary promotions.
7232 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007233
John McCall34376a62010-12-04 03:47:34 +00007234 // So we treat the LHS as a ignored value, and in C++ we allow the
7235 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007236 LHS = S.IgnoredValueConversions(LHS.take());
7237 if (LHS.isInvalid())
7238 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007239
7240 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007241 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7242 if (RHS.isInvalid())
7243 return QualType();
7244 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007245 S.RequireCompleteType(Loc, RHS.get()->getType(),
7246 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007247 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007248
John Wiegley01296292011-04-08 18:41:53 +00007249 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007250}
7251
Steve Naroff7a5af782007-07-13 16:58:59 +00007252/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7253/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007254static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7255 ExprValueKind &VK,
7256 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007257 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007258 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007259 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007260
Chris Lattner6b0cf142008-11-21 07:05:48 +00007261 QualType ResType = Op->getType();
7262 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007263
John McCall4bc41ae2010-11-18 19:01:18 +00007264 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007265 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +00007266 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007267 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007268 return QualType();
7269 }
7270 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007271 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007272 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007273 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007274 } else if (ResType->isAnyPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007275 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007276 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007277 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007278
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007279 // Diagnose bad cases where we step over interface counts.
Richard Trieub10c6312011-09-01 22:53:23 +00007280 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007281 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00007282 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007283 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007284 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007285 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007286 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007287 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007288 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007289 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007290 IsInc, IsPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007291 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7292 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007293 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007294 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +00007295 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007296 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007297 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007298 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007299 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007300 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007301 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007302 // In C++, a prefix increment is the same type as the operand. Otherwise
7303 // (in C or with postfix), the increment is the unqualified type of the
7304 // operand.
Richard Trieuba63ce62011-09-09 01:45:06 +00007305 if (IsPrefix && S.getLangOptions().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007306 VK = VK_LValue;
7307 return ResType;
7308 } else {
7309 VK = VK_RValue;
7310 return ResType.getUnqualifiedType();
7311 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007312}
7313
John Wiegley01296292011-04-08 18:41:53 +00007314ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00007315 assert(E->getValueKind() == VK_LValue &&
7316 E->getObjectKind() == OK_ObjCProperty);
7317 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7318
Douglas Gregor33823722011-06-11 01:09:30 +00007319 QualType T = E->getType();
7320 QualType ReceiverType;
7321 if (PRE->isObjectReceiver())
7322 ReceiverType = PRE->getBase()->getType();
7323 else if (PRE->isSuperReceiver())
7324 ReceiverType = PRE->getSuperReceiverType();
7325 else
7326 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
7327
John McCall34376a62010-12-04 03:47:34 +00007328 ExprValueKind VK = VK_RValue;
7329 if (PRE->isImplicitProperty()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007330 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007331 PRE->getImplicitPropertyGetter()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007332 T = getMessageSendResultType(ReceiverType, GetterMethod,
7333 PRE->isClassReceiver(),
7334 PRE->isSuperReceiver());
7335 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007336 }
7337 else {
7338 Diag(PRE->getLocation(), diag::err_getter_not_found)
7339 << PRE->getBase()->getType();
7340 }
John McCall34376a62010-12-04 03:47:34 +00007341 }
Douglas Gregor33823722011-06-11 01:09:30 +00007342
7343 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCall34376a62010-12-04 03:47:34 +00007344 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007345
7346 ExprResult Result = MaybeBindToTemporary(E);
7347 if (!Result.isInvalid())
7348 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00007349
7350 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00007351}
7352
Richard Trieucfc491d2011-08-02 04:35:43 +00007353void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
7354 QualType &LHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00007355 assert(LHS.get()->getValueKind() == VK_LValue &&
7356 LHS.get()->getObjectKind() == OK_ObjCProperty);
7357 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00007358
John McCall31168b02011-06-15 23:02:42 +00007359 bool Consumed = false;
7360
John Wiegley01296292011-04-08 18:41:53 +00007361 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00007362 // If using property-dot syntax notation for assignment, and there is a
7363 // setter, RHS expression is being passed to the setter argument. So,
7364 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00007365 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00007366 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7367 LHSTy = (*P)->getType();
John McCall31168b02011-06-15 23:02:42 +00007368 Consumed = (getLangOptions().ObjCAutoRefCount &&
7369 (*P)->hasAttr<NSConsumedAttr>());
John McCall34376a62010-12-04 03:47:34 +00007370
7371 // Otherwise, if the getter returns an l-value, just call that.
7372 } else {
John Wiegley01296292011-04-08 18:41:53 +00007373 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00007374 ExprValueKind VK = Expr::getValueKindForType(Result);
7375 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00007376 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7377 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00007378 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007379 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007380 }
John McCall31168b02011-06-15 23:02:42 +00007381 } else if (getLangOptions().ObjCAutoRefCount) {
7382 const ObjCMethodDecl *setter
7383 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7384 if (setter) {
7385 ObjCMethodDecl::param_iterator P = setter->param_begin();
7386 LHSTy = (*P)->getType();
7387 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7388 }
John McCall34376a62010-12-04 03:47:34 +00007389 }
7390
John McCall31168b02011-06-15 23:02:42 +00007391 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7392 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007393 InitializedEntity Entity =
John McCall31168b02011-06-15 23:02:42 +00007394 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley01296292011-04-08 18:41:53 +00007395 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCall31168b02011-06-15 23:02:42 +00007396 if (!ArgE.isInvalid()) {
John Wiegley01296292011-04-08 18:41:53 +00007397 RHS = ArgE;
John McCall31168b02011-06-15 23:02:42 +00007398 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7399 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7400 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007401 }
7402}
7403
7404
Anders Carlsson806700f2008-02-01 07:15:58 +00007405/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007406/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007407/// where the declaration is needed for type checking. We only need to
7408/// handle cases when the expression references a function designator
7409/// or is an lvalue. Here are some examples:
7410/// - &(x) => x
7411/// - &*****f => f for f a function designator.
7412/// - &s.xx => s
7413/// - &s.zz[1].yy -> s, if zz is an array
7414/// - *(x + 1) -> x, if x is an array
7415/// - &"123"[2] -> 0
7416/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007417static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007418 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007419 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007420 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007421 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007422 // If this is an arrow operator, the address is an offset from
7423 // the base's value, so the object the base refers to is
7424 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007425 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007426 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007427 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007428 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007429 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007430 // FIXME: This code shouldn't be necessary! We should catch the implicit
7431 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007432 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7433 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7434 if (ICE->getSubExpr()->getType()->isArrayType())
7435 return getPrimaryDecl(ICE->getSubExpr());
7436 }
7437 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007438 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007439 case Stmt::UnaryOperatorClass: {
7440 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007441
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007442 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007443 case UO_Real:
7444 case UO_Imag:
7445 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007446 return getPrimaryDecl(UO->getSubExpr());
7447 default:
7448 return 0;
7449 }
7450 }
Steve Naroff47500512007-04-19 23:00:49 +00007451 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007452 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007453 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007454 // If the result of an implicit cast is an l-value, we care about
7455 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007456 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007457 default:
7458 return 0;
7459 }
7460}
7461
Richard Trieu5f376f62011-09-07 21:46:33 +00007462namespace {
7463 enum {
7464 AO_Bit_Field = 0,
7465 AO_Vector_Element = 1,
7466 AO_Property_Expansion = 2,
7467 AO_Register_Variable = 3,
7468 AO_No_Error = 4
7469 };
7470}
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007471/// \brief Diagnose invalid operand for address of operations.
7472///
7473/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007474static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7475 Expr *E, unsigned Type) {
7476 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7477}
7478
Steve Naroff47500512007-04-19 23:00:49 +00007479/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007480/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007481/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007482/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007483/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007484/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007485/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007486static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7487 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007488 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007489 return S.Context.DependentTy;
7490 if (OrigOp->getType() == S.Context.OverloadTy)
7491 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00007492 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7493 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00007494 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7495 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7496 << OrigOp->getSourceRange();
7497 return QualType();
7498 }
John McCall8d08b9b2010-08-27 09:08:28 +00007499
John McCall2979fe02011-04-12 00:42:48 +00007500 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007501
John McCall8d08b9b2010-08-27 09:08:28 +00007502 // Make sure to ignore parentheses in subsequent checks
7503 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007504
John McCall4bc41ae2010-11-18 19:01:18 +00007505 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007506 // Implement C99-only parts of addressof rules.
7507 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007508 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007509 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7510 // (assuming the deref expression is valid).
7511 return uOp->getSubExpr()->getType();
7512 }
7513 // Technically, there should be a check for array subscript
7514 // expressions here, but the result of one is always an lvalue anyway.
7515 }
John McCallf3a88602011-02-03 08:15:49 +00007516 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007517 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5f376f62011-09-07 21:46:33 +00007518 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +00007519
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007520 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007521 bool sfinae = S.isSFINAEContext();
7522 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7523 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007524 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007525 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007526 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007527 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007528 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007529 } else if (lval == Expr::LV_MemberFunction) {
7530 // If it's an instance method, make a member pointer.
7531 // The expression must have exactly the form &A::foo.
7532
7533 // If the underlying expression isn't a decl ref, give up.
7534 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007535 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007536 << OrigOp->getSourceRange();
7537 return QualType();
7538 }
7539 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7540 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7541
7542 // The id-expression was parenthesized.
7543 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007544 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007545 << OrigOp->getSourceRange();
7546
7547 // The method was named without a qualifier.
7548 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007549 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007550 << op->getSourceRange();
7551 }
7552
John McCall4bc41ae2010-11-18 19:01:18 +00007553 return S.Context.getMemberPointerType(op->getType(),
7554 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007555 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007556 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007557 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007558 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007559 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007560 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007561 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007562 return QualType();
7563 }
John McCall086a4642010-11-24 05:12:34 +00007564 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007565 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +00007566 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +00007567 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007568 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +00007569 AddressOfError = AO_Vector_Element;
John McCall086a4642010-11-24 05:12:34 +00007570 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007571 // cannot take address of a property expression.
Richard Trieu5f376f62011-09-07 21:46:33 +00007572 AddressOfError = AO_Property_Expansion;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007573 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007574 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007575 // with the register storage-class specifier.
7576 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007577 // in C++ it is not error to take address of a register
7578 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007579 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007580 !S.getLangOptions().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +00007581 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +00007582 }
John McCalld14a8642009-11-21 08:51:07 +00007583 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007584 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007585 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007586 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007587 // Could be a pointer to member, though, if there is an explicit
7588 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007589 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007590 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007591 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007592 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007593 S.Diag(OpLoc,
7594 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007595 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007596 return QualType();
7597 }
Mike Stump11289f42009-09-09 15:08:12 +00007598
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007599 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7600 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007601 return S.Context.getMemberPointerType(op->getType(),
7602 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007603 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007604 }
Eli Friedman755c0c92011-08-26 20:28:17 +00007605 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +00007606 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007607 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007608
Richard Trieu5f376f62011-09-07 21:46:33 +00007609 if (AddressOfError != AO_No_Error) {
7610 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7611 return QualType();
7612 }
7613
Eli Friedmance7f9002009-05-16 23:27:50 +00007614 if (lval == Expr::LV_IncompleteVoidType) {
7615 // Taking the address of a void variable is technically illegal, but we
7616 // allow it in cases which are otherwise valid.
7617 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007618 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007619 }
7620
Steve Naroff47500512007-04-19 23:00:49 +00007621 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007622 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007623 return S.Context.getObjCObjectPointerType(op->getType());
7624 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007625}
7626
Chris Lattner9156f1b2010-07-05 19:17:26 +00007627/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007628static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7629 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007630 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007631 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007632
John Wiegley01296292011-04-08 18:41:53 +00007633 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7634 if (ConvResult.isInvalid())
7635 return QualType();
7636 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007637 QualType OpTy = Op->getType();
7638 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007639
7640 if (isa<CXXReinterpretCastExpr>(Op)) {
7641 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7642 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7643 Op->getSourceRange());
7644 }
7645
Chris Lattner9156f1b2010-07-05 19:17:26 +00007646 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7647 // is an incomplete type or void. It would be possible to warn about
7648 // dereferencing a void pointer, but it's completely well-defined, and such a
7649 // warning is unlikely to catch any mistakes.
7650 if (const PointerType *PT = OpTy->getAs<PointerType>())
7651 Result = PT->getPointeeType();
7652 else if (const ObjCObjectPointerType *OPT =
7653 OpTy->getAs<ObjCObjectPointerType>())
7654 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007655 else {
John McCall3aef3d82011-04-10 19:13:55 +00007656 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007657 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007658 if (PR.take() != Op)
7659 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007660 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007661
Chris Lattner9156f1b2010-07-05 19:17:26 +00007662 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007663 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007664 << OpTy << Op->getSourceRange();
7665 return QualType();
7666 }
John McCall4bc41ae2010-11-18 19:01:18 +00007667
7668 // Dereferences are usually l-values...
7669 VK = VK_LValue;
7670
7671 // ...except that certain expressions are never l-values in C.
Douglas Gregor5476205b2011-06-23 00:49:38 +00007672 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007673 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007674
7675 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007676}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007677
John McCalle3027922010-08-25 11:45:40 +00007678static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007679 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007680 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007681 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007682 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007683 case tok::periodstar: Opc = BO_PtrMemD; break;
7684 case tok::arrowstar: Opc = BO_PtrMemI; break;
7685 case tok::star: Opc = BO_Mul; break;
7686 case tok::slash: Opc = BO_Div; break;
7687 case tok::percent: Opc = BO_Rem; break;
7688 case tok::plus: Opc = BO_Add; break;
7689 case tok::minus: Opc = BO_Sub; break;
7690 case tok::lessless: Opc = BO_Shl; break;
7691 case tok::greatergreater: Opc = BO_Shr; break;
7692 case tok::lessequal: Opc = BO_LE; break;
7693 case tok::less: Opc = BO_LT; break;
7694 case tok::greaterequal: Opc = BO_GE; break;
7695 case tok::greater: Opc = BO_GT; break;
7696 case tok::exclaimequal: Opc = BO_NE; break;
7697 case tok::equalequal: Opc = BO_EQ; break;
7698 case tok::amp: Opc = BO_And; break;
7699 case tok::caret: Opc = BO_Xor; break;
7700 case tok::pipe: Opc = BO_Or; break;
7701 case tok::ampamp: Opc = BO_LAnd; break;
7702 case tok::pipepipe: Opc = BO_LOr; break;
7703 case tok::equal: Opc = BO_Assign; break;
7704 case tok::starequal: Opc = BO_MulAssign; break;
7705 case tok::slashequal: Opc = BO_DivAssign; break;
7706 case tok::percentequal: Opc = BO_RemAssign; break;
7707 case tok::plusequal: Opc = BO_AddAssign; break;
7708 case tok::minusequal: Opc = BO_SubAssign; break;
7709 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7710 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7711 case tok::ampequal: Opc = BO_AndAssign; break;
7712 case tok::caretequal: Opc = BO_XorAssign; break;
7713 case tok::pipeequal: Opc = BO_OrAssign; break;
7714 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007715 }
7716 return Opc;
7717}
7718
John McCalle3027922010-08-25 11:45:40 +00007719static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007720 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007721 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007722 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007723 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007724 case tok::plusplus: Opc = UO_PreInc; break;
7725 case tok::minusminus: Opc = UO_PreDec; break;
7726 case tok::amp: Opc = UO_AddrOf; break;
7727 case tok::star: Opc = UO_Deref; break;
7728 case tok::plus: Opc = UO_Plus; break;
7729 case tok::minus: Opc = UO_Minus; break;
7730 case tok::tilde: Opc = UO_Not; break;
7731 case tok::exclaim: Opc = UO_LNot; break;
7732 case tok::kw___real: Opc = UO_Real; break;
7733 case tok::kw___imag: Opc = UO_Imag; break;
7734 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007735 }
7736 return Opc;
7737}
7738
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007739/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7740/// This warning is only emitted for builtin assignment operations. It is also
7741/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007742static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007743 SourceLocation OpLoc) {
7744 if (!S.ActiveTemplateInstantiations.empty())
7745 return;
7746 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7747 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007748 LHSExpr = LHSExpr->IgnoreParenImpCasts();
7749 RHSExpr = RHSExpr->IgnoreParenImpCasts();
7750 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
7751 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
7752 if (!LHSDeclRef || !RHSDeclRef ||
7753 LHSDeclRef->getLocation().isMacroID() ||
7754 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007755 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007756 const ValueDecl *LHSDecl =
7757 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
7758 const ValueDecl *RHSDecl =
7759 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
7760 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007761 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007762 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007763 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007764 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007765 if (RefTy->getPointeeType().isVolatileQualified())
7766 return;
7767
7768 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007769 << LHSDeclRef->getType()
7770 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007771}
7772
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007773/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7774/// operator @p Opc at location @c TokLoc. This routine only supports
7775/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007776ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007777 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007778 Expr *LHSExpr, Expr *RHSExpr) {
7779 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007780 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007781 // The following two variables are used for compound assignment operators
7782 QualType CompLHSTy; // Type of LHS after promotions for computation
7783 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007784 ExprValueKind VK = VK_RValue;
7785 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007786
Douglas Gregor1beec452011-03-12 01:48:56 +00007787 // Check if a 'foo<int>' involved in a binary op, identifies a single
7788 // function unambiguously (i.e. an lvalue ala 13.4)
7789 // But since an assignment can trigger target based overload, exclude it in
7790 // our blind search. i.e:
7791 // template<class T> void f(); template<class T, class U> void f(U);
7792 // f<int> == 0; // resolve f<int> blindly
7793 // void (*p)(int); p = f<int>; // resolve f<int> using target
7794 if (Opc != BO_Assign) {
Richard Trieu4a287fb2011-09-07 01:49:20 +00007795 ExprResult resolvedLHS = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00007796 if (!resolvedLHS.isUsable()) return ExprError();
Richard Trieu4a287fb2011-09-07 01:49:20 +00007797 LHS = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00007798
Richard Trieu4a287fb2011-09-07 01:49:20 +00007799 ExprResult resolvedRHS = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00007800 if (!resolvedRHS.isUsable()) return ExprError();
Richard Trieu4a287fb2011-09-07 01:49:20 +00007801 RHS = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00007802 }
7803
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007804 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007805 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007806 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007807 if (getLangOptions().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +00007808 LHS.get()->getObjectKind() != OK_ObjCProperty) {
7809 VK = LHS.get()->getValueKind();
7810 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007811 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007812 if (!ResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00007813 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007814 break;
John McCalle3027922010-08-25 11:45:40 +00007815 case BO_PtrMemD:
7816 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007817 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007818 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007819 break;
John McCalle3027922010-08-25 11:45:40 +00007820 case BO_Mul:
7821 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007822 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007823 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007824 break;
John McCalle3027922010-08-25 11:45:40 +00007825 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007826 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007827 break;
John McCalle3027922010-08-25 11:45:40 +00007828 case BO_Add:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007829 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007830 break;
John McCalle3027922010-08-25 11:45:40 +00007831 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007832 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007833 break;
John McCalle3027922010-08-25 11:45:40 +00007834 case BO_Shl:
7835 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007836 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007837 break;
John McCalle3027922010-08-25 11:45:40 +00007838 case BO_LE:
7839 case BO_LT:
7840 case BO_GE:
7841 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007842 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007843 break;
John McCalle3027922010-08-25 11:45:40 +00007844 case BO_EQ:
7845 case BO_NE:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007846 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007847 break;
John McCalle3027922010-08-25 11:45:40 +00007848 case BO_And:
7849 case BO_Xor:
7850 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007851 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007852 break;
John McCalle3027922010-08-25 11:45:40 +00007853 case BO_LAnd:
7854 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007855 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007856 break;
John McCalle3027922010-08-25 11:45:40 +00007857 case BO_MulAssign:
7858 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007859 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007860 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007861 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007862 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7863 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007864 break;
John McCalle3027922010-08-25 11:45:40 +00007865 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007866 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007867 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007868 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7869 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007870 break;
John McCalle3027922010-08-25 11:45:40 +00007871 case BO_AddAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007872 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7873 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7874 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007875 break;
John McCalle3027922010-08-25 11:45:40 +00007876 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007877 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7878 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7879 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007880 break;
John McCalle3027922010-08-25 11:45:40 +00007881 case BO_ShlAssign:
7882 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007883 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007884 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007885 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7886 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007887 break;
John McCalle3027922010-08-25 11:45:40 +00007888 case BO_AndAssign:
7889 case BO_XorAssign:
7890 case BO_OrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007891 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007892 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007893 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7894 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007895 break;
John McCalle3027922010-08-25 11:45:40 +00007896 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007897 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
7898 if (getLangOptions().CPlusPlus && !RHS.isInvalid()) {
7899 VK = RHS.get()->getValueKind();
7900 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007901 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007902 break;
7903 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00007904 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007905 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007906
7907 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +00007908 CheckArrayAccess(LHS.get());
7909 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007910
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007911 if (CompResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00007912 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00007913 ResultTy, VK, OK, OpLoc));
Richard Trieu4a287fb2011-09-07 01:49:20 +00007914 if (getLangOptions().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +00007915 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007916 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007917 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007918 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00007919 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00007920 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00007921 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007922}
7923
Sebastian Redl44615072009-10-27 12:10:02 +00007924/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7925/// operators are mixed in a way that suggests that the programmer forgot that
7926/// comparison operators have higher precedence. The most typical example of
7927/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007928static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007929 SourceLocation OpLoc, Expr *LHSExpr,
7930 Expr *RHSExpr) {
Sebastian Redl44615072009-10-27 12:10:02 +00007931 typedef BinaryOperator BinOp;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007932 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
7933 RHSopc = static_cast<BinOp::Opcode>(-1);
7934 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
7935 LHSopc = BO->getOpcode();
7936 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
7937 RHSopc = BO->getOpcode();
Sebastian Redl43028242009-10-26 15:24:15 +00007938
7939 // Subs are not binary operators.
Richard Trieu4a287fb2011-09-07 01:49:20 +00007940 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl43028242009-10-26 15:24:15 +00007941 return;
7942
7943 // Bitwise operations are sometimes used as eager logical ops.
7944 // Don't diagnose this.
Richard Trieu4a287fb2011-09-07 01:49:20 +00007945 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
7946 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007947 return;
7948
Richard Trieu4a287fb2011-09-07 01:49:20 +00007949 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
7950 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00007951 if (!isLeftComp && !isRightComp) return;
7952
Richard Trieu4a287fb2011-09-07 01:49:20 +00007953 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
7954 OpLoc)
7955 : SourceRange(OpLoc, RHSExpr->getLocEnd());
7956 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
7957 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00007958 SourceRange ParensRange = isLeftComp ?
Richard Trieu4a287fb2011-09-07 01:49:20 +00007959 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
7960 RHSExpr->getLocEnd())
7961 : SourceRange(LHSExpr->getLocStart(),
7962 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu73088052011-08-10 22:41:34 +00007963
7964 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7965 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
7966 SuggestParentheses(Self, OpLoc,
7967 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007968 RHSExpr->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +00007969 SuggestParentheses(Self, OpLoc,
7970 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
7971 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00007972}
7973
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007974/// \brief It accepts a '&' expr that is inside a '|' one.
7975/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7976/// in parentheses.
7977static void
7978EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7979 BinaryOperator *Bop) {
7980 assert(Bop->getOpcode() == BO_And);
7981 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7982 << Bop->getSourceRange() << OpLoc;
7983 SuggestParentheses(Self, Bop->getOperatorLoc(),
7984 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7985 Bop->getSourceRange());
7986}
7987
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007988/// \brief It accepts a '&&' expr that is inside a '||' one.
7989/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7990/// in parentheses.
7991static void
7992EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007993 BinaryOperator *Bop) {
7994 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007995 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7996 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007997 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007998 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007999 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008000}
8001
8002/// \brief Returns true if the given expression can be evaluated as a constant
8003/// 'true'.
8004static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8005 bool Res;
8006 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8007}
8008
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008009/// \brief Returns true if the given expression can be evaluated as a constant
8010/// 'false'.
8011static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8012 bool Res;
8013 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8014}
8015
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008016/// \brief Look for '&&' in the left hand of a '||' expr.
8017static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008018 Expr *LHSExpr, Expr *RHSExpr) {
8019 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008020 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008021 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008022 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008023 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008024 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8025 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8026 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8027 } else if (Bop->getOpcode() == BO_LOr) {
8028 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8029 // If it's "a || b && 1 || c" we didn't warn earlier for
8030 // "a || b && 1", but warn now.
8031 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8032 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8033 }
8034 }
8035 }
8036}
8037
8038/// \brief Look for '&&' in the right hand of a '||' expr.
8039static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008040 Expr *LHSExpr, Expr *RHSExpr) {
8041 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008042 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008043 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008044 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008045 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008046 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8047 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8048 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008049 }
8050 }
8051}
8052
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008053/// \brief Look for '&' in the left or right hand of a '|' expr.
8054static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8055 Expr *OrArg) {
8056 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8057 if (Bop->getOpcode() == BO_And)
8058 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8059 }
8060}
8061
Sebastian Redl43028242009-10-26 15:24:15 +00008062/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008063/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008064static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008065 SourceLocation OpLoc, Expr *LHSExpr,
8066 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008067 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008068 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008069 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008070
8071 // Diagnose "arg1 & arg2 | arg3"
8072 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008073 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8074 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008075 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008076
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008077 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8078 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008079 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008080 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8081 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008082 }
Sebastian Redl43028242009-10-26 15:24:15 +00008083}
8084
Steve Naroff218bc2b2007-05-04 21:54:46 +00008085// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008086ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008087 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008088 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +00008089 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008090 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8091 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008092
Sebastian Redl43028242009-10-26 15:24:15 +00008093 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008094 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00008095
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008096 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +00008097}
8098
John McCalldadc5752010-08-24 06:29:42 +00008099ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008100 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008101 Expr *LHSExpr, Expr *RHSExpr) {
John McCall622114c2010-12-06 05:26:58 +00008102 if (getLangOptions().CPlusPlus) {
8103 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008104
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008105 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) {
John McCall622114c2010-12-06 05:26:58 +00008106 UseBuiltinOperator = false;
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008107 } else if (Opc == BO_Assign &&
8108 LHSExpr->getObjectKind() == OK_ObjCProperty) {
John McCall622114c2010-12-06 05:26:58 +00008109 UseBuiltinOperator = true;
8110 } else {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008111 UseBuiltinOperator = !LHSExpr->getType()->isOverloadableType() &&
8112 !RHSExpr->getType()->isOverloadableType();
John McCall622114c2010-12-06 05:26:58 +00008113 }
8114
8115 if (!UseBuiltinOperator) {
8116 // Find all of the overloaded operators visible from this
8117 // point. We perform both an operator-name lookup from the local
8118 // scope and an argument-dependent lookup based on the types of
8119 // the arguments.
8120 UnresolvedSet<16> Functions;
8121 OverloadedOperatorKind OverOp
8122 = BinaryOperator::getOverloadedOperator(Opc);
8123 if (S && OverOp != OO_None)
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008124 LookupOverloadedOperatorName(OverOp, S, LHSExpr->getType(),
8125 RHSExpr->getType(), Functions);
John McCall622114c2010-12-06 05:26:58 +00008126
8127 // Build the (potentially-overloaded, potentially-dependent)
8128 // binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008129 return CreateOverloadedBinOp(OpLoc, Opc, Functions, LHSExpr, RHSExpr);
John McCall622114c2010-12-06 05:26:58 +00008130 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00008131 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008132
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008133 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008134 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008135}
8136
John McCalldadc5752010-08-24 06:29:42 +00008137ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008138 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008139 Expr *InputExpr) {
8140 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008141 ExprValueKind VK = VK_RValue;
8142 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008143 QualType resultType;
8144 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008145 case UO_PreInc:
8146 case UO_PreDec:
8147 case UO_PostInc:
8148 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008149 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008150 Opc == UO_PreInc ||
8151 Opc == UO_PostInc,
8152 Opc == UO_PreInc ||
8153 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008154 break;
John McCalle3027922010-08-25 11:45:40 +00008155 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00008156 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008157 break;
John McCall31996342011-04-07 08:22:57 +00008158 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00008159 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00008160 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008161 Input = move(resolved);
8162 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8163 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008164 break;
John McCall31996342011-04-07 08:22:57 +00008165 }
John McCalle3027922010-08-25 11:45:40 +00008166 case UO_Plus:
8167 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008168 Input = UsualUnaryConversions(Input.take());
8169 if (Input.isInvalid()) return ExprError();
8170 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008171 if (resultType->isDependentType())
8172 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008173 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8174 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008175 break;
8176 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8177 resultType->isEnumeralType())
8178 break;
8179 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008180 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008181 resultType->isPointerType())
8182 break;
John McCall36226622010-10-12 02:09:17 +00008183 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008184 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008185 if (Input.isInvalid()) return ExprError();
8186 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008187 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008188
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008189 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008190 << resultType << Input.get()->getSourceRange());
8191
John McCalle3027922010-08-25 11:45:40 +00008192 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008193 Input = UsualUnaryConversions(Input.take());
8194 if (Input.isInvalid()) return ExprError();
8195 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008196 if (resultType->isDependentType())
8197 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008198 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8199 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8200 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008201 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008202 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008203 else if (resultType->hasIntegerRepresentation())
8204 break;
8205 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008206 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008207 if (Input.isInvalid()) return ExprError();
8208 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008209 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008210 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008211 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008212 }
Steve Naroff35d85152007-05-07 00:24:15 +00008213 break;
John Wiegley01296292011-04-08 18:41:53 +00008214
John McCalle3027922010-08-25 11:45:40 +00008215 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008216 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008217 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8218 if (Input.isInvalid()) return ExprError();
8219 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008220 if (resultType->isDependentType())
8221 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008222 if (resultType->isScalarType()) {
8223 // C99 6.5.3.3p1: ok, fallthrough;
8224 if (Context.getLangOptions().CPlusPlus) {
8225 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8226 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008227 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8228 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008229 }
John McCall36226622010-10-12 02:09:17 +00008230 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008231 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008232 if (Input.isInvalid()) return ExprError();
8233 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008234 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008235 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008236 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008237 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008238
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008239 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008240 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008241 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008242 break;
John McCalle3027922010-08-25 11:45:40 +00008243 case UO_Real:
8244 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008245 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008246 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00008247 if (Input.isInvalid()) return ExprError();
8248 if (Input.get()->getValueKind() != VK_RValue &&
8249 Input.get()->getObjectKind() == OK_Ordinary)
8250 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008251 break;
John McCalle3027922010-08-25 11:45:40 +00008252 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008253 resultType = Input.get()->getType();
8254 VK = Input.get()->getValueKind();
8255 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008256 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008257 }
John Wiegley01296292011-04-08 18:41:53 +00008258 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008259 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008260
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008261 // Check for array bounds violations in the operand of the UnaryOperator,
8262 // except for the '*' and '&' operators that have to be handled specially
8263 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8264 // that are explicitly defined as valid by the standard).
8265 if (Opc != UO_AddrOf && Opc != UO_Deref)
8266 CheckArrayAccess(Input.get());
8267
John Wiegley01296292011-04-08 18:41:53 +00008268 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008269 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008270}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008271
John McCalldadc5752010-08-24 06:29:42 +00008272ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008273 UnaryOperatorKind Opc, Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008274 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008275 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008276 // Find all of the overloaded operators visible from this
8277 // point. We perform both an operator-name lookup from the local
8278 // scope and an argument-dependent lookup based on the types of
8279 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008280 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008281 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008282 if (S && OverOp != OO_None)
8283 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8284 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008285
John McCallb268a282010-08-23 23:25:46 +00008286 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008287 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008288
John McCallb268a282010-08-23 23:25:46 +00008289 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008290}
8291
Douglas Gregor5287f092009-11-05 00:51:44 +00008292// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008293ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008294 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008295 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008296}
8297
Steve Naroff66356bd2007-09-16 14:56:35 +00008298/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008299ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008300 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008301 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008302 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008303 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008304 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008305}
8306
John McCall31168b02011-06-15 23:02:42 +00008307/// Given the last statement in a statement-expression, check whether
8308/// the result is a producing expression (like a call to an
8309/// ns_returns_retained function) and, if so, rebuild it to hoist the
8310/// release out of the full-expression. Otherwise, return null.
8311/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +00008312static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +00008313 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +00008314 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCall31168b02011-06-15 23:02:42 +00008315 if (!cleanups) return 0;
8316
8317 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +00008318 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCall31168b02011-06-15 23:02:42 +00008319 return 0;
8320
8321 // Splice out the cast. This shouldn't modify any interesting
8322 // features of the statement.
8323 Expr *producer = cast->getSubExpr();
8324 assert(producer->getType() == cast->getType());
8325 assert(producer->getValueKind() == cast->getValueKind());
8326 cleanups->setSubExpr(producer);
8327 return cleanups;
8328}
8329
John McCalldadc5752010-08-24 06:29:42 +00008330ExprResult
John McCallb268a282010-08-23 23:25:46 +00008331Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008332 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008333 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8334 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8335
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008336 bool isFileScope
8337 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008338 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008339 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008340
Chris Lattner366727f2007-07-24 16:58:17 +00008341 // FIXME: there are a variety of strange constraints to enforce here, for
8342 // example, it is not possible to goto into a stmt expression apparently.
8343 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008344
Chris Lattner366727f2007-07-24 16:58:17 +00008345 // If there are sub stmts in the compound stmt, take the type of the last one
8346 // as the type of the stmtexpr.
8347 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008348 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008349 if (!Compound->body_empty()) {
8350 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008351 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008352 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008353 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8354 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008355 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008356 }
John McCall31168b02011-06-15 23:02:42 +00008357
John Wiegley01296292011-04-08 18:41:53 +00008358 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008359 // Do function/array conversion on the last expression, but not
8360 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008361 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8362 if (LastExpr.isInvalid())
8363 return ExprError();
8364 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008365
John Wiegley01296292011-04-08 18:41:53 +00008366 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008367 // In ARC, if the final expression ends in a consume, splice
8368 // the consume out and bind it later. In the alternate case
8369 // (when dealing with a retainable type), the result
8370 // initialization will create a produce. In both cases the
8371 // result will be +1, and we'll need to balance that out with
8372 // a bind.
8373 if (Expr *rebuiltLastStmt
8374 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8375 LastExpr = rebuiltLastStmt;
8376 } else {
8377 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008378 InitializedEntity::InitializeResult(LPLoc,
8379 Ty,
8380 false),
8381 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008382 LastExpr);
8383 }
8384
John Wiegley01296292011-04-08 18:41:53 +00008385 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008386 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008387 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008388 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008389 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008390 else
John Wiegley01296292011-04-08 18:41:53 +00008391 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008392 StmtExprMayBindToTemp = true;
8393 }
8394 }
8395 }
Chris Lattner944d3062008-07-26 19:51:01 +00008396 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008397
Eli Friedmanba961a92009-03-23 00:24:07 +00008398 // FIXME: Check that expression type is complete/non-abstract; statement
8399 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008400 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8401 if (StmtExprMayBindToTemp)
8402 return MaybeBindToTemporary(ResStmtExpr);
8403 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008404}
Steve Naroff78864672007-08-01 22:05:33 +00008405
John McCalldadc5752010-08-24 06:29:42 +00008406ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008407 TypeSourceInfo *TInfo,
8408 OffsetOfComponent *CompPtr,
8409 unsigned NumComponents,
8410 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008411 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008412 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008413 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008414
Chris Lattnerf17bd422007-08-30 17:45:32 +00008415 // We must have at least one component that refers to the type, and the first
8416 // one is known to be a field designator. Verify that the ArgTy represents
8417 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008418 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008419 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8420 << ArgTy << TypeRange);
8421
8422 // Type must be complete per C99 7.17p3 because a declaring a variable
8423 // with an incomplete type would be ill-formed.
8424 if (!Dependent
8425 && RequireCompleteType(BuiltinLoc, ArgTy,
8426 PDiag(diag::err_offsetof_incomplete_type)
8427 << TypeRange))
8428 return ExprError();
8429
Chris Lattner78502cf2007-08-31 21:49:13 +00008430 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8431 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008432 // FIXME: This diagnostic isn't actually visible because the location is in
8433 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008434 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008435 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8436 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008437
8438 bool DidWarnAboutNonPOD = false;
8439 QualType CurrentType = ArgTy;
8440 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008441 SmallVector<OffsetOfNode, 4> Comps;
8442 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008443 for (unsigned i = 0; i != NumComponents; ++i) {
8444 const OffsetOfComponent &OC = CompPtr[i];
8445 if (OC.isBrackets) {
8446 // Offset of an array sub-field. TODO: Should we allow vector elements?
8447 if (!CurrentType->isDependentType()) {
8448 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8449 if(!AT)
8450 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8451 << CurrentType);
8452 CurrentType = AT->getElementType();
8453 } else
8454 CurrentType = Context.DependentTy;
8455
8456 // The expression must be an integral expression.
8457 // FIXME: An integral constant expression?
8458 Expr *Idx = static_cast<Expr*>(OC.U.E);
8459 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8460 !Idx->getType()->isIntegerType())
8461 return ExprError(Diag(Idx->getLocStart(),
8462 diag::err_typecheck_subscript_not_integer)
8463 << Idx->getSourceRange());
8464
8465 // Record this array index.
8466 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8467 Exprs.push_back(Idx);
8468 continue;
8469 }
8470
8471 // Offset of a field.
8472 if (CurrentType->isDependentType()) {
8473 // We have the offset of a field, but we can't look into the dependent
8474 // type. Just record the identifier of the field.
8475 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8476 CurrentType = Context.DependentTy;
8477 continue;
8478 }
8479
8480 // We need to have a complete type to look into.
8481 if (RequireCompleteType(OC.LocStart, CurrentType,
8482 diag::err_offsetof_incomplete_type))
8483 return ExprError();
8484
8485 // Look for the designated field.
8486 const RecordType *RC = CurrentType->getAs<RecordType>();
8487 if (!RC)
8488 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8489 << CurrentType);
8490 RecordDecl *RD = RC->getDecl();
8491
8492 // C++ [lib.support.types]p5:
8493 // The macro offsetof accepts a restricted set of type arguments in this
8494 // International Standard. type shall be a POD structure or a POD union
8495 // (clause 9).
8496 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8497 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008498 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008499 PDiag(diag::warn_offsetof_non_pod_type)
8500 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8501 << CurrentType))
8502 DidWarnAboutNonPOD = true;
8503 }
8504
8505 // Look for the field.
8506 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8507 LookupQualifiedName(R, RD);
8508 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008509 IndirectFieldDecl *IndirectMemberDecl = 0;
8510 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008511 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008512 MemberDecl = IndirectMemberDecl->getAnonField();
8513 }
8514
Douglas Gregor882211c2010-04-28 22:16:22 +00008515 if (!MemberDecl)
8516 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8517 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8518 OC.LocEnd));
8519
Douglas Gregor10982ea2010-04-28 22:36:06 +00008520 // C99 7.17p3:
8521 // (If the specified member is a bit-field, the behavior is undefined.)
8522 //
8523 // We diagnose this as an error.
8524 if (MemberDecl->getBitWidth()) {
8525 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8526 << MemberDecl->getDeclName()
8527 << SourceRange(BuiltinLoc, RParenLoc);
8528 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8529 return ExprError();
8530 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008531
8532 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008533 if (IndirectMemberDecl)
8534 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008535
Douglas Gregord1702062010-04-29 00:18:15 +00008536 // If the member was found in a base class, introduce OffsetOfNodes for
8537 // the base class indirections.
8538 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8539 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008540 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008541 CXXBasePath &Path = Paths.front();
8542 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8543 B != BEnd; ++B)
8544 Comps.push_back(OffsetOfNode(B->Base));
8545 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008546
Francois Pichet783dd6e2010-11-21 06:08:52 +00008547 if (IndirectMemberDecl) {
8548 for (IndirectFieldDecl::chain_iterator FI =
8549 IndirectMemberDecl->chain_begin(),
8550 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8551 assert(isa<FieldDecl>(*FI));
8552 Comps.push_back(OffsetOfNode(OC.LocStart,
8553 cast<FieldDecl>(*FI), OC.LocEnd));
8554 }
8555 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008556 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008557
Douglas Gregor882211c2010-04-28 22:16:22 +00008558 CurrentType = MemberDecl->getType().getNonReferenceType();
8559 }
8560
8561 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8562 TInfo, Comps.data(), Comps.size(),
8563 Exprs.data(), Exprs.size(), RParenLoc));
8564}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008565
John McCalldadc5752010-08-24 06:29:42 +00008566ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008567 SourceLocation BuiltinLoc,
8568 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008569 ParsedType ParsedArgTy,
John McCall36226622010-10-12 02:09:17 +00008570 OffsetOfComponent *CompPtr,
8571 unsigned NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008572 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +00008573
Douglas Gregor882211c2010-04-28 22:16:22 +00008574 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00008575 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +00008576 if (ArgTy.isNull())
8577 return ExprError();
8578
Eli Friedman06dcfd92010-08-05 10:15:45 +00008579 if (!ArgTInfo)
8580 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8581
8582 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008583 RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008584}
8585
8586
John McCalldadc5752010-08-24 06:29:42 +00008587ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008588 Expr *CondExpr,
8589 Expr *LHSExpr, Expr *RHSExpr,
8590 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008591 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8592
John McCall7decc9e2010-11-18 06:31:45 +00008593 ExprValueKind VK = VK_RValue;
8594 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008595 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008596 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008597 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008598 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008599 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008600 } else {
8601 // The conditional expression is required to be a constant expression.
8602 llvm::APSInt condEval(32);
8603 SourceLocation ExpLoc;
8604 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008605 return ExprError(Diag(ExpLoc,
8606 diag::err_typecheck_choose_expr_requires_constant)
8607 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008608
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008609 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008610 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8611
8612 resType = ActiveExpr->getType();
8613 ValueDependent = ActiveExpr->isValueDependent();
8614 VK = ActiveExpr->getValueKind();
8615 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008616 }
8617
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008618 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008619 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008620 resType->isDependentType(),
8621 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008622}
8623
Steve Naroffc540d662008-09-03 18:15:37 +00008624//===----------------------------------------------------------------------===//
8625// Clang Extensions.
8626//===----------------------------------------------------------------------===//
8627
8628/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +00008629void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008630 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuba63ce62011-09-09 01:45:06 +00008631 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008632 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +00008633 if (CurScope)
8634 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008635 else
8636 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008637}
8638
Mike Stump82f071f2009-02-04 22:31:32 +00008639void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008640 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008641 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008642 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008643
John McCall8cb7bdf2010-06-04 23:28:52 +00008644 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008645 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008646
John McCall3882ace2011-01-05 12:14:39 +00008647 // GetTypeForDeclarator always produces a function type for a block
8648 // literal signature. Furthermore, it is always a FunctionProtoType
8649 // unless the function was written with a typedef.
8650 assert(T->isFunctionType() &&
8651 "GetTypeForDeclarator made a non-function block signature");
8652
8653 // Look for an explicit signature in that function type.
8654 FunctionProtoTypeLoc ExplicitSignature;
8655
8656 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8657 if (isa<FunctionProtoTypeLoc>(tmp)) {
8658 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8659
8660 // Check whether that explicit signature was synthesized by
8661 // GetTypeForDeclarator. If so, don't save that as part of the
8662 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008663 if (ExplicitSignature.getLocalRangeBegin() ==
8664 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008665 // This would be much cheaper if we stored TypeLocs instead of
8666 // TypeSourceInfos.
8667 TypeLoc Result = ExplicitSignature.getResultLoc();
8668 unsigned Size = Result.getFullDataSize();
8669 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8670 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8671
8672 ExplicitSignature = FunctionProtoTypeLoc();
8673 }
John McCalla3ccba02010-06-04 11:21:44 +00008674 }
Mike Stump11289f42009-09-09 15:08:12 +00008675
John McCall3882ace2011-01-05 12:14:39 +00008676 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8677 CurBlock->FunctionType = T;
8678
8679 const FunctionType *Fn = T->getAs<FunctionType>();
8680 QualType RetTy = Fn->getResultType();
8681 bool isVariadic =
8682 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8683
John McCall8e346702010-06-04 19:02:56 +00008684 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008685
John McCalla3ccba02010-06-04 11:21:44 +00008686 // Don't allow returning a objc interface by value.
8687 if (RetTy->isObjCObjectType()) {
8688 Diag(ParamInfo.getSourceRange().getBegin(),
8689 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8690 return;
8691 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008692
John McCalla3ccba02010-06-04 11:21:44 +00008693 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008694 // return type. TODO: what should we do with declarators like:
8695 // ^ * { ... }
8696 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008697 if (RetTy != Context.DependentTy)
8698 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008699
John McCalla3ccba02010-06-04 11:21:44 +00008700 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008701 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008702 if (ExplicitSignature) {
8703 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8704 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008705 if (Param->getIdentifier() == 0 &&
8706 !Param->isImplicit() &&
8707 !Param->isInvalidDecl() &&
8708 !getLangOptions().CPlusPlus)
8709 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008710 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008711 }
John McCalla3ccba02010-06-04 11:21:44 +00008712
8713 // Fake up parameter variables if we have a typedef, like
8714 // ^ fntype { ... }
8715 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8716 for (FunctionProtoType::arg_type_iterator
8717 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8718 ParmVarDecl *Param =
8719 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8720 ParamInfo.getSourceRange().getBegin(),
8721 *I);
John McCall8e346702010-06-04 19:02:56 +00008722 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008723 }
Steve Naroffc540d662008-09-03 18:15:37 +00008724 }
John McCalla3ccba02010-06-04 11:21:44 +00008725
John McCall8e346702010-06-04 19:02:56 +00008726 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008727 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +00008728 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +00008729 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8730 CurBlock->TheDecl->param_end(),
8731 /*CheckParameterNames=*/false);
8732 }
8733
John McCalla3ccba02010-06-04 11:21:44 +00008734 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008735 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008736
John McCall8e346702010-06-04 19:02:56 +00008737 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008738 Diag(ParamInfo.getAttributes()->getLoc(),
8739 diag::warn_attribute_sentinel_not_variadic) << 1;
8740 // FIXME: remove the attribute.
8741 }
8742
8743 // Put the parameter variables in scope. We can bail out immediately
8744 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008745 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008746 return;
8747
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008748 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008749 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8750 (*AI)->setOwningFunction(CurBlock->TheDecl);
8751
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008752 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008753 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008754 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008755
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008756 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008757 }
John McCallf7b2fb52010-01-22 00:28:27 +00008758 }
Steve Naroffc540d662008-09-03 18:15:37 +00008759}
8760
8761/// ActOnBlockError - If there is an error parsing a block, this callback
8762/// is invoked to pop the information about the block from the action impl.
8763void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008764 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008765 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008766 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008767}
8768
8769/// ActOnBlockStmtExpr - This is called when the body of a block statement
8770/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008771ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008772 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008773 // If blocks are disabled, emit an error.
8774 if (!LangOpts.Blocks)
8775 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008776
Douglas Gregor9a28e842010-03-01 23:15:13 +00008777 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008778
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008779 PopDeclContext();
8780
Steve Naroffc540d662008-09-03 18:15:37 +00008781 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008782 if (!BSI->ReturnType.isNull())
8783 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008784
Mike Stump3bf1ab42009-07-28 22:04:01 +00008785 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008786 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008787
John McCallc63de662011-02-02 13:00:07 +00008788 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008789 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8790 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00008791
John McCall8e346702010-06-04 19:02:56 +00008792 // If the user wrote a function type in some form, try to use that.
8793 if (!BSI->FunctionType.isNull()) {
8794 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8795
8796 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8797 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8798
8799 // Turn protoless block types into nullary block types.
8800 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008801 FunctionProtoType::ExtProtoInfo EPI;
8802 EPI.ExtInfo = Ext;
8803 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008804
8805 // Otherwise, if we don't need to change anything about the function type,
8806 // preserve its sugar structure.
8807 } else if (FTy->getResultType() == RetTy &&
8808 (!NoReturn || FTy->getNoReturnAttr())) {
8809 BlockTy = BSI->FunctionType;
8810
8811 // Otherwise, make the minimal modifications to the function type.
8812 } else {
8813 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008814 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8815 EPI.TypeQuals = 0; // FIXME: silently?
8816 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008817 BlockTy = Context.getFunctionType(RetTy,
8818 FPT->arg_type_begin(),
8819 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008820 EPI);
John McCall8e346702010-06-04 19:02:56 +00008821 }
8822
8823 // If we don't have a function type, just build one from nothing.
8824 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008825 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00008826 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008827 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008828 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008829
John McCall8e346702010-06-04 19:02:56 +00008830 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8831 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008832 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008833
Chris Lattner45542ea2009-04-19 05:28:12 +00008834 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00008835 if (getCurFunction()->NeedsScopeChecking() &&
8836 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008837 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008838
Chris Lattner60f84492011-02-17 23:58:47 +00008839 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008840
Fariborz Jahanian256d39d2011-07-11 18:04:54 +00008841 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8842 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8843 const VarDecl *variable = ci->getVariable();
8844 QualType T = variable->getType();
8845 QualType::DestructionKind destructKind = T.isDestructedType();
8846 if (destructKind != QualType::DK_none)
8847 getCurFunction()->setHasBranchProtectedScope();
8848 }
8849
Douglas Gregor49695f02011-09-06 20:46:03 +00008850 computeNRVO(Body, getCurBlock());
8851
Benjamin Kramera4fb8362011-07-12 14:11:05 +00008852 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8853 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8854 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8855
Douglas Gregor9a28e842010-03-01 23:15:13 +00008856 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008857}
8858
John McCalldadc5752010-08-24 06:29:42 +00008859ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008860 Expr *E, ParsedType Ty,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008861 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008862 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00008863 GetTypeFromParser(Ty, &TInfo);
8864 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008865}
8866
John McCalldadc5752010-08-24 06:29:42 +00008867ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008868 Expr *E, TypeSourceInfo *TInfo,
8869 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008870 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008871
Eli Friedman121ba0c2008-08-09 23:32:40 +00008872 // Get the va_list type
8873 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008874 if (VaListType->isArrayType()) {
8875 // Deal with implicit array decay; for example, on x86-64,
8876 // va_list is an array, but it's supposed to decay to
8877 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008878 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008879 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00008880 ExprResult Result = UsualUnaryConversions(E);
8881 if (Result.isInvalid())
8882 return ExprError();
8883 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00008884 } else {
8885 // Otherwise, the va_list argument must be an l-value because
8886 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008887 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008888 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008889 return ExprError();
8890 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008891
Douglas Gregorad3150c2009-05-19 23:10:31 +00008892 if (!E->isTypeDependent() &&
8893 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008894 return ExprError(Diag(E->getLocStart(),
8895 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008896 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008897 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008898
David Majnemerc75d1a12011-06-14 05:17:32 +00008899 if (!TInfo->getType()->isDependentType()) {
8900 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8901 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8902 << TInfo->getTypeLoc().getSourceRange()))
8903 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00008904
David Majnemerc75d1a12011-06-14 05:17:32 +00008905 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8906 TInfo->getType(),
8907 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8908 << TInfo->getTypeLoc().getSourceRange()))
8909 return ExprError();
8910
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008911 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00008912 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008913 TInfo->getType()->isObjCLifetimeType()
8914 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8915 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00008916 << TInfo->getType()
8917 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008918 }
Eli Friedman6290ae42011-07-11 21:45:59 +00008919
8920 // Check for va_arg where arguments of the given type will be promoted
8921 // (i.e. this va_arg is guaranteed to have undefined behavior).
8922 QualType PromoteType;
8923 if (TInfo->getType()->isPromotableIntegerType()) {
8924 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8925 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8926 PromoteType = QualType();
8927 }
8928 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8929 PromoteType = Context.DoubleTy;
8930 if (!PromoteType.isNull())
8931 Diag(TInfo->getTypeLoc().getBeginLoc(),
8932 diag::warn_second_parameter_to_va_arg_never_compatible)
8933 << TInfo->getType()
8934 << PromoteType
8935 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00008936 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008937
Abramo Bagnara27db2392010-08-10 10:06:15 +00008938 QualType T = TInfo->getType().getNonLValueExprType(Context);
8939 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008940}
8941
John McCalldadc5752010-08-24 06:29:42 +00008942ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008943 // The type of __null will be int or long, depending on the size of
8944 // pointers on the target.
8945 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008946 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
8947 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008948 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008949 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008950 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008951 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008952 Ty = Context.LongLongTy;
8953 else {
David Blaikie83d382b2011-09-23 05:06:16 +00008954 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008955 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00008956
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008957 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008958}
8959
Alexis Huntc46382e2010-04-28 23:02:27 +00008960static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008961 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008962 if (!SemaRef.getLangOptions().ObjC1)
8963 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008964
Anders Carlssonace5d072009-11-10 04:46:30 +00008965 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8966 if (!PT)
8967 return;
8968
8969 // Check if the destination is of type 'id'.
8970 if (!PT->isObjCIdType()) {
8971 // Check if the destination is the 'NSString' interface.
8972 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8973 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8974 return;
8975 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008976
Anders Carlssonace5d072009-11-10 04:46:30 +00008977 // Strip off any parens and casts.
8978 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregorfb65e592011-07-27 05:40:30 +00008979 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00008980 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008981
Douglas Gregora771f462010-03-31 17:46:05 +00008982 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00008983}
8984
Chris Lattner9bad62c2008-01-04 18:04:52 +00008985bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8986 SourceLocation Loc,
8987 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00008988 Expr *SrcExpr, AssignmentAction Action,
8989 bool *Complained) {
8990 if (Complained)
8991 *Complained = false;
8992
Chris Lattner9bad62c2008-01-04 18:04:52 +00008993 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00008994 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008995 bool isInvalid = false;
8996 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00008997 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00008998 ConversionFixItGenerator ConvHints;
8999 bool MayHaveConvFixit = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009000
Chris Lattner9bad62c2008-01-04 18:04:52 +00009001 switch (ConvTy) {
David Blaikie83d382b2011-09-23 05:06:16 +00009002 default: llvm_unreachable("Unknown conversion type");
Chris Lattner9bad62c2008-01-04 18:04:52 +00009003 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009004 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009005 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00009006 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9007 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009008 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009009 case IntToPointer:
9010 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00009011 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9012 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009013 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009014 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009015 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009016 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00009017 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9018 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00009019 if (Hint.isNull() && !CheckInferredResultType) {
9020 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9021 }
9022 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009023 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009024 case IncompatiblePointerSign:
9025 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9026 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009027 case FunctionVoidPointer:
9028 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9029 break;
John McCall4fff8f62011-02-01 00:10:29 +00009030 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009031 // Perform array-to-pointer decay if necessary.
9032 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9033
John McCall4fff8f62011-02-01 00:10:29 +00009034 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9035 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9036 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9037 DiagKind = diag::err_typecheck_incompatible_address_space;
9038 break;
John McCall31168b02011-06-15 23:02:42 +00009039
9040
9041 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009042 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00009043 break;
John McCall4fff8f62011-02-01 00:10:29 +00009044 }
9045
9046 llvm_unreachable("unknown error case for discarding qualifiers!");
9047 // fallthrough
9048 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009049 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009050 // If the qualifiers lost were because we were applying the
9051 // (deprecated) C++ conversion from a string literal to a char*
9052 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9053 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009054 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009055 // bit of refactoring (so that the second argument is an
9056 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009057 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009058 // C++ semantics.
9059 if (getLangOptions().CPlusPlus &&
9060 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9061 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009062 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9063 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009064 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009065 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009066 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009067 case IntToBlockPointer:
9068 DiagKind = diag::err_int_to_block_pointer;
9069 break;
9070 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009071 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009072 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009073 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009074 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009075 // it can give a more specific diagnostic.
9076 DiagKind = diag::warn_incompatible_qualified_id;
9077 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009078 case IncompatibleVectors:
9079 DiagKind = diag::warn_incompatible_vectors;
9080 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00009081 case IncompatibleObjCWeakRef:
9082 DiagKind = diag::err_arc_weak_unavailable_assign;
9083 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009084 case Incompatible:
9085 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00009086 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9087 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009088 isInvalid = true;
9089 break;
9090 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009091
Douglas Gregorc68e1402010-04-09 00:35:39 +00009092 QualType FirstType, SecondType;
9093 switch (Action) {
9094 case AA_Assigning:
9095 case AA_Initializing:
9096 // The destination type comes first.
9097 FirstType = DstType;
9098 SecondType = SrcType;
9099 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009100
Douglas Gregorc68e1402010-04-09 00:35:39 +00009101 case AA_Returning:
9102 case AA_Passing:
9103 case AA_Converting:
9104 case AA_Sending:
9105 case AA_Casting:
9106 // The source type comes first.
9107 FirstType = SrcType;
9108 SecondType = DstType;
9109 break;
9110 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009111
Anna Zaks3b402712011-07-28 19:51:27 +00009112 PartialDiagnostic FDiag = PDiag(DiagKind);
9113 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9114
9115 // If we can fix the conversion, suggest the FixIts.
9116 assert(ConvHints.isNull() || Hint.isNull());
9117 if (!ConvHints.isNull()) {
9118 for (llvm::SmallVector<FixItHint, 1>::iterator
9119 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
9120 HI != HE; ++HI)
9121 FDiag << *HI;
9122 } else {
9123 FDiag << Hint;
9124 }
9125 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9126
9127 Diag(Loc, FDiag);
9128
Douglas Gregor33823722011-06-11 01:09:30 +00009129 if (CheckInferredResultType)
9130 EmitRelatedResultTypeNote(SrcExpr);
9131
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009132 if (Complained)
9133 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009134 return isInvalid;
9135}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009136
Chris Lattnerc71d08b2009-04-25 21:59:05 +00009137bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009138 llvm::APSInt ICEResult;
9139 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9140 if (Result)
9141 *Result = ICEResult;
9142 return false;
9143 }
9144
Anders Carlssone54e8a12008-11-30 19:50:32 +00009145 Expr::EvalResult EvalResult;
9146
Mike Stump4e1f26a2009-02-19 03:04:26 +00009147 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00009148 EvalResult.HasSideEffects) {
9149 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9150
9151 if (EvalResult.Diag) {
9152 // We only show the note if it's not the usual "invalid subexpression"
9153 // or if it's actually in a subexpression.
9154 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9155 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9156 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9157 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009158
Anders Carlssone54e8a12008-11-30 19:50:32 +00009159 return true;
9160 }
9161
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009162 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9163 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009164
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009165 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009166 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
David Blaikie9c902b52011-09-25 23:23:43 +00009167 != DiagnosticsEngine::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009168 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009169
Anders Carlssone54e8a12008-11-30 19:50:32 +00009170 if (Result)
9171 *Result = EvalResult.Val.getInt();
9172 return false;
9173}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009174
Douglas Gregorff790f12009-11-26 00:44:06 +00009175void
Mike Stump11289f42009-09-09 15:08:12 +00009176Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009177 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00009178 ExpressionEvaluationContextRecord(NewContext,
9179 ExprTemporaries.size(),
9180 ExprNeedsCleanups));
9181 ExprNeedsCleanups = false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009182}
9183
Richard Trieucfc491d2011-08-02 04:35:43 +00009184void Sema::PopExpressionEvaluationContext() {
Douglas Gregorff790f12009-11-26 00:44:06 +00009185 // Pop the current expression evaluation context off the stack.
9186 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9187 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009188
Douglas Gregorfab31f42009-12-12 07:57:52 +00009189 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9190 if (Rec.PotentiallyReferenced) {
9191 // Mark any remaining declarations in the current position of the stack
9192 // as "referenced". If they were not meant to be referenced, semantic
9193 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009194 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009195 I = Rec.PotentiallyReferenced->begin(),
9196 IEnd = Rec.PotentiallyReferenced->end();
9197 I != IEnd; ++I)
9198 MarkDeclarationReferenced(I->first, I->second);
9199 }
9200
9201 if (Rec.PotentiallyDiagnosed) {
9202 // Emit any pending diagnostics.
9203 for (PotentiallyEmittedDiagnostics::iterator
9204 I = Rec.PotentiallyDiagnosed->begin(),
9205 IEnd = Rec.PotentiallyDiagnosed->end();
9206 I != IEnd; ++I)
9207 Diag(I->first, I->second);
9208 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009209 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009210
9211 // When are coming out of an unevaluated context, clear out any
9212 // temporaries that we may have created as part of the evaluation of
9213 // the expression in that context: they aren't relevant because they
9214 // will never be constructed.
John McCall31168b02011-06-15 23:02:42 +00009215 if (Rec.Context == Unevaluated) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009216 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9217 ExprTemporaries.end());
John McCall31168b02011-06-15 23:02:42 +00009218 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9219
9220 // Otherwise, merge the contexts together.
9221 } else {
9222 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9223 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009224
9225 // Destroy the popped expression evaluation record.
9226 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009227}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009228
John McCall31168b02011-06-15 23:02:42 +00009229void Sema::DiscardCleanupsInEvaluationContext() {
9230 ExprTemporaries.erase(
9231 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
9232 ExprTemporaries.end());
9233 ExprNeedsCleanups = false;
9234}
9235
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009236/// \brief Note that the given declaration was referenced in the source code.
9237///
9238/// This routine should be invoke whenever a given declaration is referenced
9239/// in the source code, and where that reference occurred. If this declaration
9240/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9241/// C99 6.9p3), then the declaration will be marked as used.
9242///
9243/// \param Loc the location where the declaration was referenced.
9244///
9245/// \param D the declaration that has been referenced by the source code.
9246void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9247 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009248
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00009249 D->setReferenced();
9250
Douglas Gregorebada0772010-06-17 23:14:26 +00009251 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009252 return;
Mike Stump11289f42009-09-09 15:08:12 +00009253
Richard Trieucfc491d2011-08-02 04:35:43 +00009254 // Mark a parameter or variable declaration "used", regardless of whether
9255 // we're in a template or not. The reason for this is that unevaluated
9256 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9257 // (-Wunused-variables and -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009258 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009259 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009260 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009261 return;
9262 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009263
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009264 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9265 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009266
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009267 // Do not mark anything as "used" within a dependent context; wait for
9268 // an instantiation.
9269 if (CurContext->isDependentContext())
9270 return;
Mike Stump11289f42009-09-09 15:08:12 +00009271
Douglas Gregorff790f12009-11-26 00:44:06 +00009272 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009273 case Unevaluated:
9274 // We are in an expression that is not potentially evaluated; do nothing.
9275 return;
Mike Stump11289f42009-09-09 15:08:12 +00009276
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009277 case PotentiallyEvaluated:
9278 // We are in a potentially-evaluated expression, so this declaration is
9279 // "used"; handle this below.
9280 break;
Mike Stump11289f42009-09-09 15:08:12 +00009281
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009282 case PotentiallyPotentiallyEvaluated:
9283 // We are in an expression that may be potentially evaluated; queue this
9284 // declaration reference until we know whether the expression is
9285 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009286 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009287 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009288
9289 case PotentiallyEvaluatedIfUsed:
9290 // Referenced declarations will only be used if the construct in the
9291 // containing expression is used.
9292 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009293 }
Mike Stump11289f42009-09-09 15:08:12 +00009294
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009295 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009296 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009297 if (Constructor->isDefaulted()) {
9298 if (Constructor->isDefaultConstructor()) {
9299 if (Constructor->isTrivial())
9300 return;
9301 if (!Constructor->isUsed(false))
9302 DefineImplicitDefaultConstructor(Loc, Constructor);
9303 } else if (Constructor->isCopyConstructor()) {
9304 if (!Constructor->isUsed(false))
9305 DefineImplicitCopyConstructor(Loc, Constructor);
9306 } else if (Constructor->isMoveConstructor()) {
9307 if (!Constructor->isUsed(false))
9308 DefineImplicitMoveConstructor(Loc, Constructor);
9309 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009310 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009311
Douglas Gregor88d292c2010-05-13 16:44:06 +00009312 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009313 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Alexis Huntf91729462011-05-12 22:46:25 +00009314 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009315 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009316 if (Destructor->isVirtual())
9317 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009318 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Alexis Huntc9a55732011-05-14 05:23:28 +00009319 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009320 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009321 if (!MethodDecl->isUsed(false)) {
9322 if (MethodDecl->isCopyAssignmentOperator())
9323 DefineImplicitCopyAssignment(Loc, MethodDecl);
9324 else
9325 DefineImplicitMoveAssignment(Loc, MethodDecl);
9326 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00009327 } else if (MethodDecl->isVirtual())
9328 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009329 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009330 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009331 // Recursive functions should be marked when used from another function.
9332 if (CurContext == Function) return;
9333
Mike Stump11289f42009-09-09 15:08:12 +00009334 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009335 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009336 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009337 bool AlreadyInstantiated = false;
9338 if (FunctionTemplateSpecializationInfo *SpecInfo
9339 = Function->getTemplateSpecializationInfo()) {
9340 if (SpecInfo->getPointOfInstantiation().isInvalid())
9341 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009342 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009343 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009344 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009345 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009346 = Function->getMemberSpecializationInfo()) {
9347 if (MSInfo->getPointOfInstantiation().isInvalid())
9348 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009349 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009350 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009351 AlreadyInstantiated = true;
9352 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009353
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009354 if (!AlreadyInstantiated) {
9355 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9356 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9357 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9358 Loc));
9359 else
Chandler Carruth54080172010-08-25 08:44:16 +00009360 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009361 }
John McCall83779672011-02-19 02:53:41 +00009362 } else {
9363 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009364 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9365 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009366 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009367 MarkDeclarationReferenced(Loc, *i);
9368 }
John McCall83779672011-02-19 02:53:41 +00009369 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009370
John McCall83779672011-02-19 02:53:41 +00009371 // Keep track of used but undefined functions.
9372 if (!Function->isPure() && !Function->hasBody() &&
9373 Function->getLinkage() != ExternalLinkage) {
9374 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9375 if (old.isInvalid()) old = Loc;
9376 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009377
John McCall83779672011-02-19 02:53:41 +00009378 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009379 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009380 }
Mike Stump11289f42009-09-09 15:08:12 +00009381
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009382 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009383 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009384 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009385 Var->getInstantiatedFromStaticDataMember()) {
9386 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9387 assert(MSInfo && "Missing member specialization information?");
9388 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9389 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9390 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redl2ac2c722011-04-29 08:19:30 +00009391 // This is a modification of an existing AST node. Notify listeners.
9392 if (ASTMutationListener *L = getASTMutationListener())
9393 L->StaticDataMemberInstantiated(Var);
Chandler Carruth54080172010-08-25 08:44:16 +00009394 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009395 }
9396 }
Mike Stump11289f42009-09-09 15:08:12 +00009397
John McCall15dd4042011-02-21 19:25:48 +00009398 // Keep track of used but undefined variables. We make a hole in
9399 // the warning for static const data members with in-line
9400 // initializers.
John McCall83779672011-02-19 02:53:41 +00009401 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009402 && Var->getLinkage() != ExternalLinkage
9403 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009404 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9405 if (old.isInvalid()) old = Loc;
9406 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009407
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009408 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009409 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009410 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009411}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009412
Douglas Gregor5597ab42010-05-07 23:12:07 +00009413namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009414 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009415 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009416 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009417 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9418 Sema &S;
9419 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009420
Douglas Gregor5597ab42010-05-07 23:12:07 +00009421 public:
9422 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009423
Douglas Gregor5597ab42010-05-07 23:12:07 +00009424 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009425
9426 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9427 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009428 };
9429}
9430
Chandler Carruthaf80f662010-06-09 08:17:30 +00009431bool MarkReferencedDecls::TraverseTemplateArgument(
9432 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009433 if (Arg.getKind() == TemplateArgument::Declaration) {
9434 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9435 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009436
9437 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009438}
9439
Chandler Carruthaf80f662010-06-09 08:17:30 +00009440bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009441 if (ClassTemplateSpecializationDecl *Spec
9442 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9443 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009444 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009445 }
9446
Chandler Carruthc65667c2010-06-10 10:31:57 +00009447 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009448}
9449
9450void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9451 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009452 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009453}
9454
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009455namespace {
9456 /// \brief Helper class that marks all of the declarations referenced by
9457 /// potentially-evaluated subexpressions as "referenced".
9458 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9459 Sema &S;
9460
9461 public:
9462 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9463
9464 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9465
9466 void VisitDeclRefExpr(DeclRefExpr *E) {
9467 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9468 }
9469
9470 void VisitMemberExpr(MemberExpr *E) {
9471 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009472 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009473 }
9474
9475 void VisitCXXNewExpr(CXXNewExpr *E) {
9476 if (E->getConstructor())
9477 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9478 if (E->getOperatorNew())
9479 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9480 if (E->getOperatorDelete())
9481 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009482 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009483 }
9484
9485 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9486 if (E->getOperatorDelete())
9487 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009488 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9489 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9490 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9491 S.MarkDeclarationReferenced(E->getLocStart(),
9492 S.LookupDestructor(Record));
9493 }
9494
Douglas Gregor32b3de52010-09-11 23:32:50 +00009495 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009496 }
9497
9498 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9499 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009500 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009501 }
9502
9503 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9504 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9505 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009506
9507 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9508 Visit(E->getExpr());
9509 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009510 };
9511}
9512
9513/// \brief Mark any declarations that appear within this expression or any
9514/// potentially-evaluated subexpressions as "referenced".
9515void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9516 EvaluatedExprMarker(*this).Visit(E);
9517}
9518
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009519/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9520/// of the program being compiled.
9521///
9522/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009523/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009524/// possibility that the code will actually be executable. Code in sizeof()
9525/// expressions, code used only during overload resolution, etc., are not
9526/// potentially evaluated. This routine will suppress such diagnostics or,
9527/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009528/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009529/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009530///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009531/// This routine should be used for all diagnostics that describe the run-time
9532/// behavior of a program, such as passing a non-POD value through an ellipsis.
9533/// Failure to do so will likely result in spurious diagnostics or failures
9534/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +00009535bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009536 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +00009537 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009538 case Unevaluated:
9539 // The argument will never be evaluated, so don't complain.
9540 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009541
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009542 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009543 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +00009544 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00009545 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +00009546 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +00009547 }
9548 else
9549 Diag(Loc, PD);
9550
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009551 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009552
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009553 case PotentiallyPotentiallyEvaluated:
9554 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9555 break;
9556 }
9557
9558 return false;
9559}
9560
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009561bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9562 CallExpr *CE, FunctionDecl *FD) {
9563 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9564 return false;
9565
9566 PartialDiagnostic Note =
9567 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9568 << FD->getDeclName() : PDiag();
9569 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009570
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009571 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009572 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009573 PDiag(diag::err_call_function_incomplete_return)
9574 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009575 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009576 << CE->getSourceRange(),
9577 std::make_pair(NoteLoc, Note)))
9578 return true;
9579
9580 return false;
9581}
9582
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009583// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009584// will prevent this condition from triggering, which is what we want.
9585void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9586 SourceLocation Loc;
9587
John McCall0506e4a2009-11-11 02:41:58 +00009588 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009589 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009590
Chandler Carruthf87d6c02011-08-16 22:30:10 +00009591 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009592 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009593 return;
9594
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009595 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9596
John McCallb0e419e2009-11-12 00:06:05 +00009597 // Greylist some idioms by putting them into a warning subcategory.
9598 if (ObjCMessageExpr *ME
9599 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9600 Selector Sel = ME->getSelector();
9601
John McCallb0e419e2009-11-12 00:06:05 +00009602 // self = [<foo> init...]
Douglas Gregor486b74e2011-09-27 16:10:05 +00009603 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009604 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9605
9606 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009607 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009608 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9609 }
John McCall0506e4a2009-11-11 02:41:58 +00009610
John McCalld5707ab2009-10-12 21:59:07 +00009611 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +00009612 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009613 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009614 return;
9615
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009616 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009617 Loc = Op->getOperatorLoc();
9618 } else {
9619 // Not an assignment.
9620 return;
9621 }
9622
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009623 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009624
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009625 SourceLocation Open = E->getSourceRange().getBegin();
9626 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9627 Diag(Loc, diag::note_condition_assign_silence)
9628 << FixItHint::CreateInsertion(Open, "(")
9629 << FixItHint::CreateInsertion(Close, ")");
9630
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009631 if (IsOrAssign)
9632 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9633 << FixItHint::CreateReplacement(Loc, "!=");
9634 else
9635 Diag(Loc, diag::note_condition_assign_to_comparison)
9636 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00009637}
9638
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009639/// \brief Redundant parentheses over an equality comparison can indicate
9640/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +00009641void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009642 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +00009643 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009644 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9645 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009646 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00009647 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009648 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009649
Richard Trieuba63ce62011-09-09 01:45:06 +00009650 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009651
9652 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009653 if (opE->getOpcode() == BO_EQ &&
9654 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9655 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009656 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009657
Ted Kremenekae022092011-02-02 02:20:30 +00009658 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +00009659 Diag(Loc, diag::note_equality_comparison_silence)
Richard Trieuba63ce62011-09-09 01:45:06 +00009660 << FixItHint::CreateRemoval(ParenE->getSourceRange().getBegin())
9661 << FixItHint::CreateRemoval(ParenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009662 Diag(Loc, diag::note_equality_comparison_to_assign)
9663 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009664 }
9665}
9666
John Wiegley01296292011-04-08 18:41:53 +00009667ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +00009668 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009669 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9670 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009671
John McCall0009fcc2011-04-26 20:42:42 +00009672 ExprResult result = CheckPlaceholderExpr(E);
9673 if (result.isInvalid()) return ExprError();
9674 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009675
John McCall0009fcc2011-04-26 20:42:42 +00009676 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +00009677 if (getLangOptions().CPlusPlus)
9678 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9679
John Wiegley01296292011-04-08 18:41:53 +00009680 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9681 if (ERes.isInvalid())
9682 return ExprError();
9683 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +00009684
9685 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +00009686 if (!T->isScalarType()) { // C99 6.8.4.1p1
9687 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9688 << T << E->getSourceRange();
9689 return ExprError();
9690 }
John McCalld5707ab2009-10-12 21:59:07 +00009691 }
9692
John Wiegley01296292011-04-08 18:41:53 +00009693 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +00009694}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009695
John McCalldadc5752010-08-24 06:29:42 +00009696ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009697 Expr *SubExpr) {
9698 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009699 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009700
Richard Trieuba63ce62011-09-09 01:45:06 +00009701 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +00009702}
John McCall36e7fe32010-10-12 00:20:44 +00009703
John McCall31996342011-04-07 08:22:57 +00009704namespace {
John McCall2979fe02011-04-12 00:42:48 +00009705 /// A visitor for rebuilding a call to an __unknown_any expression
9706 /// to have an appropriate type.
9707 struct RebuildUnknownAnyFunction
9708 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9709
9710 Sema &S;
9711
9712 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9713
9714 ExprResult VisitStmt(Stmt *S) {
9715 llvm_unreachable("unexpected statement!");
9716 return ExprError();
9717 }
9718
Richard Trieu10162ab2011-09-09 03:59:41 +00009719 ExprResult VisitExpr(Expr *E) {
9720 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
9721 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +00009722 return ExprError();
9723 }
9724
9725 /// Rebuild an expression which simply semantically wraps another
9726 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +00009727 template <class T> ExprResult rebuildSugarExpr(T *E) {
9728 ExprResult SubResult = Visit(E->getSubExpr());
9729 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +00009730
Richard Trieu10162ab2011-09-09 03:59:41 +00009731 Expr *SubExpr = SubResult.take();
9732 E->setSubExpr(SubExpr);
9733 E->setType(SubExpr->getType());
9734 E->setValueKind(SubExpr->getValueKind());
9735 assert(E->getObjectKind() == OK_Ordinary);
9736 return E;
John McCall2979fe02011-04-12 00:42:48 +00009737 }
9738
Richard Trieu10162ab2011-09-09 03:59:41 +00009739 ExprResult VisitParenExpr(ParenExpr *E) {
9740 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +00009741 }
9742
Richard Trieu10162ab2011-09-09 03:59:41 +00009743 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9744 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +00009745 }
9746
Richard Trieu10162ab2011-09-09 03:59:41 +00009747 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9748 ExprResult SubResult = Visit(E->getSubExpr());
9749 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +00009750
Richard Trieu10162ab2011-09-09 03:59:41 +00009751 Expr *SubExpr = SubResult.take();
9752 E->setSubExpr(SubExpr);
9753 E->setType(S.Context.getPointerType(SubExpr->getType()));
9754 assert(E->getValueKind() == VK_RValue);
9755 assert(E->getObjectKind() == OK_Ordinary);
9756 return E;
John McCall2979fe02011-04-12 00:42:48 +00009757 }
9758
Richard Trieu10162ab2011-09-09 03:59:41 +00009759 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
9760 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +00009761
Richard Trieu10162ab2011-09-09 03:59:41 +00009762 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +00009763
Richard Trieu10162ab2011-09-09 03:59:41 +00009764 assert(E->getValueKind() == VK_RValue);
John McCall2979fe02011-04-12 00:42:48 +00009765 if (S.getLangOptions().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +00009766 !(isa<CXXMethodDecl>(VD) &&
9767 cast<CXXMethodDecl>(VD)->isInstance()))
9768 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +00009769
Richard Trieu10162ab2011-09-09 03:59:41 +00009770 return E;
John McCall2979fe02011-04-12 00:42:48 +00009771 }
9772
Richard Trieu10162ab2011-09-09 03:59:41 +00009773 ExprResult VisitMemberExpr(MemberExpr *E) {
9774 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +00009775 }
9776
Richard Trieu10162ab2011-09-09 03:59:41 +00009777 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9778 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +00009779 }
9780 };
9781}
9782
9783/// Given a function expression of unknown-any type, try to rebuild it
9784/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +00009785static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
9786 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
9787 if (Result.isInvalid()) return ExprError();
9788 return S.DefaultFunctionArrayConversion(Result.take());
John McCall2979fe02011-04-12 00:42:48 +00009789}
9790
9791namespace {
John McCall2d2e8702011-04-11 07:02:50 +00009792 /// A visitor for rebuilding an expression of type __unknown_anytype
9793 /// into one which resolves the type directly on the referring
9794 /// expression. Strict preservation of the original source
9795 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +00009796 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +00009797 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +00009798
9799 Sema &S;
9800
9801 /// The current destination type.
9802 QualType DestType;
9803
Richard Trieu10162ab2011-09-09 03:59:41 +00009804 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
9805 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +00009806
John McCall39439732011-04-09 22:50:59 +00009807 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +00009808 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +00009809 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009810 }
9811
Richard Trieu10162ab2011-09-09 03:59:41 +00009812 ExprResult VisitExpr(Expr *E) {
9813 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9814 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +00009815 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009816 }
9817
Richard Trieu10162ab2011-09-09 03:59:41 +00009818 ExprResult VisitCallExpr(CallExpr *E);
9819 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +00009820
John McCall39439732011-04-09 22:50:59 +00009821 /// Rebuild an expression which simply semantically wraps another
9822 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +00009823 template <class T> ExprResult rebuildSugarExpr(T *E) {
9824 ExprResult SubResult = Visit(E->getSubExpr());
9825 if (SubResult.isInvalid()) return ExprError();
9826 Expr *SubExpr = SubResult.take();
9827 E->setSubExpr(SubExpr);
9828 E->setType(SubExpr->getType());
9829 E->setValueKind(SubExpr->getValueKind());
9830 assert(E->getObjectKind() == OK_Ordinary);
9831 return E;
John McCall39439732011-04-09 22:50:59 +00009832 }
John McCall31996342011-04-07 08:22:57 +00009833
Richard Trieu10162ab2011-09-09 03:59:41 +00009834 ExprResult VisitParenExpr(ParenExpr *E) {
9835 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +00009836 }
9837
Richard Trieu10162ab2011-09-09 03:59:41 +00009838 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9839 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +00009840 }
9841
Richard Trieu10162ab2011-09-09 03:59:41 +00009842 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9843 const PointerType *Ptr = DestType->getAs<PointerType>();
9844 if (!Ptr) {
9845 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
9846 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +00009847 return ExprError();
9848 }
Richard Trieu10162ab2011-09-09 03:59:41 +00009849 assert(E->getValueKind() == VK_RValue);
9850 assert(E->getObjectKind() == OK_Ordinary);
9851 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +00009852
9853 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +00009854 DestType = Ptr->getPointeeType();
9855 ExprResult SubResult = Visit(E->getSubExpr());
9856 if (SubResult.isInvalid()) return ExprError();
9857 E->setSubExpr(SubResult.take());
9858 return E;
John McCall2979fe02011-04-12 00:42:48 +00009859 }
9860
Richard Trieu10162ab2011-09-09 03:59:41 +00009861 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +00009862
Richard Trieu10162ab2011-09-09 03:59:41 +00009863 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +00009864
Richard Trieu10162ab2011-09-09 03:59:41 +00009865 ExprResult VisitMemberExpr(MemberExpr *E) {
9866 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +00009867 }
John McCall39439732011-04-09 22:50:59 +00009868
Richard Trieu10162ab2011-09-09 03:59:41 +00009869 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9870 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +00009871 }
9872 };
9873}
9874
John McCall2d2e8702011-04-11 07:02:50 +00009875/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +00009876ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
9877 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +00009878
9879 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +00009880 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +00009881 FK_FunctionPointer,
9882 FK_BlockPointer
9883 };
9884
Richard Trieu10162ab2011-09-09 03:59:41 +00009885 FnKind Kind;
9886 QualType CalleeType = CalleeExpr->getType();
9887 if (CalleeType == S.Context.BoundMemberTy) {
9888 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
9889 Kind = FK_MemberFunction;
9890 CalleeType = Expr::findBoundMemberType(CalleeExpr);
9891 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
9892 CalleeType = Ptr->getPointeeType();
9893 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +00009894 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +00009895 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
9896 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +00009897 }
Richard Trieu10162ab2011-09-09 03:59:41 +00009898 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +00009899
9900 // Verify that this is a legal result type of a function.
9901 if (DestType->isArrayType() || DestType->isFunctionType()) {
9902 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +00009903 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +00009904 diagID = diag::err_block_returning_array_function;
9905
Richard Trieu10162ab2011-09-09 03:59:41 +00009906 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +00009907 << DestType->isFunctionType() << DestType;
9908 return ExprError();
9909 }
9910
9911 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +00009912 E->setType(DestType.getNonLValueExprType(S.Context));
9913 E->setValueKind(Expr::getValueKindForType(DestType));
9914 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +00009915
9916 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu10162ab2011-09-09 03:59:41 +00009917 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall2d2e8702011-04-11 07:02:50 +00009918 DestType = S.Context.getFunctionType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +00009919 Proto->arg_type_begin(),
9920 Proto->getNumArgs(),
9921 Proto->getExtProtoInfo());
John McCall2d2e8702011-04-11 07:02:50 +00009922 else
9923 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +00009924 FnType->getExtInfo());
John McCall2d2e8702011-04-11 07:02:50 +00009925
9926 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +00009927 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +00009928 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +00009929 // Nothing to do.
9930 break;
9931
9932 case FK_FunctionPointer:
9933 DestType = S.Context.getPointerType(DestType);
9934 break;
9935
9936 case FK_BlockPointer:
9937 DestType = S.Context.getBlockPointerType(DestType);
9938 break;
9939 }
9940
9941 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +00009942 ExprResult CalleeResult = Visit(CalleeExpr);
9943 if (!CalleeResult.isUsable()) return ExprError();
9944 E->setCallee(CalleeResult.take());
John McCall2d2e8702011-04-11 07:02:50 +00009945
9946 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +00009947 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +00009948}
9949
Richard Trieu10162ab2011-09-09 03:59:41 +00009950ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +00009951 // Verify that this is a legal result type of a call.
9952 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +00009953 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +00009954 << DestType->isFunctionType() << DestType;
9955 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009956 }
9957
John McCall3f4138c2011-07-13 17:56:40 +00009958 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +00009959 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
9960 assert(Method->getResultType() == S.Context.UnknownAnyTy);
9961 Method->setResultType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +00009962 }
John McCall2979fe02011-04-12 00:42:48 +00009963
John McCall2d2e8702011-04-11 07:02:50 +00009964 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +00009965 E->setType(DestType.getNonReferenceType());
9966 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +00009967
Richard Trieu10162ab2011-09-09 03:59:41 +00009968 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +00009969}
9970
Richard Trieu10162ab2011-09-09 03:59:41 +00009971ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +00009972 // The only case we should ever see here is a function-to-pointer decay.
Richard Trieu10162ab2011-09-09 03:59:41 +00009973 assert(E->getCastKind() == CK_FunctionToPointerDecay);
9974 assert(E->getValueKind() == VK_RValue);
9975 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +00009976
Richard Trieu10162ab2011-09-09 03:59:41 +00009977 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +00009978
John McCall2d2e8702011-04-11 07:02:50 +00009979 // Rebuild the sub-expression as the pointee (function) type.
9980 DestType = DestType->castAs<PointerType>()->getPointeeType();
9981
Richard Trieu10162ab2011-09-09 03:59:41 +00009982 ExprResult Result = Visit(E->getSubExpr());
9983 if (!Result.isUsable()) return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009984
Richard Trieu10162ab2011-09-09 03:59:41 +00009985 E->setSubExpr(Result.take());
9986 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +00009987}
9988
Richard Trieu10162ab2011-09-09 03:59:41 +00009989ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
9990 ExprValueKind ValueKind = VK_LValue;
9991 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +00009992
9993 // We know how to make this work for certain kinds of decls:
9994
9995 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +00009996 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
9997 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
9998 DestType = Ptr->getPointeeType();
9999 ExprResult Result = resolveDecl(E, VD);
10000 if (Result.isInvalid()) return ExprError();
10001 return S.ImpCastExprToType(Result.take(), Type,
John McCall9a877fe2011-08-10 04:12:23 +000010002 CK_FunctionToPointerDecay, VK_RValue);
10003 }
10004
Richard Trieu10162ab2011-09-09 03:59:41 +000010005 if (!Type->isFunctionType()) {
10006 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
10007 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000010008 return ExprError();
10009 }
John McCall2d2e8702011-04-11 07:02:50 +000010010
Richard Trieu10162ab2011-09-09 03:59:41 +000010011 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
10012 if (MD->isInstance()) {
10013 ValueKind = VK_RValue;
10014 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000010015 }
10016
John McCall2d2e8702011-04-11 07:02:50 +000010017 // Function references aren't l-values in C.
10018 if (!S.getLangOptions().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000010019 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000010020
10021 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000010022 } else if (isa<VarDecl>(VD)) {
10023 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
10024 Type = RefTy->getPointeeType();
10025 } else if (Type->isFunctionType()) {
10026 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
10027 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000010028 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010029 }
10030
10031 // - nothing else
10032 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000010033 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10034 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000010035 return ExprError();
10036 }
10037
Richard Trieu10162ab2011-09-09 03:59:41 +000010038 VD->setType(DestType);
10039 E->setType(Type);
10040 E->setValueKind(ValueKind);
10041 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000010042}
10043
John McCall31996342011-04-07 08:22:57 +000010044/// Check a cast of an unknown-any type. We intentionally only
10045/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000010046ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
10047 Expr *CastExpr, CastKind &CastKind,
10048 ExprValueKind &VK, CXXCastPath &Path) {
John McCall31996342011-04-07 08:22:57 +000010049 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000010050 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000010051 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000010052
Richard Trieuba63ce62011-09-09 01:45:06 +000010053 CastExpr = result.take();
10054 VK = CastExpr->getValueKind();
10055 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000010056
Richard Trieuba63ce62011-09-09 01:45:06 +000010057 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000010058}
10059
Richard Trieuba63ce62011-09-09 01:45:06 +000010060static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
10061 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000010062 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000010063 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000010064 E = E->IgnoreParenImpCasts();
10065 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
10066 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000010067 diagID = diag::err_uncasted_call_of_unknown_any;
10068 } else {
John McCall31996342011-04-07 08:22:57 +000010069 break;
John McCall2d2e8702011-04-11 07:02:50 +000010070 }
John McCall31996342011-04-07 08:22:57 +000010071 }
10072
John McCall2d2e8702011-04-11 07:02:50 +000010073 SourceLocation loc;
10074 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000010075 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010076 loc = ref->getLocation();
10077 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000010078 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010079 loc = mem->getMemberLoc();
10080 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000010081 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010082 diagID = diag::err_uncasted_call_of_unknown_any;
10083 loc = msg->getSelectorLoc();
10084 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000010085 if (!d) {
10086 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
10087 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
10088 << orig->getSourceRange();
10089 return ExprError();
10090 }
John McCall2d2e8702011-04-11 07:02:50 +000010091 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000010092 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10093 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000010094 return ExprError();
10095 }
10096
10097 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000010098
10099 // Never recoverable.
10100 return ExprError();
10101}
10102
John McCall36e7fe32010-10-12 00:20:44 +000010103/// Check for operands with placeholder types and complain if found.
10104/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000010105ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +000010106 // Placeholder types are always *exactly* the appropriate builtin type.
10107 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +000010108
John McCall31996342011-04-07 08:22:57 +000010109 // Overloaded expressions.
10110 if (type == Context.OverloadTy)
10111 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010112 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +000010113 QualType(),
10114 diag::err_ovl_unresolvable);
10115
John McCall0009fcc2011-04-26 20:42:42 +000010116 // Bound member functions.
10117 if (type == Context.BoundMemberTy) {
10118 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
10119 << E->getSourceRange();
10120 return ExprError();
10121 }
10122
John McCall31996342011-04-07 08:22:57 +000010123 // Expressions of unknown type.
10124 if (type == Context.UnknownAnyTy)
10125 return diagnoseUnknownAnyExpr(*this, E);
10126
10127 assert(!type->isPlaceholderType());
10128 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +000010129}
Richard Trieu2c850c02011-04-21 21:44:26 +000010130
Richard Trieuba63ce62011-09-09 01:45:06 +000010131bool Sema::CheckCaseExpression(Expr *E) {
10132 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000010133 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000010134 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
10135 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000010136 return false;
10137}