blob: ec71a4e94d19edb005d3b7efc86887397333382a [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
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000059static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
60 NamedDecl *D, SourceLocation Loc,
61 const ObjCInterfaceDecl *UnknownObjCClass) {
62 // See if this declaration is unavailable or deprecated.
63 std::string Message;
64 AvailabilityResult Result = D->getAvailability(&Message);
65 switch (Result) {
66 case AR_Available:
67 case AR_NotYetIntroduced:
68 break;
69
70 case AR_Deprecated:
71 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
72 break;
73
74 case AR_Unavailable:
75 if (cast<Decl>(S.CurContext)->getAvailability() != AR_Unavailable) {
76 if (Message.empty()) {
77 if (!UnknownObjCClass)
78 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
79 else
80 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
81 << D->getDeclName();
82 }
83 else
84 S.Diag(Loc, diag::err_unavailable_message)
85 << D->getDeclName() << Message;
86 S.Diag(D->getLocation(), diag::note_unavailable_here)
87 << isa<FunctionDecl>(D) << false;
88 }
89 break;
90 }
91 return Result;
92}
93
Douglas Gregor171c45a2009-02-18 21:56:37 +000094/// \brief Determine whether the use of this declaration is valid, and
95/// emit any corresponding diagnostics.
96///
97/// This routine diagnoses various problems with referencing
98/// declarations that can occur when using a declaration. For example,
99/// it might warn if a deprecated or unavailable declaration is being
100/// used, or produce an error (and return true) if a C++0x deleted
101/// function is being used.
102///
103/// \returns true if there was an error (this declaration cannot be
104/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +0000105///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +0000106bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000107 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000108 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
109 // If there were any diagnostics suppressed by template argument deduction,
110 // emit them now.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000111 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000112 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
113 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000114 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000115 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
116 Diag(Suppressed[I].first, Suppressed[I].second);
117
118 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000119 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000120 // entry from the table, because we want to avoid ever emitting these
121 // diagnostics again.
122 Suppressed.clear();
123 }
124 }
125
Richard Smith30482bc2011-02-20 03:19:35 +0000126 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +0000127 if (ParsingInitForAutoVars.count(D)) {
128 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
129 << D->getDeclName();
130 return true;
Richard Smith30482bc2011-02-20 03:19:35 +0000131 }
132
Douglas Gregor171c45a2009-02-18 21:56:37 +0000133 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +0000134 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +0000135 if (FD->isDeleted()) {
136 Diag(Loc, diag::err_deleted_function_use);
John McCall31168b02011-06-15 23:02:42 +0000137 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
Douglas Gregor171c45a2009-02-18 21:56:37 +0000138 return true;
139 }
Douglas Gregorde681d42009-02-24 04:26:15 +0000140 }
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000141 AvailabilityResult Result =
142 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000143
Anders Carlsson73067a02010-10-22 23:37:08 +0000144 // Warn if this is used but marked unused.
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000145 if (D->hasAttr<UnusedAttr>())
Anders Carlsson73067a02010-10-22 23:37:08 +0000146 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
Fariborz Jahaniand7106122011-09-29 18:40:01 +0000147 // For available enumerator, it will become unavailable/deprecated
148 // if its enum declaration is as such.
149 if (Result == AR_Available)
150 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
151 const DeclContext *DC = ECD->getDeclContext();
152 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000153 DiagnoseAvailabilityOfDecl(*this,
154 const_cast< EnumDecl *>(TheEnumDecl),
155 Loc, UnknownObjCClass);
Fariborz Jahaniand7106122011-09-29 18:40:01 +0000156 }
Douglas Gregor171c45a2009-02-18 21:56:37 +0000157 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000158}
159
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000160/// \brief Retrieve the message suffix that should be added to a
161/// diagnostic complaining about the given function being deleted or
162/// unavailable.
163std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
164 // FIXME: C++0x implicitly-deleted special member functions could be
165 // detected here so that we could improve diagnostics to say, e.g.,
166 // "base class 'A' had a deleted copy constructor".
167 if (FD->isDeleted())
168 return std::string();
169
170 std::string Message;
171 if (FD->getAvailability(&Message))
172 return ": " + Message;
173
174 return std::string();
175}
176
John McCallb46f2872011-09-09 07:56:05 +0000177/// DiagnoseSentinelCalls - This routine checks whether a call or
178/// message-send is to a declaration with the sentinel attribute, and
179/// if so, it checks that the requirements of the sentinel are
180/// satisfied.
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000181void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCallb46f2872011-09-09 07:56:05 +0000182 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000183 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000184 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000185 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000186
John McCallb46f2872011-09-09 07:56:05 +0000187 // The number of formal parameters of the declaration.
188 unsigned numFormalParams;
Mike Stump11289f42009-09-09 15:08:12 +0000189
John McCallb46f2872011-09-09 07:56:05 +0000190 // The kind of declaration. This is also an index into a %select in
191 // the diagnostic.
192 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
193
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000194 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000195 numFormalParams = MD->param_size();
196 calleeType = CT_Method;
Mike Stump12b8ce12009-08-04 21:02:39 +0000197 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000198 numFormalParams = FD->param_size();
199 calleeType = CT_Function;
200 } else if (isa<VarDecl>(D)) {
201 QualType type = cast<ValueDecl>(D)->getType();
202 const FunctionType *fn = 0;
203 if (const PointerType *ptr = type->getAs<PointerType>()) {
204 fn = ptr->getPointeeType()->getAs<FunctionType>();
205 if (!fn) return;
206 calleeType = CT_Function;
207 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
208 fn = ptr->getPointeeType()->castAs<FunctionType>();
209 calleeType = CT_Block;
210 } else {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000211 return;
John McCallb46f2872011-09-09 07:56:05 +0000212 }
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000213
John McCallb46f2872011-09-09 07:56:05 +0000214 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
215 numFormalParams = proto->getNumArgs();
216 } else {
217 numFormalParams = 0;
218 }
219 } else {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000220 return;
221 }
John McCallb46f2872011-09-09 07:56:05 +0000222
223 // "nullPos" is the number of formal parameters at the end which
224 // effectively count as part of the variadic arguments. This is
225 // useful if you would prefer to not have *any* formal parameters,
226 // but the language forces you to have at least one.
227 unsigned nullPos = attr->getNullPos();
228 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
229 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
230
231 // The number of arguments which should follow the sentinel.
232 unsigned numArgsAfterSentinel = attr->getSentinel();
233
234 // If there aren't enough arguments for all the formal parameters,
235 // the sentinel, and the args after the sentinel, complain.
236 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000237 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCallb46f2872011-09-09 07:56:05 +0000238 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000239 return;
240 }
John McCallb46f2872011-09-09 07:56:05 +0000241
242 // Otherwise, find the sentinel expression.
243 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall7ddbcf42010-05-06 23:53:00 +0000244 if (!sentinelExpr) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000245 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000246
247 // nullptr_t is always treated as null.
248 if (sentinelExpr->getType()->isNullPtrType()) return;
249
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000250 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000251 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
252 Expr::NPC_ValueDependentIsNull))
253 return;
254
255 // Unfortunately, __null has type 'int'.
256 if (isa<GNUNullExpr>(sentinelExpr)) return;
257
John McCallb46f2872011-09-09 07:56:05 +0000258 // Pick a reasonable string to insert. Optimistically use 'nil' or
259 // 'NULL' if those are actually defined in the context. Only use
260 // 'nil' for ObjC methods, where it's much more likely that the
261 // variadic arguments form a list of object pointers.
262 SourceLocation MissingNilLoc
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000263 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
264 std::string NullValue;
John McCallb46f2872011-09-09 07:56:05 +0000265 if (calleeType == CT_Method &&
266 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000267 NullValue = "nil";
268 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
269 NullValue = "NULL";
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000270 else
John McCallb46f2872011-09-09 07:56:05 +0000271 NullValue = "(void*) 0";
Eli Friedman9ab36372011-09-27 23:46:37 +0000272
273 if (MissingNilLoc.isInvalid())
274 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
275 else
276 Diag(MissingNilLoc, diag::warn_missing_sentinel)
277 << calleeType
278 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCallb46f2872011-09-09 07:56:05 +0000279 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000280}
281
Richard Trieuba63ce62011-09-09 01:45:06 +0000282SourceRange Sema::getExprRange(Expr *E) const {
283 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor87f95b02009-02-26 21:00:50 +0000284}
285
Chris Lattner513165e2008-07-25 21:10:04 +0000286//===----------------------------------------------------------------------===//
287// Standard Promotions and Conversions
288//===----------------------------------------------------------------------===//
289
Chris Lattner513165e2008-07-25 21:10:04 +0000290/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000291ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattner513165e2008-07-25 21:10:04 +0000292 QualType Ty = E->getType();
293 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
294
Chris Lattner513165e2008-07-25 21:10:04 +0000295 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000296 E = ImpCastExprToType(E, Context.getPointerType(Ty),
297 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000298 else if (Ty->isArrayType()) {
299 // In C90 mode, arrays only promote to pointers if the array expression is
300 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
301 // type 'array of type' is converted to an expression that has type 'pointer
302 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
303 // that has type 'array of type' ...". The relevant change is "an lvalue"
304 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000305 //
306 // C++ 4.2p1:
307 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
308 // T" can be converted to an rvalue of type "pointer to T".
309 //
John McCall086a4642010-11-24 05:12:34 +0000310 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000311 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
312 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000313 }
John Wiegley01296292011-04-08 18:41:53 +0000314 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000315}
316
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000317static void CheckForNullPointerDereference(Sema &S, Expr *E) {
318 // Check to see if we are dereferencing a null pointer. If so,
319 // and if not volatile-qualified, this is undefined behavior that the
320 // optimizer will delete, so warn about it. People sometimes try to use this
321 // to get a deterministic trap and are surprised by clang's behavior. This
322 // only handles the pattern "*null", which is a very syntactic check.
323 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
324 if (UO->getOpcode() == UO_Deref &&
325 UO->getSubExpr()->IgnoreParenCasts()->
326 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
327 !UO->getType().isVolatileQualified()) {
328 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
329 S.PDiag(diag::warn_indirection_through_null)
330 << UO->getSubExpr()->getSourceRange());
331 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
332 S.PDiag(diag::note_indirection_through_null));
333 }
334}
335
John Wiegley01296292011-04-08 18:41:53 +0000336ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000337 // C++ [conv.lval]p1:
338 // A glvalue of a non-function, non-array type T can be
339 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000340 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000341
John McCall27584242010-12-06 20:48:59 +0000342 QualType T = E->getType();
343 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000344
Eli Friedman0dfb8892011-10-06 23:00:33 +0000345 // We can't do lvalue-to-rvalue on atomics yet.
346 if (T->getAs<AtomicType>())
347 return Owned(E);
348
John McCall27584242010-12-06 20:48:59 +0000349 // Create a load out of an ObjCProperty l-value, if necessary.
350 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +0000351 ExprResult Res = ConvertPropertyForRValue(E);
352 if (Res.isInvalid())
353 return Owned(E);
354 E = Res.take();
John McCall27584242010-12-06 20:48:59 +0000355 if (!E->isGLValue())
John Wiegley01296292011-04-08 18:41:53 +0000356 return Owned(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000357 }
John McCall27584242010-12-06 20:48:59 +0000358
359 // We don't want to throw lvalue-to-rvalue casts on top of
360 // expressions of certain types in C++.
361 if (getLangOptions().CPlusPlus &&
362 (E->getType() == Context.OverloadTy ||
363 T->isDependentType() ||
364 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000365 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000366
367 // The C standard is actually really unclear on this point, and
368 // DR106 tells us what the result should be but not why. It's
369 // generally best to say that void types just doesn't undergo
370 // lvalue-to-rvalue at all. Note that expressions of unqualified
371 // 'void' type are never l-values, but qualified void can be.
372 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000373 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000374
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000375 CheckForNullPointerDereference(*this, E);
376
John McCall27584242010-12-06 20:48:59 +0000377 // C++ [conv.lval]p1:
378 // [...] If T is a non-class type, the type of the prvalue is the
379 // cv-unqualified version of T. Otherwise, the type of the
380 // rvalue is T.
381 //
382 // C99 6.3.2.1p2:
383 // If the lvalue has qualified type, the value has the unqualified
384 // version of the type of the lvalue; otherwise, the value has the
385 // type of the lvalue.
386 if (T.hasQualifiers())
387 T = T.getUnqualifiedType();
Ted Kremenek64699be2011-02-16 01:57:07 +0000388
John Wiegley01296292011-04-08 18:41:53 +0000389 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
390 E, 0, VK_RValue));
John McCall27584242010-12-06 20:48:59 +0000391}
392
John Wiegley01296292011-04-08 18:41:53 +0000393ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
394 ExprResult Res = DefaultFunctionArrayConversion(E);
395 if (Res.isInvalid())
396 return ExprError();
397 Res = DefaultLvalueConversion(Res.take());
398 if (Res.isInvalid())
399 return ExprError();
400 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000401}
402
403
Chris Lattner513165e2008-07-25 21:10:04 +0000404/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000405/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000406/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000407/// apply if the array is an argument to the sizeof or address (&) operators.
408/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000409ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000410 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000411 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
412 if (Res.isInvalid())
413 return Owned(E);
414 E = Res.take();
John McCallf3735e02010-12-01 04:43:34 +0000415
416 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000417 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000418
419 // Try to perform integral promotions if the object has a theoretically
420 // promotable type.
421 if (Ty->isIntegralOrUnscopedEnumerationType()) {
422 // C99 6.3.1.1p2:
423 //
424 // The following may be used in an expression wherever an int or
425 // unsigned int may be used:
426 // - an object or expression with an integer type whose integer
427 // conversion rank is less than or equal to the rank of int
428 // and unsigned int.
429 // - A bit-field of type _Bool, int, signed int, or unsigned int.
430 //
431 // If an int can represent all values of the original type, the
432 // value is converted to an int; otherwise, it is converted to an
433 // unsigned int. These are called the integer promotions. All
434 // other types are unchanged by the integer promotions.
435
436 QualType PTy = Context.isPromotableBitField(E);
437 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000438 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
439 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000440 }
441 if (Ty->isPromotableIntegerType()) {
442 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000443 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
444 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000445 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000446 }
John Wiegley01296292011-04-08 18:41:53 +0000447 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000448}
449
Chris Lattner2ce500f2008-07-25 22:25:12 +0000450/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000451/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000452/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000453ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
454 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000455 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000456
John Wiegley01296292011-04-08 18:41:53 +0000457 ExprResult Res = UsualUnaryConversions(E);
458 if (Res.isInvalid())
459 return Owned(E);
460 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000461
Chris Lattner2ce500f2008-07-25 22:25:12 +0000462 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000463 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000464 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
465
John McCall4bb057d2011-08-27 22:06:17 +0000466 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall0562caa2011-08-29 23:55:37 +0000467 // promotion, even on class types, but note:
468 // C++11 [conv.lval]p2:
469 // When an lvalue-to-rvalue conversion occurs in an unevaluated
470 // operand or a subexpression thereof the value contained in the
471 // referenced object is not accessed. Otherwise, if the glvalue
472 // has a class type, the conversion copy-initializes a temporary
473 // of type T from the glvalue and the result of the conversion
474 // is a prvalue for the temporary.
475 // FIXME: add some way to gate this entire thing for correctness in
476 // potentially potentially evaluated contexts.
John McCall4bb057d2011-08-27 22:06:17 +0000477 if (getLangOptions().CPlusPlus && E->isGLValue() &&
478 ExprEvalContexts.back().Context != Unevaluated) {
John McCall29ad95b2011-08-27 01:09:30 +0000479 ExprResult Temp = PerformCopyInitialization(
480 InitializedEntity::InitializeTemporary(E->getType()),
481 E->getExprLoc(),
482 Owned(E));
483 if (Temp.isInvalid())
484 return ExprError();
485 E = Temp.get();
486 }
487
John Wiegley01296292011-04-08 18:41:53 +0000488 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000489}
490
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000491/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
492/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000493/// interfaces passed by value.
494ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000495 FunctionDecl *FDecl) {
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000496 ExprResult ExprRes = CheckPlaceholderExpr(E);
497 if (ExprRes.isInvalid())
498 return ExprError();
499
500 ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000501 if (ExprRes.isInvalid())
502 return ExprError();
503 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000504
Douglas Gregor347e0f22011-05-21 19:26:31 +0000505 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000506 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000507 DiagRuntimeBehavior(E->getLocStart(), 0,
508 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
509 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000510 return ExprError();
John McCall29ad95b2011-08-27 01:09:30 +0000511
John McCall31168b02011-06-15 23:02:42 +0000512 if (!E->getType().isPODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000513 // C++0x [expr.call]p7:
514 // Passing a potentially-evaluated argument of class type (Clause 9)
515 // having a non-trivial copy constructor, a non-trivial move constructor,
516 // or a non-trivial destructor, with no corresponding parameter,
517 // is conditionally-supported with implementation-defined semantics.
518 bool TrivialEnough = false;
519 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
520 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
521 if (Record->hasTrivialCopyConstructor() &&
522 Record->hasTrivialMoveConstructor() &&
523 Record->hasTrivialDestructor())
524 TrivialEnough = true;
525 }
526 }
John McCall31168b02011-06-15 23:02:42 +0000527
528 if (!TrivialEnough &&
529 getLangOptions().ObjCAutoRefCount &&
530 E->getType()->isObjCLifetimeType())
531 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000532
533 if (TrivialEnough) {
534 // Nothing to diagnose. This is okay.
535 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000536 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor253cadf2011-05-21 16:27:21 +0000537 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000538 << CT)) {
539 // Turn this into a trap.
540 CXXScopeSpec SS;
541 UnqualifiedId Name;
542 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
543 E->getLocStart());
544 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
545 if (TrapFn.isInvalid())
546 return ExprError();
547
548 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
549 MultiExprArg(), E->getLocEnd());
550 if (Call.isInvalid())
551 return ExprError();
552
553 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
554 Call.get(), E);
555 if (Comma.isInvalid())
John McCall1cd60a22011-08-26 18:41:18 +0000556 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000557 E = Comma.get();
558 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000559 }
560
John Wiegley01296292011-04-08 18:41:53 +0000561 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000562}
563
Richard Trieu7aa58f12011-09-02 20:58:51 +0000564/// \brief Converts an integer to complex float type. Helper function of
565/// UsualArithmeticConversions()
566///
567/// \return false if the integer expression is an integer type and is
568/// successfully converted to the complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000569static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
570 ExprResult &ComplexExpr,
571 QualType IntTy,
572 QualType ComplexTy,
573 bool SkipCast) {
574 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
575 if (SkipCast) return false;
576 if (IntTy->isIntegerType()) {
577 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
578 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
579 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000580 CK_FloatingRealToComplex);
581 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +0000582 assert(IntTy->isComplexIntegerType());
583 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000584 CK_IntegralComplexToFloatingComplex);
585 }
586 return false;
587}
588
589/// \brief Takes two complex float types and converts them to the same type.
590/// Helper function of UsualArithmeticConversions()
591static QualType
Richard Trieu5065cdd2011-09-06 18:25:09 +0000592handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
593 ExprResult &RHS, QualType LHSType,
594 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000595 bool IsCompAssign) {
Richard Trieu5065cdd2011-09-06 18:25:09 +0000596 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000597
598 if (order < 0) {
599 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000600 if (!IsCompAssign)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000601 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
602 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000603 }
604 if (order > 0)
605 // _Complex float -> _Complex double
Richard Trieu5065cdd2011-09-06 18:25:09 +0000606 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
607 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000608}
609
610/// \brief Converts otherExpr to complex float and promotes complexExpr if
611/// necessary. Helper function of UsualArithmeticConversions()
612static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuba63ce62011-09-09 01:45:06 +0000613 ExprResult &ComplexExpr,
614 ExprResult &OtherExpr,
615 QualType ComplexTy,
616 QualType OtherTy,
617 bool ConvertComplexExpr,
618 bool ConvertOtherExpr) {
619 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000620
621 // If just the complexExpr is complex, the otherExpr needs to be converted,
622 // and the complexExpr might need to be promoted.
623 if (order > 0) { // complexExpr is wider
624 // float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000625 if (ConvertOtherExpr) {
626 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
627 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
628 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000629 CK_FloatingRealToComplex);
630 }
Richard Trieuba63ce62011-09-09 01:45:06 +0000631 return ComplexTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000632 }
633
634 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000635 QualType result = (order == 0 ? ComplexTy :
636 S.Context.getComplexType(OtherTy));
Richard Trieu7aa58f12011-09-02 20:58:51 +0000637
638 // double -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000639 if (ConvertOtherExpr)
640 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000641 CK_FloatingRealToComplex);
642
643 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000644 if (ConvertComplexExpr && order < 0)
645 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000646 CK_FloatingComplexCast);
647
648 return result;
649}
650
651/// \brief Handle arithmetic conversion with complex types. Helper function of
652/// UsualArithmeticConversions()
Richard Trieu5065cdd2011-09-06 18:25:09 +0000653static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
654 ExprResult &RHS, QualType LHSType,
655 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000656 bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000657 // if we have an integer operand, the result is the complex type.
Richard Trieu5065cdd2011-09-06 18:25:09 +0000658 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000659 /*skipCast*/false))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000660 return LHSType;
661 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000662 /*skipCast*/IsCompAssign))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000663 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000664
665 // This handles complex/complex, complex/float, or float/complex.
666 // When both operands are complex, the shorter operand is converted to the
667 // type of the longer, and that is the type of the result. This corresponds
668 // to what is done when combining two real floating-point operands.
669 // The fun begins when size promotion occur across type domains.
670 // From H&S 6.3.4: When one operand is complex and the other is a real
671 // floating-point type, the less precise type is converted, within it's
672 // real or complex domain, to the precision of the other type. For example,
673 // when combining a "long double" with a "double _Complex", the
674 // "double _Complex" is promoted to "long double _Complex".
675
Richard Trieu5065cdd2011-09-06 18:25:09 +0000676 bool LHSComplexFloat = LHSType->isComplexType();
677 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000678
679 // If both are complex, just cast to the more precise type.
680 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000681 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
682 LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000683 IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000684
685 // If only one operand is complex, promote it if necessary and convert the
686 // other operand to complex.
687 if (LHSComplexFloat)
688 return handleOtherComplexFloatConversion(
Richard Trieuba63ce62011-09-09 01:45:06 +0000689 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000690 /*convertOtherExpr*/ true);
691
692 assert(RHSComplexFloat);
693 return handleOtherComplexFloatConversion(
Richard Trieu5065cdd2011-09-06 18:25:09 +0000694 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000695 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000696}
697
698/// \brief Hande arithmetic conversion from integer to float. Helper function
699/// of UsualArithmeticConversions()
Richard Trieuba63ce62011-09-09 01:45:06 +0000700static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
701 ExprResult &IntExpr,
702 QualType FloatTy, QualType IntTy,
703 bool ConvertFloat, bool ConvertInt) {
704 if (IntTy->isIntegerType()) {
705 if (ConvertInt)
Richard Trieu7aa58f12011-09-02 20:58:51 +0000706 // Convert intExpr to the lhs floating point type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000707 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000708 CK_IntegralToFloating);
Richard Trieuba63ce62011-09-09 01:45:06 +0000709 return FloatTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000710 }
711
712 // Convert both sides to the appropriate complex float.
Richard Trieuba63ce62011-09-09 01:45:06 +0000713 assert(IntTy->isComplexIntegerType());
714 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000715
716 // _Complex int -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000717 if (ConvertInt)
718 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000719 CK_IntegralComplexToFloatingComplex);
720
721 // float -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000722 if (ConvertFloat)
723 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000724 CK_FloatingRealToComplex);
725
726 return result;
727}
728
729/// \brief Handle arithmethic conversion with floating point types. Helper
730/// function of UsualArithmeticConversions()
Richard Trieucfe3f212011-09-06 18:38:41 +0000731static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
732 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000733 QualType RHSType, bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000734 bool LHSFloat = LHSType->isRealFloatingType();
735 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000736
737 // If we have two real floating types, convert the smaller operand
738 // to the bigger result.
739 if (LHSFloat && RHSFloat) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000740 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000741 if (order > 0) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000742 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
743 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000744 }
745
746 assert(order < 0 && "illegal float comparison");
Richard Trieuba63ce62011-09-09 01:45:06 +0000747 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000748 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
749 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000750 }
751
752 if (LHSFloat)
Richard Trieucfe3f212011-09-06 18:38:41 +0000753 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000754 /*convertFloat=*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000755 /*convertInt=*/ true);
756 assert(RHSFloat);
Richard Trieucfe3f212011-09-06 18:38:41 +0000757 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000758 /*convertInt=*/ true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000759 /*convertFloat=*/!IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000760}
761
762/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000763/// of UsualArithmeticConversions()
Richard Trieu7aa58f12011-09-02 20:58:51 +0000764// FIXME: if the operands are (int, _Complex long), we currently
765// don't promote the complex. Also, signedness?
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000766static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
767 ExprResult &RHS, QualType LHSType,
768 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000769 bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000770 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
771 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000772
Richard Trieucfe3f212011-09-06 18:38:41 +0000773 if (LHSComplexInt && RHSComplexInt) {
774 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
775 RHSComplexInt->getElementType());
Richard Trieu7aa58f12011-09-02 20:58:51 +0000776 assert(order && "inequal types with equal element ordering");
777 if (order > 0) {
778 // _Complex int -> _Complex long
Richard Trieucfe3f212011-09-06 18:38:41 +0000779 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
780 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000781 }
782
Richard Trieuba63ce62011-09-09 01:45:06 +0000783 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000784 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
785 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000786 }
787
Richard Trieucfe3f212011-09-06 18:38:41 +0000788 if (LHSComplexInt) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000789 // int -> _Complex int
Richard Trieucfe3f212011-09-06 18:38:41 +0000790 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
791 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000792 }
793
Richard Trieucfe3f212011-09-06 18:38:41 +0000794 assert(RHSComplexInt);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000795 // int -> _Complex int
Richard Trieuba63ce62011-09-09 01:45:06 +0000796 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000797 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
798 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000799}
800
801/// \brief Handle integer arithmetic conversions. Helper function of
802/// UsualArithmeticConversions()
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000803static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
804 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000805 QualType RHSType, bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000806 // The rules for this case are in C99 6.3.1.8
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000807 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
808 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
809 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
810 if (LHSSigned == RHSSigned) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000811 // Same signedness; use the higher-ranked type
812 if (order >= 0) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000813 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
814 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000815 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000816 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
817 return RHSType;
818 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000819 // The unsigned type has greater than or equal rank to the
820 // signed type, so use the unsigned type
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000821 if (RHSSigned) {
822 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
823 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000824 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000825 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
826 return RHSType;
827 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000828 // The two types are different widths; if we are here, that
829 // means the signed type is larger than the unsigned type, so
830 // use the signed type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000831 if (LHSSigned) {
832 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
833 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000834 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000835 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
836 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000837 } else {
838 // The signed type is higher-ranked than the unsigned type,
839 // but isn't actually any bigger (like unsigned int and long
840 // on most 32-bit systems). Use the unsigned type corresponding
841 // to the signed type.
842 QualType result =
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000843 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
844 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuba63ce62011-09-09 01:45:06 +0000845 if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000846 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000847 return result;
848 }
849}
850
Chris Lattner513165e2008-07-25 21:10:04 +0000851/// UsualArithmeticConversions - Performs various conversions that are common to
852/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000853/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000854/// responsible for emitting appropriate error diagnostics.
855/// FIXME: verify the conversion rules for "complex int" are consistent with
856/// GCC.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000857QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +0000858 bool IsCompAssign) {
859 if (!IsCompAssign) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000860 LHS = UsualUnaryConversions(LHS.take());
861 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000862 return QualType();
863 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000864
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000865 RHS = UsualUnaryConversions(RHS.take());
866 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000867 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000868
Mike Stump11289f42009-09-09 15:08:12 +0000869 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000870 // For example, "const float" and "float" are equivalent.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000871 QualType LHSType =
872 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
873 QualType RHSType =
874 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000875
876 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000877 if (LHSType == RHSType)
878 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000879
880 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
881 // The caller can deal with this (e.g. pointer + int).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000882 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
883 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000884
John McCalld005ac92010-11-13 08:17:45 +0000885 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000886 QualType LHSUnpromotedType = LHSType;
887 if (LHSType->isPromotableIntegerType())
888 LHSType = Context.getPromotedIntegerType(LHSType);
889 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000890 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000891 LHSType = LHSBitfieldPromoteTy;
Richard Trieuba63ce62011-09-09 01:45:06 +0000892 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000893 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000894
John McCalld005ac92010-11-13 08:17:45 +0000895 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000896 if (LHSType == RHSType)
897 return LHSType;
John McCalld005ac92010-11-13 08:17:45 +0000898
899 // At this point, we have two different arithmetic types.
900
901 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000902 if (LHSType->isComplexType() || RHSType->isComplexType())
903 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000904 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000905
906 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000907 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
908 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000909 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000910
911 // Handle GCC complex int extension.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000912 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000913 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000914 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000915
916 // Finally, we have two differing integer types.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000917 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000918 IsCompAssign);
Douglas Gregora11693b2008-11-12 17:17:38 +0000919}
920
Chris Lattner513165e2008-07-25 21:10:04 +0000921//===----------------------------------------------------------------------===//
922// Semantic Analysis for various Expression Types
923//===----------------------------------------------------------------------===//
924
925
Peter Collingbourne91147592011-04-15 00:35:48 +0000926ExprResult
927Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
928 SourceLocation DefaultLoc,
929 SourceLocation RParenLoc,
930 Expr *ControllingExpr,
Richard Trieuba63ce62011-09-09 01:45:06 +0000931 MultiTypeArg ArgTypes,
932 MultiExprArg ArgExprs) {
933 unsigned NumAssocs = ArgTypes.size();
934 assert(NumAssocs == ArgExprs.size());
Peter Collingbourne91147592011-04-15 00:35:48 +0000935
Richard Trieuba63ce62011-09-09 01:45:06 +0000936 ParsedType *ParsedTypes = ArgTypes.release();
937 Expr **Exprs = ArgExprs.release();
Peter Collingbourne91147592011-04-15 00:35:48 +0000938
939 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
940 for (unsigned i = 0; i < NumAssocs; ++i) {
941 if (ParsedTypes[i])
942 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
943 else
944 Types[i] = 0;
945 }
946
947 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
948 ControllingExpr, Types, Exprs,
949 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000950 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000951 return ER;
952}
953
954ExprResult
955Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
956 SourceLocation DefaultLoc,
957 SourceLocation RParenLoc,
958 Expr *ControllingExpr,
959 TypeSourceInfo **Types,
960 Expr **Exprs,
961 unsigned NumAssocs) {
962 bool TypeErrorFound = false,
963 IsResultDependent = ControllingExpr->isTypeDependent(),
964 ContainsUnexpandedParameterPack
965 = ControllingExpr->containsUnexpandedParameterPack();
966
967 for (unsigned i = 0; i < NumAssocs; ++i) {
968 if (Exprs[i]->containsUnexpandedParameterPack())
969 ContainsUnexpandedParameterPack = true;
970
971 if (Types[i]) {
972 if (Types[i]->getType()->containsUnexpandedParameterPack())
973 ContainsUnexpandedParameterPack = true;
974
975 if (Types[i]->getType()->isDependentType()) {
976 IsResultDependent = true;
977 } else {
978 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
979 // complete object type other than a variably modified type."
980 unsigned D = 0;
981 if (Types[i]->getType()->isIncompleteType())
982 D = diag::err_assoc_type_incomplete;
983 else if (!Types[i]->getType()->isObjectType())
984 D = diag::err_assoc_type_nonobject;
985 else if (Types[i]->getType()->isVariablyModifiedType())
986 D = diag::err_assoc_type_variably_modified;
987
988 if (D != 0) {
989 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
990 << Types[i]->getTypeLoc().getSourceRange()
991 << Types[i]->getType();
992 TypeErrorFound = true;
993 }
994
995 // C1X 6.5.1.1p2 "No two generic associations in the same generic
996 // selection shall specify compatible types."
997 for (unsigned j = i+1; j < NumAssocs; ++j)
998 if (Types[j] && !Types[j]->getType()->isDependentType() &&
999 Context.typesAreCompatible(Types[i]->getType(),
1000 Types[j]->getType())) {
1001 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1002 diag::err_assoc_compatible_types)
1003 << Types[j]->getTypeLoc().getSourceRange()
1004 << Types[j]->getType()
1005 << Types[i]->getType();
1006 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1007 diag::note_compat_assoc)
1008 << Types[i]->getTypeLoc().getSourceRange()
1009 << Types[i]->getType();
1010 TypeErrorFound = true;
1011 }
1012 }
1013 }
1014 }
1015 if (TypeErrorFound)
1016 return ExprError();
1017
1018 // If we determined that the generic selection is result-dependent, don't
1019 // try to compute the result expression.
1020 if (IsResultDependent)
1021 return Owned(new (Context) GenericSelectionExpr(
1022 Context, KeyLoc, ControllingExpr,
1023 Types, Exprs, NumAssocs, DefaultLoc,
1024 RParenLoc, ContainsUnexpandedParameterPack));
1025
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001026 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +00001027 unsigned DefaultIndex = -1U;
1028 for (unsigned i = 0; i < NumAssocs; ++i) {
1029 if (!Types[i])
1030 DefaultIndex = i;
1031 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1032 Types[i]->getType()))
1033 CompatIndices.push_back(i);
1034 }
1035
1036 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
1037 // type compatible with at most one of the types named in its generic
1038 // association list."
1039 if (CompatIndices.size() > 1) {
1040 // We strip parens here because the controlling expression is typically
1041 // parenthesized in macro definitions.
1042 ControllingExpr = ControllingExpr->IgnoreParens();
1043 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1044 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1045 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001046 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +00001047 E = CompatIndices.end(); I != E; ++I) {
1048 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1049 diag::note_compat_assoc)
1050 << Types[*I]->getTypeLoc().getSourceRange()
1051 << Types[*I]->getType();
1052 }
1053 return ExprError();
1054 }
1055
1056 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
1057 // its controlling expression shall have type compatible with exactly one of
1058 // the types named in its generic association list."
1059 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1060 // We strip parens here because the controlling expression is typically
1061 // parenthesized in macro definitions.
1062 ControllingExpr = ControllingExpr->IgnoreParens();
1063 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1064 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1065 return ExprError();
1066 }
1067
1068 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
1069 // type name that is compatible with the type of the controlling expression,
1070 // then the result expression of the generic selection is the expression
1071 // in that generic association. Otherwise, the result expression of the
1072 // generic selection is the expression in the default generic association."
1073 unsigned ResultIndex =
1074 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1075
1076 return Owned(new (Context) GenericSelectionExpr(
1077 Context, KeyLoc, ControllingExpr,
1078 Types, Exprs, NumAssocs, DefaultLoc,
1079 RParenLoc, ContainsUnexpandedParameterPack,
1080 ResultIndex));
1081}
1082
Steve Naroff83895f72007-09-16 03:34:24 +00001083/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001084/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1085/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1086/// multiple tokens. However, the common case is that StringToks points to one
1087/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001088///
John McCalldadc5752010-08-24 06:29:42 +00001089ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +00001090Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001091 assert(NumStringToks && "Must have at least one string!");
1092
Chris Lattner8a24e582009-01-16 18:51:42 +00001093 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001094 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001095 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001096
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001097 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001098 for (unsigned i = 0; i != NumStringToks; ++i)
1099 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001100
Chris Lattner36fc8792008-02-11 00:02:17 +00001101 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001102 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001103 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001104 else if (Literal.isUTF16())
1105 StrTy = Context.Char16Ty;
1106 else if (Literal.isUTF32())
1107 StrTy = Context.Char32Ty;
Anders Carlsson6b06e182011-04-06 18:42:48 +00001108 else if (Literal.Pascal)
1109 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001110
Douglas Gregorfb65e592011-07-27 05:40:30 +00001111 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1112 if (Literal.isWide())
1113 Kind = StringLiteral::Wide;
1114 else if (Literal.isUTF8())
1115 Kind = StringLiteral::UTF8;
1116 else if (Literal.isUTF16())
1117 Kind = StringLiteral::UTF16;
1118 else if (Literal.isUTF32())
1119 Kind = StringLiteral::UTF32;
1120
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001121 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +00001122 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001123 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001124
Chris Lattner36fc8792008-02-11 00:02:17 +00001125 // Get an array type for the string, according to C99 6.4.5. This includes
1126 // the nul terminator character as well as the string length for pascal
1127 // strings.
1128 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001129 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001130 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001131
Chris Lattner5b183d82006-11-10 05:03:26 +00001132 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +00001133 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001134 Kind, Literal.Pascal, StrTy,
Alexis Hunt3b791862010-08-30 17:47:05 +00001135 &StringTokLocs[0],
1136 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +00001137}
1138
John McCallc63de662011-02-02 13:00:07 +00001139enum CaptureResult {
1140 /// No capture is required.
1141 CR_NoCapture,
1142
1143 /// A capture is required.
1144 CR_Capture,
1145
John McCall351762c2011-02-07 10:33:21 +00001146 /// A by-ref capture is required.
1147 CR_CaptureByRef,
1148
John McCallc63de662011-02-02 13:00:07 +00001149 /// An error occurred when trying to capture the given variable.
1150 CR_Error
1151};
1152
1153/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +00001154///
John McCallc63de662011-02-02 13:00:07 +00001155/// \param var - the variable referenced
1156/// \param DC - the context which we couldn't capture through
1157static CaptureResult
John McCall351762c2011-02-07 10:33:21 +00001158diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001159 VarDecl *var, DeclContext *DC) {
1160 switch (S.ExprEvalContexts.back().Context) {
1161 case Sema::Unevaluated:
1162 // The argument will never be evaluated, so don't complain.
1163 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +00001164
John McCallc63de662011-02-02 13:00:07 +00001165 case Sema::PotentiallyEvaluated:
1166 case Sema::PotentiallyEvaluatedIfUsed:
1167 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +00001168
John McCallc63de662011-02-02 13:00:07 +00001169 case Sema::PotentiallyPotentiallyEvaluated:
1170 // FIXME: delay these!
1171 break;
Chris Lattner497d7b02009-04-21 22:26:47 +00001172 }
Mike Stump11289f42009-09-09 15:08:12 +00001173
John McCallc63de662011-02-02 13:00:07 +00001174 // Don't diagnose about capture if we're not actually in code right
1175 // now; in general, there are more appropriate places that will
1176 // diagnose this.
1177 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1178
John McCall92d627e2011-03-22 23:15:50 +00001179 // Certain madnesses can happen with parameter declarations, which
1180 // we want to ignore.
1181 if (isa<ParmVarDecl>(var)) {
1182 // - If the parameter still belongs to the translation unit, then
1183 // we're actually just using one parameter in the declaration of
1184 // the next. This is useful in e.g. VLAs.
1185 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1186 return CR_NoCapture;
1187
1188 // - This particular madness can happen in ill-formed default
1189 // arguments; claim it's okay and let downstream code handle it.
1190 if (S.CurContext == var->getDeclContext()->getParent())
1191 return CR_NoCapture;
1192 }
John McCallc63de662011-02-02 13:00:07 +00001193
1194 DeclarationName functionName;
1195 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1196 functionName = fn->getDeclName();
1197 // FIXME: variable from enclosing block that we couldn't capture from!
1198
1199 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1200 << var->getIdentifier() << functionName;
1201 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1202 << var->getIdentifier();
1203
1204 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +00001205}
1206
John McCall351762c2011-02-07 10:33:21 +00001207/// There is a well-formed capture at a particular scope level;
1208/// propagate it through all the nested blocks.
Richard Trieuba63ce62011-09-09 01:45:06 +00001209static CaptureResult propagateCapture(Sema &S, unsigned ValidScopeIndex,
1210 const BlockDecl::Capture &Capture) {
1211 VarDecl *var = Capture.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001212
1213 // Update all the inner blocks with the capture information.
Richard Trieuba63ce62011-09-09 01:45:06 +00001214 for (unsigned i = ValidScopeIndex + 1, e = S.FunctionScopes.size();
John McCall351762c2011-02-07 10:33:21 +00001215 i != e; ++i) {
1216 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1217 innerBlock->Captures.push_back(
Richard Trieuba63ce62011-09-09 01:45:06 +00001218 BlockDecl::Capture(Capture.getVariable(), Capture.isByRef(),
1219 /*nested*/ true, Capture.getCopyExpr()));
John McCall351762c2011-02-07 10:33:21 +00001220 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1221 }
1222
Richard Trieuba63ce62011-09-09 01:45:06 +00001223 return Capture.isByRef() ? CR_CaptureByRef : CR_Capture;
John McCall351762c2011-02-07 10:33:21 +00001224}
1225
1226/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +00001227/// given value in the current context requires a variable capture.
1228///
1229/// This also keeps the captures set in the BlockScopeInfo records
1230/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +00001231static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00001232 ValueDecl *Value) {
John McCallc63de662011-02-02 13:00:07 +00001233 // Only variables ever require capture.
Richard Trieuba63ce62011-09-09 01:45:06 +00001234 VarDecl *var = dyn_cast<VarDecl>(Value);
John McCallf4cd4f92011-02-09 01:13:10 +00001235 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +00001236
1237 // Fast path: variables from the current context never require capture.
1238 DeclContext *DC = S.CurContext;
1239 if (var->getDeclContext() == DC) return CR_NoCapture;
1240
1241 // Only variables with local storage require capture.
1242 // FIXME: What about 'const' variables in C++?
1243 if (!var->hasLocalStorage()) return CR_NoCapture;
1244
1245 // Otherwise, we need to capture.
1246
1247 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +00001248 do {
1249 // Only blocks (and eventually C++0x closures) can capture; other
1250 // scopes don't work.
1251 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +00001252 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +00001253
1254 BlockScopeInfo *blockScope =
1255 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1256 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1257
John McCall351762c2011-02-07 10:33:21 +00001258 // Check whether we've already captured it in this block. If so,
1259 // we're done.
1260 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1261 return propagateCapture(S, functionScopesIndex,
1262 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +00001263
1264 functionScopesIndex--;
1265 DC = cast<BlockDecl>(DC)->getDeclContext();
1266 } while (var->getDeclContext() != DC);
1267
John McCall351762c2011-02-07 10:33:21 +00001268 // Okay, we descended all the way to the block that defines the variable.
1269 // Actually try to capture it.
1270 QualType type = var->getType();
1271
1272 // Prohibit variably-modified types.
1273 if (type->isVariablyModifiedType()) {
1274 S.Diag(loc, diag::err_ref_vm_type);
1275 S.Diag(var->getLocation(), diag::note_declared_at);
1276 return CR_Error;
1277 }
1278
1279 // Prohibit arrays, even in __block variables, but not references to
1280 // them.
1281 if (type->isArrayType()) {
1282 S.Diag(loc, diag::err_ref_array_type);
1283 S.Diag(var->getLocation(), diag::note_declared_at);
1284 return CR_Error;
1285 }
1286
1287 S.MarkDeclarationReferenced(loc, var);
1288
1289 // The BlocksAttr indicates the variable is bound by-reference.
1290 bool byRef = var->hasAttr<BlocksAttr>();
1291
1292 // Build a copy expression.
1293 Expr *copyExpr = 0;
John McCalla85af562011-04-28 02:15:35 +00001294 const RecordType *rtype;
1295 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1296 (rtype = type->getAs<RecordType>())) {
1297
1298 // The capture logic needs the destructor, so make sure we mark it.
1299 // Usually this is unnecessary because most local variables have
1300 // their destructors marked at declaration time, but parameters are
1301 // an exception because it's technically only the call site that
1302 // actually requires the destructor.
1303 if (isa<ParmVarDecl>(var))
1304 S.FinalizeVarWithDestructor(var, rtype);
1305
John McCall351762c2011-02-07 10:33:21 +00001306 // According to the blocks spec, the capture of a variable from
1307 // the stack requires a const copy constructor. This is not true
1308 // of the copy/move done to move a __block variable to the heap.
1309 type.addConst();
1310
1311 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1312 ExprResult result =
1313 S.PerformCopyInitialization(
1314 InitializedEntity::InitializeBlock(var->getLocation(),
1315 type, false),
1316 loc, S.Owned(declRef));
1317
1318 // Build a full-expression copy expression if initialization
1319 // succeeded and used a non-trivial constructor. Recover from
1320 // errors by pretending that the copy isn't necessary.
1321 if (!result.isInvalid() &&
1322 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1323 result = S.MaybeCreateExprWithCleanups(result);
1324 copyExpr = result.take();
1325 }
1326 }
1327
1328 // We're currently at the declarer; go back to the closure.
1329 functionScopesIndex++;
1330 BlockScopeInfo *blockScope =
1331 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1332
1333 // Build a valid capture in this scope.
1334 blockScope->Captures.push_back(
1335 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1336 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1337
1338 // Propagate that to inner captures if necessary.
1339 return propagateCapture(S, functionScopesIndex,
1340 blockScope->Captures.back());
1341}
1342
Richard Trieuba63ce62011-09-09 01:45:06 +00001343static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *VD,
John McCall351762c2011-02-07 10:33:21 +00001344 const DeclarationNameInfo &NameInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00001345 bool ByRef) {
1346 assert(isa<VarDecl>(VD) && "capturing non-variable");
John McCall351762c2011-02-07 10:33:21 +00001347
Richard Trieuba63ce62011-09-09 01:45:06 +00001348 VarDecl *var = cast<VarDecl>(VD);
John McCall351762c2011-02-07 10:33:21 +00001349 assert(var->hasLocalStorage() && "capturing non-local");
Richard Trieuba63ce62011-09-09 01:45:06 +00001350 assert(ByRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
John McCall351762c2011-02-07 10:33:21 +00001351
1352 QualType exprType = var->getType().getNonReferenceType();
1353
1354 BlockDeclRefExpr *BDRE;
Richard Trieuba63ce62011-09-09 01:45:06 +00001355 if (!ByRef) {
John McCall351762c2011-02-07 10:33:21 +00001356 // The variable will be bound by copy; make it const within the
1357 // closure, but record that this was done in the expression.
1358 bool constAdded = !exprType.isConstQualified();
1359 exprType.addConst();
1360
1361 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1362 NameInfo.getLoc(), false,
1363 constAdded);
1364 } else {
1365 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1366 NameInfo.getLoc(), true);
1367 }
1368
1369 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001370}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001371
John McCalldadc5752010-08-24 06:29:42 +00001372ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001373Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001374 SourceLocation Loc,
1375 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001376 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001377 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001378}
1379
John McCallf4cd4f92011-02-09 01:13:10 +00001380/// BuildDeclRefExpr - Build an expression that references a
1381/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001382ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001383Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001384 const DeclarationNameInfo &NameInfo,
1385 const CXXScopeSpec *SS) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00001386 if (getLangOptions().CUDA)
1387 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1388 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1389 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1390 CalleeTarget = IdentifyCUDATarget(Callee);
1391 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1392 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1393 << CalleeTarget << D->getIdentifier() << CallerTarget;
1394 Diag(D->getLocation(), diag::note_previous_decl)
1395 << D->getIdentifier();
1396 return ExprError();
1397 }
1398 }
1399
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001400 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001401
John McCall086a4642010-11-24 05:12:34 +00001402 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001403 SS? SS->getWithLocInContext(Context)
1404 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001405 D, NameInfo, Ty, VK);
1406
1407 // Just in case we're building an illegal pointer-to-member.
1408 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1409 E->setObjectKind(OK_BitField);
1410
1411 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001412}
1413
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001414/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001415/// possibly a list of template arguments.
1416///
1417/// If this produces template arguments, it is permitted to call
1418/// DecomposeTemplateName.
1419///
1420/// This actually loses a lot of source location information for
1421/// non-standard name kinds; we should consider preserving that in
1422/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001423void
1424Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1425 TemplateArgumentListInfo &Buffer,
1426 DeclarationNameInfo &NameInfo,
1427 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001428 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1429 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1430 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1431
Douglas Gregor5476205b2011-06-23 00:49:38 +00001432 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001433 Id.TemplateId->getTemplateArgs(),
1434 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001435 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001436 TemplateArgsPtr.release();
1437
John McCall3e56fd42010-08-23 07:28:44 +00001438 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001439 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001440 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001441 TemplateArgs = &Buffer;
1442 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001443 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001444 TemplateArgs = 0;
1445 }
1446}
1447
John McCalld681c392009-12-16 08:11:27 +00001448/// Diagnose an empty lookup.
1449///
1450/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001451bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001452 CorrectTypoContext CTC,
1453 TemplateArgumentListInfo *ExplicitTemplateArgs,
1454 Expr **Args, unsigned NumArgs) {
John McCalld681c392009-12-16 08:11:27 +00001455 DeclarationName Name = R.getLookupName();
1456
John McCalld681c392009-12-16 08:11:27 +00001457 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001458 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001459 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1460 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001461 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001462 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001463 diagnostic_suggest = diag::err_undeclared_use_suggest;
1464 }
John McCalld681c392009-12-16 08:11:27 +00001465
Douglas Gregor598b08f2009-12-31 05:20:13 +00001466 // If the original lookup was an unqualified lookup, fake an
1467 // unqualified lookup. This is useful when (for example) the
1468 // original lookup would not have found something because it was a
1469 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001470 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001471 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001472 if (isa<CXXRecordDecl>(DC)) {
1473 LookupQualifiedName(R, DC);
1474
1475 if (!R.empty()) {
1476 // Don't give errors about ambiguities in this lookup.
1477 R.suppressDiagnostics();
1478
1479 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1480 bool isInstance = CurMethod &&
1481 CurMethod->isInstance() &&
1482 DC == CurMethod->getParent();
1483
1484 // Give a code modification hint to insert 'this->'.
1485 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1486 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001487 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001488 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1489 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001490 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001491 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001492 if (DepMethod) {
Francois Pichet0706d202011-09-17 17:15:52 +00001493 if (getLangOptions().MicrosoftExt)
Francois Pichetbcf64712011-09-07 00:14:57 +00001494 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyfe712382010-08-20 20:54:15 +00001495 Diag(R.getNameLoc(), diagnostic) << Name
1496 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1497 QualType DepThisType = DepMethod->getThisType(Context);
1498 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1499 R.getNameLoc(), DepThisType, false);
1500 TemplateArgumentListInfo TList;
1501 if (ULE->hasExplicitTemplateArgs())
1502 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001503
Douglas Gregore16af532011-02-28 18:50:33 +00001504 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001505 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001506 CXXDependentScopeMemberExpr *DepExpr =
1507 CXXDependentScopeMemberExpr::Create(
1508 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001509 SS.getWithLocInContext(Context), NULL,
Francois Pichet4391c752011-09-04 23:00:48 +00001510 R.getLookupNameInfo(),
1511 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyfe712382010-08-20 20:54:15 +00001512 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001513 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001514 // FIXME: we should be able to handle this case too. It is correct
1515 // to add this-> here. This is a workaround for PR7947.
1516 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001517 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001518 } else {
John McCalld681c392009-12-16 08:11:27 +00001519 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001520 }
John McCalld681c392009-12-16 08:11:27 +00001521
1522 // Do we really want to note all of these?
1523 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1524 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1525
1526 // Tell the callee to try to recover.
1527 return false;
1528 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001529
1530 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001531 }
1532 }
1533
Douglas Gregor598b08f2009-12-31 05:20:13 +00001534 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001535 TypoCorrection Corrected;
1536 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1537 S, &SS, NULL, false, CTC))) {
1538 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1539 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1540 R.setLookupName(Corrected.getCorrection());
1541
Hans Wennborg38198de2011-07-12 08:45:31 +00001542 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001543 if (Corrected.isOverloaded()) {
1544 OverloadCandidateSet OCS(R.getNameLoc());
1545 OverloadCandidateSet::iterator Best;
1546 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1547 CDEnd = Corrected.end();
1548 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001549 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001550 dyn_cast<FunctionTemplateDecl>(*CD))
1551 AddTemplateOverloadCandidate(
1552 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1553 Args, NumArgs, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001554 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1555 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1556 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1557 Args, NumArgs, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001558 }
1559 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1560 case OR_Success:
1561 ND = Best->Function;
1562 break;
1563 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001564 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001565 }
1566 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001567 R.addDecl(ND);
1568 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001569 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001570 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1571 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001572 else
1573 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 Gregorc2fa1692011-06-28 16:20:02 +00001576 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1577 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001578 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001579 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001580
1581 // Tell the callee to try to recover.
1582 return false;
1583 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001584
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001585 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001586 // FIXME: If we ended up with a typo for a type name or
1587 // Objective-C class name, we're in trouble because the parser
1588 // is in the wrong place to recover. Suggest the typo
1589 // correction, but don't make it a fix-it since we're not going
1590 // to recover well anyway.
1591 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001592 Diag(R.getNameLoc(), diagnostic_suggest)
1593 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001594 else
1595 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001596 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001597 << SS.getRange();
1598
1599 // Don't try to recover; it won't work.
1600 return true;
1601 }
1602 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001603 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001604 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001605 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001606 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001607 else
Douglas Gregor25363982010-01-01 00:15:04 +00001608 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001609 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001610 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001611 return true;
1612 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001613 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001614 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001615
1616 // Emit a special diagnostic for failed member lookups.
1617 // FIXME: computing the declaration context might fail here (?)
1618 if (!SS.isEmpty()) {
1619 Diag(R.getNameLoc(), diag::err_no_member)
1620 << Name << computeDeclContext(SS, false)
1621 << SS.getRange();
1622 return true;
1623 }
1624
John McCalld681c392009-12-16 08:11:27 +00001625 // Give up, we can't recover.
1626 Diag(R.getNameLoc(), diagnostic) << Name;
1627 return true;
1628}
1629
John McCalldadc5752010-08-24 06:29:42 +00001630ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001631 CXXScopeSpec &SS,
1632 UnqualifiedId &Id,
1633 bool HasTrailingLParen,
Richard Trieuba63ce62011-09-09 01:45:06 +00001634 bool IsAddressOfOperand) {
1635 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00001636 "cannot be direct & operand and have a trailing lparen");
1637
1638 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001639 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001640
John McCall10eae182009-11-30 22:42:35 +00001641 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001642
1643 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001644 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001645 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001646 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001647
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001648 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001649 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001650 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001651
John McCalle66edc12009-11-24 19:00:30 +00001652 // C++ [temp.dep.expr]p3:
1653 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001654 // -- an identifier that was declared with a dependent type,
1655 // (note: handled after lookup)
1656 // -- a template-id that is dependent,
1657 // (note: handled in BuildTemplateIdExpr)
1658 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001659 // -- a nested-name-specifier that contains a class-name that
1660 // names a dependent type.
1661 // Determine whether this is a member of an unknown specialization;
1662 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001663 bool DependentID = false;
1664 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1665 Name.getCXXNameType()->isDependentType()) {
1666 DependentID = true;
1667 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001668 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001669 if (RequireCompleteDeclContext(SS, DC))
1670 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001671 } else {
1672 DependentID = true;
1673 }
1674 }
1675
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001676 if (DependentID)
Richard Trieuba63ce62011-09-09 01:45:06 +00001677 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001678 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001679
Fariborz Jahanian86151342010-07-22 23:33:21 +00001680 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001681 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001682 LookupResult R(*this, NameInfo,
1683 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1684 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001685 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001686 // Lookup the template name again to correctly establish the context in
1687 // which it was found. This is really unfortunate as we already did the
1688 // lookup to determine that it was a template name in the first place. If
1689 // this becomes a performance hit, we can work harder to preserve those
1690 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001691 bool MemberOfUnknownSpecialization;
1692 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1693 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001694
1695 if (MemberOfUnknownSpecialization ||
1696 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Richard Trieuba63ce62011-09-09 01:45:06 +00001697 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregora5226932011-02-04 13:35:07 +00001698 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001699 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001700 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001701 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001702
Douglas Gregora5226932011-02-04 13:35:07 +00001703 // If the result might be in a dependent base class, this is a dependent
1704 // id-expression.
1705 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Richard Trieuba63ce62011-09-09 01:45:06 +00001706 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregora5226932011-02-04 13:35:07 +00001707 TemplateArgs);
1708
John McCalle66edc12009-11-24 19:00:30 +00001709 // If this reference is in an Objective-C method, then we need to do
1710 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001711 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001712 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001713 if (E.isInvalid())
1714 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001715
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001716 if (Expr *Ex = E.takeAs<Expr>())
1717 return Owned(Ex);
1718
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001719 // for further use, this must be set to false if in class method.
1720 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001721 }
Chris Lattner59a25942008-03-31 00:36:02 +00001722 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001723
John McCalle66edc12009-11-24 19:00:30 +00001724 if (R.isAmbiguous())
1725 return ExprError();
1726
Douglas Gregor171c45a2009-02-18 21:56:37 +00001727 // Determine whether this name might be a candidate for
1728 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001729 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001730
John McCalle66edc12009-11-24 19:00:30 +00001731 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001732 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001733 // in C90, extension in C99, forbidden in C++).
1734 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1735 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1736 if (D) R.addDecl(D);
1737 }
1738
1739 // If this name wasn't predeclared and if this is not a function
1740 // call, diagnose the problem.
1741 if (R.empty()) {
Francois Pichetd8e4e412011-09-24 10:38:05 +00001742
1743 // In Microsoft mode, if we are inside a template class member function
1744 // and we can't resolve an identifier then assume the identifier is type
1745 // dependent. The goal is to postpone name lookup to instantiation time
1746 // to be able to search into type dependent base classes.
1747 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
1748 isa<CXXMethodDecl>(CurContext))
1749 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
1750 TemplateArgs);
1751
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001752 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001753 return ExprError();
1754
1755 assert(!R.empty() &&
1756 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001757
1758 // If we found an Objective-C instance variable, let
1759 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001760 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001761 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1762 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001763 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanian44653702011-09-23 23:11:38 +00001764 // In a hopelessly buggy code, Objective-C instance variable
1765 // lookup fails and no expression will be built to reference it.
1766 if (!E.isInvalid() && !E.get())
1767 return ExprError();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001768 return move(E);
1769 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001770 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001771 }
Mike Stump11289f42009-09-09 15:08:12 +00001772
John McCalle66edc12009-11-24 19:00:30 +00001773 // This is guaranteed from this point on.
1774 assert(!R.empty() || ADL);
1775
John McCall2d74de92009-12-01 22:10:20 +00001776 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001777 // C++ [class.mfct.non-static]p3:
1778 // When an id-expression that is not part of a class member access
1779 // syntax and not used to form a pointer to member is used in the
1780 // body of a non-static member function of class X, if name lookup
1781 // resolves the name in the id-expression to a non-static non-type
1782 // member of some class C, the id-expression is transformed into a
1783 // class member access expression using (*this) as the
1784 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001785 //
1786 // But we don't actually need to do this for '&' operands if R
1787 // resolved to a function or overloaded function set, because the
1788 // expression is ill-formed if it actually works out to be a
1789 // non-static member function:
1790 //
1791 // C++ [expr.ref]p4:
1792 // Otherwise, if E1.E2 refers to a non-static member function. . .
1793 // [t]he expression can be used only as the left-hand operand of a
1794 // member function call.
1795 //
1796 // There are other safeguards against such uses, but it's important
1797 // to get this right here so that we don't end up making a
1798 // spuriously dependent expression if we're inside a dependent
1799 // instance method.
John McCall57500772009-12-16 12:17:52 +00001800 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001801 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00001802 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00001803 MightBeImplicitMember = true;
1804 else if (!SS.isEmpty())
1805 MightBeImplicitMember = false;
1806 else if (R.isOverloadedResult())
1807 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001808 else if (R.isUnresolvableResult())
1809 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001810 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001811 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1812 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001813
1814 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001815 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001816 }
1817
John McCalle66edc12009-11-24 19:00:30 +00001818 if (TemplateArgs)
1819 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001820
John McCalle66edc12009-11-24 19:00:30 +00001821 return BuildDeclarationNameExpr(SS, R, ADL);
1822}
1823
John McCall10eae182009-11-30 22:42:35 +00001824/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1825/// declaration name, generally during template instantiation.
1826/// There's a large number of things which don't need to be done along
1827/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001828ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001829Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001830 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001831 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001832 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001833 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001834
John McCall0b66eb32010-05-01 00:40:08 +00001835 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001836 return ExprError();
1837
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001838 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001839 LookupQualifiedName(R, DC);
1840
1841 if (R.isAmbiguous())
1842 return ExprError();
1843
1844 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001845 Diag(NameInfo.getLoc(), diag::err_no_member)
1846 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001847 return ExprError();
1848 }
1849
1850 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1851}
1852
1853/// LookupInObjCMethod - The parser has read a name in, and Sema has
1854/// detected that we're currently inside an ObjC method. Perform some
1855/// additional lookup.
1856///
1857/// Ideally, most of this would be done by lookup, but there's
1858/// actually quite a lot of extra work involved.
1859///
1860/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001861ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001862Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001863 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001864 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001865 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001866
John McCalle66edc12009-11-24 19:00:30 +00001867 // There are two cases to handle here. 1) scoped lookup could have failed,
1868 // in which case we should look for an ivar. 2) scoped lookup could have
1869 // found a decl, but that decl is outside the current instance method (i.e.
1870 // a global variable). In these two cases, we do a lookup for an ivar with
1871 // this name, if the lookup sucedes, we replace it our current decl.
1872
1873 // If we're in a class method, we don't normally want to look for
1874 // ivars. But if we don't find anything else, and there's an
1875 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001876 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001877
1878 bool LookForIvars;
1879 if (Lookup.empty())
1880 LookForIvars = true;
1881 else if (IsClassMethod)
1882 LookForIvars = false;
1883 else
1884 LookForIvars = (Lookup.isSingleResult() &&
1885 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001886 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001887 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001888 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001889 ObjCInterfaceDecl *ClassDeclared;
1890 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1891 // Diagnose using an ivar in a class method.
1892 if (IsClassMethod)
1893 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1894 << IV->getDeclName());
1895
1896 // If we're referencing an invalid decl, just return this as a silent
1897 // error node. The error diagnostic was already emitted on the decl.
1898 if (IV->isInvalidDecl())
1899 return ExprError();
1900
1901 // Check if referencing a field with __attribute__((deprecated)).
1902 if (DiagnoseUseOfDecl(IV, Loc))
1903 return ExprError();
1904
1905 // Diagnose the use of an ivar outside of the declaring class.
1906 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1907 ClassDeclared != IFace)
1908 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1909
1910 // FIXME: This should use a new expr for a direct reference, don't
1911 // turn this into Self->ivar, just return a BareIVarExpr or something.
1912 IdentifierInfo &II = Context.Idents.get("self");
1913 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001914 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001915 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001916 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001917 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001918 SelfName, false, false);
1919 if (SelfExpr.isInvalid())
1920 return ExprError();
1921
John Wiegley01296292011-04-08 18:41:53 +00001922 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1923 if (SelfExpr.isInvalid())
1924 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001925
John McCalle66edc12009-11-24 19:00:30 +00001926 MarkDeclarationReferenced(Loc, IV);
1927 return Owned(new (Context)
1928 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001929 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001930 }
Chris Lattner87313662010-04-12 05:10:17 +00001931 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001932 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001933 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001934 ObjCInterfaceDecl *ClassDeclared;
1935 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1936 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1937 IFace == ClassDeclared)
1938 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1939 }
1940 }
1941
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001942 if (Lookup.empty() && II && AllowBuiltinCreation) {
1943 // FIXME. Consolidate this with similar code in LookupName.
1944 if (unsigned BuiltinID = II->getBuiltinID()) {
1945 if (!(getLangOptions().CPlusPlus &&
1946 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1947 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1948 S, Lookup.isForRedeclaration(),
1949 Lookup.getNameLoc());
1950 if (D) Lookup.addDecl(D);
1951 }
1952 }
1953 }
John McCalle66edc12009-11-24 19:00:30 +00001954 // Sentinel value saying that we didn't do anything special.
1955 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001956}
John McCalld14a8642009-11-21 08:51:07 +00001957
John McCall16df1e52010-03-30 21:47:33 +00001958/// \brief Cast a base object to a member's actual type.
1959///
1960/// Logically this happens in three phases:
1961///
1962/// * First we cast from the base type to the naming class.
1963/// The naming class is the class into which we were looking
1964/// when we found the member; it's the qualifier type if a
1965/// qualifier was provided, and otherwise it's the base type.
1966///
1967/// * Next we cast from the naming class to the declaring class.
1968/// If the member we found was brought into a class's scope by
1969/// a using declaration, this is that class; otherwise it's
1970/// the class declaring the member.
1971///
1972/// * Finally we cast from the declaring class to the "true"
1973/// declaring class of the member. This conversion does not
1974/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001975ExprResult
1976Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001977 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001978 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001979 NamedDecl *Member) {
1980 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1981 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001982 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001983
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001984 QualType DestRecordType;
1985 QualType DestType;
1986 QualType FromRecordType;
1987 QualType FromType = From->getType();
1988 bool PointerConversions = false;
1989 if (isa<FieldDecl>(Member)) {
1990 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001991
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001992 if (FromType->getAs<PointerType>()) {
1993 DestType = Context.getPointerType(DestRecordType);
1994 FromRecordType = FromType->getPointeeType();
1995 PointerConversions = true;
1996 } else {
1997 DestType = DestRecordType;
1998 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001999 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002000 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2001 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00002002 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002003
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002004 DestType = Method->getThisType(Context);
2005 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002006
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002007 if (FromType->getAs<PointerType>()) {
2008 FromRecordType = FromType->getPointeeType();
2009 PointerConversions = true;
2010 } else {
2011 FromRecordType = FromType;
2012 DestType = DestRecordType;
2013 }
2014 } else {
2015 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00002016 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002017 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002018
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002019 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002020 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002021
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002022 // If the unqualified types are the same, no conversion is necessary.
2023 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002024 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002025
John McCall16df1e52010-03-30 21:47:33 +00002026 SourceRange FromRange = From->getSourceRange();
2027 SourceLocation FromLoc = FromRange.getBegin();
2028
Eli Friedmanbe4b3632011-09-27 21:58:52 +00002029 ExprValueKind VK = From->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002030
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002031 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002032 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002033 // class name.
2034 //
2035 // If the member was a qualified name and the qualified referred to a
2036 // specific base subobject type, we'll cast to that intermediate type
2037 // first and then to the object in which the member is declared. That allows
2038 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2039 //
2040 // class Base { public: int x; };
2041 // class Derived1 : public Base { };
2042 // class Derived2 : public Base { };
2043 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2044 //
2045 // void VeryDerived::f() {
2046 // x = 17; // error: ambiguous base subobjects
2047 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2048 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002049 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002050 QualType QType = QualType(Qualifier->getAsType(), 0);
2051 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2052 assert(QType->isRecordType() && "lookup done with non-record type");
2053
2054 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2055
2056 // In C++98, the qualifier type doesn't actually have to be a base
2057 // type of the object type, in which case we just ignore it.
2058 // Otherwise build the appropriate casts.
2059 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002060 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002061 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002062 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002063 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002064
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002065 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002066 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002067 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2068 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002069
2070 FromType = QType;
2071 FromRecordType = QRecordType;
2072
2073 // If the qualifier type was the same as the destination type,
2074 // we're done.
2075 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002076 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002077 }
2078 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002079
John McCall16df1e52010-03-30 21:47:33 +00002080 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002081
John McCall16df1e52010-03-30 21:47:33 +00002082 // If we actually found the member through a using declaration, cast
2083 // down to the using declaration's type.
2084 //
2085 // Pointer equality is fine here because only one declaration of a
2086 // class ever has member declarations.
2087 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2088 assert(isa<UsingShadowDecl>(FoundDecl));
2089 QualType URecordType = Context.getTypeDeclType(
2090 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2091
2092 // We only need to do this if the naming-class to declaring-class
2093 // conversion is non-trivial.
2094 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2095 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002096 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002097 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002098 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002099 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002100
John McCall16df1e52010-03-30 21:47:33 +00002101 QualType UType = URecordType;
2102 if (PointerConversions)
2103 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002104 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2105 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002106 FromType = UType;
2107 FromRecordType = URecordType;
2108 }
2109
2110 // We don't do access control for the conversion from the
2111 // declaring class to the true declaring class.
2112 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002113 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002114
John McCallcf142162010-08-07 06:22:56 +00002115 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002116 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2117 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002118 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002119 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002120
John Wiegley01296292011-04-08 18:41:53 +00002121 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2122 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002123}
Douglas Gregor3256d042009-06-30 15:47:41 +00002124
John McCalle66edc12009-11-24 19:00:30 +00002125bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002126 const LookupResult &R,
2127 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002128 // Only when used directly as the postfix-expression of a call.
2129 if (!HasTrailingLParen)
2130 return false;
2131
2132 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002133 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002134 return false;
2135
2136 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002137 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002138 return false;
2139
2140 // Turn off ADL when we find certain kinds of declarations during
2141 // normal lookup:
2142 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2143 NamedDecl *D = *I;
2144
2145 // C++0x [basic.lookup.argdep]p3:
2146 // -- a declaration of a class member
2147 // Since using decls preserve this property, we check this on the
2148 // original decl.
John McCall57500772009-12-16 12:17:52 +00002149 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002150 return false;
2151
2152 // C++0x [basic.lookup.argdep]p3:
2153 // -- a block-scope function declaration that is not a
2154 // using-declaration
2155 // NOTE: we also trigger this for function templates (in fact, we
2156 // don't check the decl type at all, since all other decl types
2157 // turn off ADL anyway).
2158 if (isa<UsingShadowDecl>(D))
2159 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2160 else if (D->getDeclContext()->isFunctionOrMethod())
2161 return false;
2162
2163 // C++0x [basic.lookup.argdep]p3:
2164 // -- a declaration that is neither a function or a function
2165 // template
2166 // And also for builtin functions.
2167 if (isa<FunctionDecl>(D)) {
2168 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2169
2170 // But also builtin functions.
2171 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2172 return false;
2173 } else if (!isa<FunctionTemplateDecl>(D))
2174 return false;
2175 }
2176
2177 return true;
2178}
2179
2180
John McCalld14a8642009-11-21 08:51:07 +00002181/// Diagnoses obvious problems with the use of the given declaration
2182/// as an expression. This is only actually called for lookups that
2183/// were not overloaded, and it doesn't promise that the declaration
2184/// will in fact be used.
2185static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002186 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002187 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2188 return true;
2189 }
2190
2191 if (isa<ObjCInterfaceDecl>(D)) {
2192 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2193 return true;
2194 }
2195
2196 if (isa<NamespaceDecl>(D)) {
2197 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2198 return true;
2199 }
2200
2201 return false;
2202}
2203
John McCalldadc5752010-08-24 06:29:42 +00002204ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002205Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002206 LookupResult &R,
2207 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002208 // If this is a single, fully-resolved result and we don't need ADL,
2209 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002210 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002211 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2212 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002213
2214 // We only need to check the declaration if there's exactly one
2215 // result, because in the overloaded case the results can only be
2216 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002217 if (R.isSingleResult() &&
2218 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002219 return ExprError();
2220
John McCall58cc69d2010-01-27 01:50:18 +00002221 // Otherwise, just build an unresolved lookup expression. Suppress
2222 // any lookup-related diagnostics; we'll hash these out later, when
2223 // we've picked a target.
2224 R.suppressDiagnostics();
2225
John McCalld14a8642009-11-21 08:51:07 +00002226 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002227 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002228 SS.getWithLocInContext(Context),
2229 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002230 NeedsADL, R.isOverloadedResult(),
2231 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002232
2233 return Owned(ULE);
2234}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002235
John McCalld14a8642009-11-21 08:51:07 +00002236/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002237ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002238Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002239 const DeclarationNameInfo &NameInfo,
2240 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002241 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002242 assert(!isa<FunctionTemplateDecl>(D) &&
2243 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002244
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002245 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002246 if (CheckDeclInExpr(*this, Loc, D))
2247 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002248
Douglas Gregore7488b92009-12-01 16:58:18 +00002249 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2250 // Specifically diagnose references to class templates that are missing
2251 // a template argument list.
2252 Diag(Loc, diag::err_template_decl_ref)
2253 << Template << SS.getRange();
2254 Diag(Template->getLocation(), diag::note_template_decl_here);
2255 return ExprError();
2256 }
2257
2258 // Make sure that we're referring to a value.
2259 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2260 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002261 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002262 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002263 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002264 return ExprError();
2265 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002266
Douglas Gregor171c45a2009-02-18 21:56:37 +00002267 // Check whether this declaration can be used. Note that we suppress
2268 // this check when we're going to perform argument-dependent lookup
2269 // on this function name, because this might not be the function
2270 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002271 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002272 return ExprError();
2273
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002274 // Only create DeclRefExpr's for valid Decl's.
2275 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002276 return ExprError();
2277
John McCallf3a88602011-02-03 08:15:49 +00002278 // Handle members of anonymous structs and unions. If we got here,
2279 // and the reference is to a class member indirect field, then this
2280 // must be the subject of a pointer-to-member expression.
2281 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2282 if (!indirectField->isCXXClassMember())
2283 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2284 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002285
Chris Lattner2a9d9892008-10-20 05:16:36 +00002286 // If the identifier reference is inside a block, and it refers to a value
2287 // that is outside the block, create a BlockDeclRefExpr instead of a
2288 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2289 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002290 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002291 // We do not do this for things like enum constants, global variables, etc,
2292 // as they do not get snapshotted.
2293 //
John McCall351762c2011-02-07 10:33:21 +00002294 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002295 case CR_Error:
2296 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002297
John McCallc63de662011-02-02 13:00:07 +00002298 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002299 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2300 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2301
2302 case CR_CaptureByRef:
2303 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2304 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002305
2306 case CR_NoCapture: {
2307 // If this reference is not in a block or if the referenced
2308 // variable is within the block, create a normal DeclRefExpr.
2309
2310 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002311 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002312
2313 switch (D->getKind()) {
2314 // Ignore all the non-ValueDecl kinds.
2315#define ABSTRACT_DECL(kind)
2316#define VALUE(type, base)
2317#define DECL(type, base) \
2318 case Decl::type:
2319#include "clang/AST/DeclNodes.inc"
2320 llvm_unreachable("invalid value decl kind");
2321 return ExprError();
2322
2323 // These shouldn't make it here.
2324 case Decl::ObjCAtDefsField:
2325 case Decl::ObjCIvar:
2326 llvm_unreachable("forming non-member reference to ivar?");
2327 return ExprError();
2328
2329 // Enum constants are always r-values and never references.
2330 // Unresolved using declarations are dependent.
2331 case Decl::EnumConstant:
2332 case Decl::UnresolvedUsingValue:
2333 valueKind = VK_RValue;
2334 break;
2335
2336 // Fields and indirect fields that got here must be for
2337 // pointer-to-member expressions; we just call them l-values for
2338 // internal consistency, because this subexpression doesn't really
2339 // exist in the high-level semantics.
2340 case Decl::Field:
2341 case Decl::IndirectField:
2342 assert(getLangOptions().CPlusPlus &&
2343 "building reference to field in C?");
2344
2345 // These can't have reference type in well-formed programs, but
2346 // for internal consistency we do this anyway.
2347 type = type.getNonReferenceType();
2348 valueKind = VK_LValue;
2349 break;
2350
2351 // Non-type template parameters are either l-values or r-values
2352 // depending on the type.
2353 case Decl::NonTypeTemplateParm: {
2354 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2355 type = reftype->getPointeeType();
2356 valueKind = VK_LValue; // even if the parameter is an r-value reference
2357 break;
2358 }
2359
2360 // For non-references, we need to strip qualifiers just in case
2361 // the template parameter was declared as 'const int' or whatever.
2362 valueKind = VK_RValue;
2363 type = type.getUnqualifiedType();
2364 break;
2365 }
2366
2367 case Decl::Var:
2368 // In C, "extern void blah;" is valid and is an r-value.
2369 if (!getLangOptions().CPlusPlus &&
2370 !type.hasQualifiers() &&
2371 type->isVoidType()) {
2372 valueKind = VK_RValue;
2373 break;
2374 }
2375 // fallthrough
2376
2377 case Decl::ImplicitParam:
2378 case Decl::ParmVar:
2379 // These are always l-values.
2380 valueKind = VK_LValue;
2381 type = type.getNonReferenceType();
2382 break;
2383
2384 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002385 const FunctionType *fty = type->castAs<FunctionType>();
2386
2387 // If we're referring to a function with an __unknown_anytype
2388 // result type, make the entire expression __unknown_anytype.
2389 if (fty->getResultType() == Context.UnknownAnyTy) {
2390 type = Context.UnknownAnyTy;
2391 valueKind = VK_RValue;
2392 break;
2393 }
2394
John McCallf4cd4f92011-02-09 01:13:10 +00002395 // Functions are l-values in C++.
2396 if (getLangOptions().CPlusPlus) {
2397 valueKind = VK_LValue;
2398 break;
2399 }
2400
2401 // C99 DR 316 says that, if a function type comes from a
2402 // function definition (without a prototype), that type is only
2403 // used for checking compatibility. Therefore, when referencing
2404 // the function, we pretend that we don't have the full function
2405 // type.
John McCall2979fe02011-04-12 00:42:48 +00002406 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2407 isa<FunctionProtoType>(fty))
2408 type = Context.getFunctionNoProtoType(fty->getResultType(),
2409 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002410
2411 // Functions are r-values in C.
2412 valueKind = VK_RValue;
2413 break;
2414 }
2415
2416 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002417 // If we're referring to a method with an __unknown_anytype
2418 // result type, make the entire expression __unknown_anytype.
2419 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002420 if (const FunctionProtoType *proto
2421 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002422 if (proto->getResultType() == Context.UnknownAnyTy) {
2423 type = Context.UnknownAnyTy;
2424 valueKind = VK_RValue;
2425 break;
2426 }
2427
John McCallf4cd4f92011-02-09 01:13:10 +00002428 // C++ methods are l-values if static, r-values if non-static.
2429 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2430 valueKind = VK_LValue;
2431 break;
2432 }
2433 // fallthrough
2434
2435 case Decl::CXXConversion:
2436 case Decl::CXXDestructor:
2437 case Decl::CXXConstructor:
2438 valueKind = VK_RValue;
2439 break;
2440 }
2441
2442 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2443 }
2444
John McCallc63de662011-02-02 13:00:07 +00002445 }
John McCall7decc9e2010-11-18 06:31:45 +00002446
John McCall351762c2011-02-07 10:33:21 +00002447 llvm_unreachable("unknown capture result");
2448 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002449}
Chris Lattnere168f762006-11-10 05:29:30 +00002450
John McCall2979fe02011-04-12 00:42:48 +00002451ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002452 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002453
Chris Lattnere168f762006-11-10 05:29:30 +00002454 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002455 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002456 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2457 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2458 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002459 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002460
Chris Lattnera81a0272008-01-12 08:14:25 +00002461 // Pre-defined identifiers are of type char[x], where x is the length of the
2462 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002463
Anders Carlsson2fb08242009-09-08 18:24:21 +00002464 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002465 if (!currentDecl && getCurBlock())
2466 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002467 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002468 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002469 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002470 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002471
Anders Carlsson0b209a82009-09-11 01:22:35 +00002472 QualType ResTy;
2473 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2474 ResTy = Context.DependentTy;
2475 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002476 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002477
Anders Carlsson0b209a82009-09-11 01:22:35 +00002478 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002479 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002480 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2481 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002482 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002483}
2484
John McCalldadc5752010-08-24 06:29:42 +00002485ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002486 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002487 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002488 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002489 if (Invalid)
2490 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002491
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002492 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002493 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002494 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002495 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002496
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002497 QualType Ty;
2498 if (!getLangOptions().CPlusPlus)
2499 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2500 else if (Literal.isWide())
2501 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002502 else if (Literal.isUTF16())
2503 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2504 else if (Literal.isUTF32())
2505 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002506 else if (Literal.isMultiChar())
2507 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002508 else
2509 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002510
Douglas Gregorfb65e592011-07-27 05:40:30 +00002511 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2512 if (Literal.isWide())
2513 Kind = CharacterLiteral::Wide;
2514 else if (Literal.isUTF16())
2515 Kind = CharacterLiteral::UTF16;
2516 else if (Literal.isUTF32())
2517 Kind = CharacterLiteral::UTF32;
2518
2519 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2520 Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002521}
2522
John McCalldadc5752010-08-24 06:29:42 +00002523ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002524 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002525 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2526 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002527 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Douglas Gregore8bbc122011-09-02 00:18:52 +00002528 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002529 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002530 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002531 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002532
Chris Lattner23b7eb62007-06-15 23:05:46 +00002533 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002534 // Add padding so that NumericLiteralParser can overread by one character.
2535 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002536 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002537
Chris Lattner67ca9252007-05-21 01:08:44 +00002538 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002539 bool Invalid = false;
2540 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2541 if (Invalid)
2542 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002543
Mike Stump11289f42009-09-09 15:08:12 +00002544 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002545 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002546 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002547 return ExprError();
2548
Chris Lattner1c20a172007-08-26 03:42:43 +00002549 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002550
Chris Lattner1c20a172007-08-26 03:42:43 +00002551 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002552 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002553 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002554 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002555 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002556 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002557 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002558 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002559
2560 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2561
John McCall53b93a02009-12-24 09:08:04 +00002562 using llvm::APFloat;
2563 APFloat Val(Format);
2564
2565 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002566
2567 // Overflow is always an error, but underflow is only an error if
2568 // we underflowed to zero (APFloat reports denormals as underflow).
2569 if ((result & APFloat::opOverflow) ||
2570 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002571 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002572 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002573 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002574 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002575 APFloat::getLargest(Format).toString(buffer);
2576 } else {
John McCall62abc942010-02-26 23:35:57 +00002577 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002578 APFloat::getSmallest(Format).toString(buffer);
2579 }
2580
2581 Diag(Tok.getLocation(), diagnostic)
2582 << Ty
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002583 << StringRef(buffer.data(), buffer.size());
John McCall53b93a02009-12-24 09:08:04 +00002584 }
2585
2586 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002587 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002588
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002589 if (Ty == Context.DoubleTy) {
2590 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002591 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002592 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2593 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002594 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002595 }
2596 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002597 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002598 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002599 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002600 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002601
Neil Boothac582c52007-08-29 22:00:19 +00002602 // long long is a C99 feature.
2603 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002604 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002605 Diag(Tok.getLocation(), diag::ext_longlong);
2606
Chris Lattner67ca9252007-05-21 01:08:44 +00002607 // Get the value in the widest-possible width.
Douglas Gregore8bbc122011-09-02 00:18:52 +00002608 llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002609
Chris Lattner67ca9252007-05-21 01:08:44 +00002610 if (Literal.GetIntegerValue(ResultVal)) {
2611 // If this value didn't fit into uintmax_t, warn and force to ull.
2612 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002613 Ty = Context.UnsignedLongLongTy;
2614 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002615 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002616 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002617 // If this value fits into a ULL, try to figure out what else it fits into
2618 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002619
Chris Lattner67ca9252007-05-21 01:08:44 +00002620 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2621 // be an unsigned int.
2622 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2623
2624 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002625 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002626 if (!Literal.isLong && !Literal.isLongLong) {
2627 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00002628 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002629
Chris Lattner67ca9252007-05-21 01:08:44 +00002630 // Does it fit in a unsigned int?
2631 if (ResultVal.isIntN(IntSize)) {
2632 // Does it fit in a signed int?
2633 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002634 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002635 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002636 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002637 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002638 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002639 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002640
Chris Lattner67ca9252007-05-21 01:08:44 +00002641 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002642 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002643 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002644
Chris Lattner67ca9252007-05-21 01:08:44 +00002645 // Does it fit in a unsigned long?
2646 if (ResultVal.isIntN(LongSize)) {
2647 // Does it fit in a signed long?
2648 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002649 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002650 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002651 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002652 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002653 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002654 }
2655
Chris Lattner67ca9252007-05-21 01:08:44 +00002656 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002657 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002658 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002659
Chris Lattner67ca9252007-05-21 01:08:44 +00002660 // Does it fit in a unsigned long long?
2661 if (ResultVal.isIntN(LongLongSize)) {
2662 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002663 // To be compatible with MSVC, hex integer literals ending with the
2664 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002665 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
Francois Pichet0706d202011-09-17 17:15:52 +00002666 (getLangOptions().MicrosoftExt && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002667 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002668 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002669 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002670 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002671 }
2672 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002673
Chris Lattner67ca9252007-05-21 01:08:44 +00002674 // If we still couldn't decide a type, we probably have something that
2675 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002676 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002677 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002678 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00002679 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002680 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002681
Chris Lattner55258cf2008-05-09 05:59:00 +00002682 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002683 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002684 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002685 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002686 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002687
Chris Lattner1c20a172007-08-26 03:42:43 +00002688 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2689 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002690 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002691 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002692
2693 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002694}
2695
Richard Trieuba63ce62011-09-09 01:45:06 +00002696ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002697 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002698 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002699}
2700
Chandler Carruth62da79c2011-05-26 08:53:12 +00002701static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2702 SourceLocation Loc,
2703 SourceRange ArgRange) {
2704 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2705 // scalar or vector data type argument..."
2706 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2707 // type (C99 6.2.5p18) or void.
2708 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2709 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2710 << T << ArgRange;
2711 return true;
2712 }
2713
2714 assert((T->isVoidType() || !T->isIncompleteType()) &&
2715 "Scalar types should always be complete");
2716 return false;
2717}
2718
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002719static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2720 SourceLocation Loc,
2721 SourceRange ArgRange,
2722 UnaryExprOrTypeTrait TraitKind) {
2723 // C99 6.5.3.4p1:
2724 if (T->isFunctionType()) {
2725 // alignof(function) is allowed as an extension.
2726 if (TraitKind == UETT_SizeOf)
2727 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2728 return false;
2729 }
2730
2731 // Allow sizeof(void)/alignof(void) as an extension.
2732 if (T->isVoidType()) {
2733 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2734 return false;
2735 }
2736
2737 return true;
2738}
2739
2740static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2741 SourceLocation Loc,
2742 SourceRange ArgRange,
2743 UnaryExprOrTypeTrait TraitKind) {
2744 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2745 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2746 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2747 << T << (TraitKind == UETT_SizeOf)
2748 << ArgRange;
2749 return true;
2750 }
2751
2752 return false;
2753}
2754
Chandler Carruth14502c22011-05-26 08:53:10 +00002755/// \brief Check the constrains on expression operands to unary type expression
2756/// and type traits.
2757///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002758/// Completes any types necessary and validates the constraints on the operand
2759/// expression. The logic mostly mirrors the type-based overload, but may modify
2760/// the expression as it completes the type for that expression through template
2761/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00002762bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00002763 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002764 QualType ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002765
2766 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2767 // the result is the size of the referenced type."
2768 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2769 // result shall be the alignment of the referenced type."
2770 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2771 ExprTy = Ref->getPointeeType();
2772
2773 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002774 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2775 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00002776
2777 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002778 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2779 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002780 return false;
2781
Richard Trieuba63ce62011-09-09 01:45:06 +00002782 if (RequireCompleteExprType(E,
Chandler Carruth7c430c02011-05-27 01:33:31 +00002783 PDiag(diag::err_sizeof_alignof_incomplete_type)
Richard Trieuba63ce62011-09-09 01:45:06 +00002784 << ExprKind << E->getSourceRange(),
Chandler Carruth7c430c02011-05-27 01:33:31 +00002785 std::make_pair(SourceLocation(), PDiag(0))))
2786 return true;
2787
2788 // Completeing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00002789 ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002790 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2791 ExprTy = Ref->getPointeeType();
2792
Richard Trieuba63ce62011-09-09 01:45:06 +00002793 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2794 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002795 return true;
2796
Nico Weber0870deb2011-06-15 02:47:03 +00002797 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002798 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00002799 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2800 QualType OType = PVD->getOriginalType();
2801 QualType Type = PVD->getType();
2802 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002803 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00002804 << Type << OType;
2805 Diag(PVD->getLocation(), diag::note_declared_at);
2806 }
2807 }
2808 }
2809 }
2810
Chandler Carruth7c430c02011-05-27 01:33:31 +00002811 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002812}
2813
2814/// \brief Check the constraints on operands to unary expression and type
2815/// traits.
2816///
2817/// This will complete any types necessary, and validate the various constraints
2818/// on those operands.
2819///
Steve Naroff71b59a92007-06-04 22:22:31 +00002820/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002821/// C99 6.3.2.1p[2-4] all state:
2822/// Except when it is the operand of the sizeof operator ...
2823///
2824/// C++ [expr.sizeof]p4
2825/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2826/// standard conversions are not applied to the operand of sizeof.
2827///
2828/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00002829bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00002830 SourceLocation OpLoc,
2831 SourceRange ExprRange,
2832 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002833 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002834 return false;
2835
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002836 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2837 // the result is the size of the referenced type."
2838 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2839 // result shall be the alignment of the referenced type."
Richard Trieuba63ce62011-09-09 01:45:06 +00002840 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
2841 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002842
Chandler Carruth62da79c2011-05-26 08:53:12 +00002843 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002844 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002845
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002846 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002847 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002848 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00002849 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002850
Richard Trieuba63ce62011-09-09 01:45:06 +00002851 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002852 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002853 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002854 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002855
Richard Trieuba63ce62011-09-09 01:45:06 +00002856 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002857 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002858 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002859
Chris Lattner62975a72009-04-24 00:30:45 +00002860 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002861}
2862
Chandler Carruth14502c22011-05-26 08:53:10 +00002863static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002864 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002865
Mike Stump11289f42009-09-09 15:08:12 +00002866 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002867 if (isa<DeclRefExpr>(E))
2868 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002869
2870 // Cannot know anything else if the expression is dependent.
2871 if (E->isTypeDependent())
2872 return false;
2873
Douglas Gregor71235ec2009-05-02 02:18:30 +00002874 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002875 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2876 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00002877 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002878 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002879
2880 // Alignment of a field access is always okay, so long as it isn't a
2881 // bit-field.
2882 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002883 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002884 return false;
2885
Chandler Carruth14502c22011-05-26 08:53:10 +00002886 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002887}
2888
Chandler Carruth14502c22011-05-26 08:53:10 +00002889bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002890 E = E->IgnoreParens();
2891
2892 // Cannot know anything else if the expression is dependent.
2893 if (E->isTypeDependent())
2894 return false;
2895
Chandler Carruth14502c22011-05-26 08:53:10 +00002896 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002897}
2898
Douglas Gregor0950e412009-03-13 21:01:28 +00002899/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002900ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002901Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2902 SourceLocation OpLoc,
2903 UnaryExprOrTypeTrait ExprKind,
2904 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002905 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002906 return ExprError();
2907
John McCallbcd03502009-12-07 02:54:59 +00002908 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002909
Douglas Gregor0950e412009-03-13 21:01:28 +00002910 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002911 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002912 return ExprError();
2913
2914 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002915 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2916 Context.getSizeType(),
2917 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002918}
2919
2920/// \brief Build a sizeof or alignof expression given an expression
2921/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002922ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00002923Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2924 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00002925 ExprResult PE = CheckPlaceholderExpr(E);
2926 if (PE.isInvalid())
2927 return ExprError();
2928
2929 E = PE.get();
2930
Douglas Gregor0950e412009-03-13 21:01:28 +00002931 // Verify that the operand is valid.
2932 bool isInvalid = false;
2933 if (E->isTypeDependent()) {
2934 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002935 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002936 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002937 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002938 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002939 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00002940 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00002941 isInvalid = true;
2942 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00002943 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002944 }
2945
2946 if (isInvalid)
2947 return ExprError();
2948
2949 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00002950 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00002951 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00002952 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002953}
2954
Peter Collingbournee190dee2011-03-11 19:24:49 +00002955/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2956/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00002957/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002958ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002959Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00002960 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00002961 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002962 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002963 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002964
Richard Trieuba63ce62011-09-09 01:45:06 +00002965 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00002966 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002967 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002968 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002969 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002970
Douglas Gregor0950e412009-03-13 21:01:28 +00002971 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00002972 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00002973 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002974}
2975
John Wiegley01296292011-04-08 18:41:53 +00002976static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00002977 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00002978 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002979 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002980
John McCall34376a62010-12-04 03:47:34 +00002981 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00002982 if (V.get()->getObjectKind() != OK_Ordinary) {
2983 V = S.DefaultLvalueConversion(V.take());
2984 if (V.isInvalid())
2985 return QualType();
2986 }
John McCall34376a62010-12-04 03:47:34 +00002987
Chris Lattnere267f5d2007-08-26 05:39:26 +00002988 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00002989 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002990 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002991
Chris Lattnere267f5d2007-08-26 05:39:26 +00002992 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00002993 if (V.get()->getType()->isArithmeticType())
2994 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002995
John McCall36226622010-10-12 02:09:17 +00002996 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00002997 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00002998 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00002999 if (PR.get() != V.get()) {
3000 V = move(PR);
Richard Trieuba63ce62011-09-09 01:45:06 +00003001 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00003002 }
3003
Chris Lattnere267f5d2007-08-26 05:39:26 +00003004 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003005 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00003006 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003007 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003008}
3009
3010
Chris Lattnere168f762006-11-10 05:29:30 +00003011
John McCalldadc5752010-08-24 06:29:42 +00003012ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003013Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003014 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003015 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003016 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003017 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003018 case tok::plusplus: Opc = UO_PostInc; break;
3019 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003020 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003021
John McCallb268a282010-08-23 23:25:46 +00003022 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003023}
3024
John McCalldadc5752010-08-24 06:29:42 +00003025ExprResult
John McCallb268a282010-08-23 23:25:46 +00003026Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3027 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003028 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003029 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003030 if (Result.isInvalid()) return ExprError();
3031 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003032
John McCallb268a282010-08-23 23:25:46 +00003033 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003034
Douglas Gregor40412ac2008-11-19 17:17:41 +00003035 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003036 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003037 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003038 Context.DependentTy,
3039 VK_LValue, OK_Ordinary,
3040 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003041 }
3042
Mike Stump11289f42009-09-09 15:08:12 +00003043 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003044 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003045 LHSExp->getType()->isEnumeralType() ||
3046 RHSExp->getType()->isRecordType() ||
3047 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00003048 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003049 }
3050
John McCallb268a282010-08-23 23:25:46 +00003051 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003052}
3053
3054
John McCalldadc5752010-08-24 06:29:42 +00003055ExprResult
John McCallb268a282010-08-23 23:25:46 +00003056Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003057 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00003058 Expr *LHSExp = Base;
3059 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003060
Chris Lattner36d572b2007-07-16 00:14:47 +00003061 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003062 if (!LHSExp->getType()->getAs<VectorType>()) {
3063 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3064 if (Result.isInvalid())
3065 return ExprError();
3066 LHSExp = Result.take();
3067 }
3068 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3069 if (Result.isInvalid())
3070 return ExprError();
3071 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003072
Chris Lattner36d572b2007-07-16 00:14:47 +00003073 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003074 ExprValueKind VK = VK_LValue;
3075 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003076
Steve Naroffc1aadb12007-03-28 21:49:40 +00003077 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003078 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003079 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003080 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003081 Expr *BaseExpr, *IndexExpr;
3082 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003083 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3084 BaseExpr = LHSExp;
3085 IndexExpr = RHSExp;
3086 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003087 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003088 BaseExpr = LHSExp;
3089 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003090 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003091 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003092 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003093 BaseExpr = RHSExp;
3094 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003095 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003096 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003097 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003098 BaseExpr = LHSExp;
3099 IndexExpr = RHSExp;
3100 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003101 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003102 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003103 // Handle the uncommon case of "123[Ptr]".
3104 BaseExpr = RHSExp;
3105 IndexExpr = LHSExp;
3106 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003107 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003108 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003109 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003110 VK = LHSExp->getValueKind();
3111 if (VK != VK_RValue)
3112 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003113
Chris Lattner36d572b2007-07-16 00:14:47 +00003114 // FIXME: need to deal with const...
3115 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003116 } else if (LHSTy->isArrayType()) {
3117 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003118 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003119 // wasn't promoted because of the C90 rule that doesn't
3120 // allow promoting non-lvalue arrays. Warn, then
3121 // force the promotion here.
3122 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3123 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003124 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3125 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003126 LHSTy = LHSExp->getType();
3127
3128 BaseExpr = LHSExp;
3129 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003130 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003131 } else if (RHSTy->isArrayType()) {
3132 // Same as previous, except for 123[f().a] case
3133 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3134 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003135 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3136 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003137 RHSTy = RHSExp->getType();
3138
3139 BaseExpr = RHSExp;
3140 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003141 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003142 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003143 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3144 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003145 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003146 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003147 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003148 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3149 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003150
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003151 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003152 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3153 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003154 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3155
Douglas Gregorac1fb652009-03-24 19:52:54 +00003156 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003157 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3158 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003159 // incomplete types are not object types.
3160 if (ResultType->isFunctionType()) {
3161 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3162 << ResultType << BaseExpr->getSourceRange();
3163 return ExprError();
3164 }
Mike Stump11289f42009-09-09 15:08:12 +00003165
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003166 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3167 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003168 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3169 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003170
3171 // C forbids expressions of unqualified void type from being l-values.
3172 // See IsCForbiddenLValueType.
3173 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003174 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003175 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003176 PDiag(diag::err_subscript_incomplete_type)
3177 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003178 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003179
Chris Lattner62975a72009-04-24 00:30:45 +00003180 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003181 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003182 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3183 << ResultType << BaseExpr->getSourceRange();
3184 return ExprError();
3185 }
Mike Stump11289f42009-09-09 15:08:12 +00003186
John McCall4bc41ae2010-11-18 19:01:18 +00003187 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003188 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003189
Mike Stump4e1f26a2009-02-19 03:04:26 +00003190 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003191 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003192}
3193
John McCalldadc5752010-08-24 06:29:42 +00003194ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003195 FunctionDecl *FD,
3196 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003197 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003198 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003199 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003200 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003201 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003202 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003203 return ExprError();
3204 }
3205
3206 if (Param->hasUninstantiatedDefaultArg()) {
3207 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003208
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003209 // Instantiate the expression.
3210 MultiLevelTemplateArgumentList ArgList
3211 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003212
Nico Weber44887f62010-11-29 18:19:25 +00003213 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003214 = ArgList.getInnermost();
3215 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3216 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003217
Nico Weber44887f62010-11-29 18:19:25 +00003218 ExprResult Result;
3219 {
3220 // C++ [dcl.fct.default]p5:
3221 // The names in the [default argument] expression are bound, and
3222 // the semantic constraints are checked, at the point where the
3223 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003224 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00003225 Result = SubstExpr(UninstExpr, ArgList);
3226 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003227 if (Result.isInvalid())
3228 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003229
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003230 // Check the expression as an initializer for the parameter.
3231 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003232 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003233 InitializationKind Kind
3234 = InitializationKind::CreateCopy(Param->getLocation(),
3235 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3236 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003237
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003238 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3239 Result = InitSeq.Perform(*this, Entity, Kind,
3240 MultiExprArg(*this, &ResultE, 1));
3241 if (Result.isInvalid())
3242 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003243
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003244 // Build the default argument expression.
3245 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3246 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003247 }
3248
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003249 // If the default expression creates temporaries, we need to
3250 // push them to the current stack of expression temporaries so they'll
3251 // be properly destroyed.
3252 // FIXME: We should really be rebuilding the default argument with new
3253 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003254 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3255 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3256 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3257 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3258 ExprTemporaries.push_back(Temporary);
John McCall31168b02011-06-15 23:02:42 +00003259 ExprNeedsCleanups = true;
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003260 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003261
3262 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003263 // Just mark all of the declarations in this potentially-evaluated expression
3264 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003265 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00003266 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003267}
3268
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003269/// ConvertArgumentsForCall - Converts the arguments specified in
3270/// Args/NumArgs to the parameter types of the function FDecl with
3271/// function prototype Proto. Call is the call expression itself, and
3272/// Fn is the function expression. For a C++ member function, this
3273/// routine does not attempt to convert the object argument. Returns
3274/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003275bool
3276Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003277 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003278 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003279 Expr **Args, unsigned NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003280 SourceLocation RParenLoc,
3281 bool IsExecConfig) {
John McCallbebede42011-02-26 05:39:39 +00003282 // Bail out early if calling a builtin with custom typechecking.
3283 // We don't need to do this in the
3284 if (FDecl)
3285 if (unsigned ID = FDecl->getBuiltinID())
3286 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3287 return false;
3288
Mike Stump4e1f26a2009-02-19 03:04:26 +00003289 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003290 // assignment, to the types of the corresponding parameter, ...
3291 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003292 bool Invalid = false;
Peter Collingbourne740afe22011-10-02 23:49:20 +00003293 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003294 unsigned FnKind = Fn->getType()->isBlockPointerType()
3295 ? 1 /* block */
3296 : (IsExecConfig ? 3 /* kernel function (exec config) */
3297 : 0 /* function */);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003298
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003299 // If too few arguments are available (and we don't have default
3300 // arguments for the remaining parameters), don't make the call.
3301 if (NumArgs < NumArgsInProto) {
Peter Collingbourne740afe22011-10-02 23:49:20 +00003302 if (NumArgs < MinArgs) {
3303 Diag(RParenLoc, MinArgs == NumArgsInProto
3304 ? diag::err_typecheck_call_too_few_args
3305 : diag::err_typecheck_call_too_few_args_at_least)
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003306 << FnKind
Peter Collingbourne740afe22011-10-02 23:49:20 +00003307 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003308
3309 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003310 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003311 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3312 << FDecl;
3313
3314 return true;
3315 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003316 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003317 }
3318
3319 // If too many are passed and not variadic, error on the extras and drop
3320 // them.
3321 if (NumArgs > NumArgsInProto) {
3322 if (!Proto->isVariadic()) {
3323 Diag(Args[NumArgsInProto]->getLocStart(),
Peter Collingbourne740afe22011-10-02 23:49:20 +00003324 MinArgs == NumArgsInProto
3325 ? diag::err_typecheck_call_too_many_args
3326 : diag::err_typecheck_call_too_many_args_at_most)
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003327 << FnKind
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003328 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003329 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3330 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003331
3332 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003333 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003334 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3335 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003336
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003337 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003338 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003339 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003340 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003341 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003342 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003343 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003344 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3345 if (Fn->getType()->isBlockPointerType())
3346 CallType = VariadicBlock; // Block
3347 else if (isa<MemberExpr>(Fn))
3348 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003349 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003350 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003351 if (Invalid)
3352 return true;
3353 unsigned TotalNumArgs = AllArgs.size();
3354 for (unsigned i = 0; i < TotalNumArgs; ++i)
3355 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003356
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003357 return false;
3358}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003359
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003360bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3361 FunctionDecl *FDecl,
3362 const FunctionProtoType *Proto,
3363 unsigned FirstProtoArg,
3364 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003365 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003366 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003367 unsigned NumArgsInProto = Proto->getNumArgs();
3368 unsigned NumArgsToCheck = NumArgs;
3369 bool Invalid = false;
3370 if (NumArgs != NumArgsInProto)
3371 // Use default arguments for missing arguments
3372 NumArgsToCheck = NumArgsInProto;
3373 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003374 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003375 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003376 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003377
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003378 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003379 if (ArgIx < NumArgs) {
3380 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003381
Eli Friedman3164fb12009-03-22 22:00:50 +00003382 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3383 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003384 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003385 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003386 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003387
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003388 // Pass the argument
3389 ParmVarDecl *Param = 0;
3390 if (FDecl && i < FDecl->getNumParams())
3391 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003392
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003393 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003394 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003395 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3396 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003397 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003398 SourceLocation(),
3399 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003400 if (ArgE.isInvalid())
3401 return true;
3402
3403 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003404 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003405 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003406
John McCalldadc5752010-08-24 06:29:42 +00003407 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003408 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003409 if (ArgExpr.isInvalid())
3410 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003411
Anders Carlsson355933d2009-08-25 03:49:14 +00003412 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003413 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003414
3415 // Check for array bounds violations for each argument to the call. This
3416 // check only triggers warnings when the argument isn't a more complex Expr
3417 // with its own checking, such as a BinaryOperator.
3418 CheckArrayAccess(Arg);
3419
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003420 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003421 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003422
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003423 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003424 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003425
3426 // Assume that extern "C" functions with variadic arguments that
3427 // return __unknown_anytype aren't *really* variadic.
3428 if (Proto->getResultType() == Context.UnknownAnyTy &&
3429 FDecl && FDecl->isExternC()) {
3430 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3431 ExprResult arg;
3432 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3433 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3434 else
3435 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3436 Invalid |= arg.isInvalid();
3437 AllArgs.push_back(arg.take());
3438 }
3439
3440 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3441 } else {
3442 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003443 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3444 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003445 Invalid |= Arg.isInvalid();
3446 AllArgs.push_back(Arg.take());
3447 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003448 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00003449
3450 // Check for array bounds violations.
3451 for (unsigned i = ArgIx; i != NumArgs; ++i)
3452 CheckArrayAccess(Args[i]);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003453 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003454 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003455}
3456
John McCall2979fe02011-04-12 00:42:48 +00003457/// Given a function expression of unknown-any type, try to rebuild it
3458/// to have a function type.
3459static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3460
Steve Naroff83895f72007-09-16 03:34:24 +00003461/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003462/// This provides the location of the left/right parens and a list of comma
3463/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003464ExprResult
John McCallb268a282010-08-23 23:25:46 +00003465Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003466 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003467 Expr *ExecConfig, bool IsExecConfig) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003468 unsigned NumArgs = ArgExprs.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003469
3470 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003471 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003472 if (Result.isInvalid()) return ExprError();
3473 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003474
Richard Trieuba63ce62011-09-09 01:45:06 +00003475 Expr **Args = ArgExprs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003476
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003477 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003478 // If this is a pseudo-destructor expression, build the call immediately.
3479 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3480 if (NumArgs > 0) {
3481 // Pseudo-destructor calls should not have any arguments.
3482 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003483 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003484 SourceRange(Args[0]->getLocStart(),
3485 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003486
Douglas Gregorad8a3362009-09-04 17:36:40 +00003487 NumArgs = 0;
3488 }
Mike Stump11289f42009-09-09 15:08:12 +00003489
Douglas Gregorad8a3362009-09-04 17:36:40 +00003490 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003491 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003492 }
Mike Stump11289f42009-09-09 15:08:12 +00003493
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003494 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003495 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003496 // FIXME: Will need to cache the results of name lookup (including ADL) in
3497 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003498 bool Dependent = false;
3499 if (Fn->isTypeDependent())
3500 Dependent = true;
3501 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3502 Dependent = true;
3503
Peter Collingbourne41f85462011-02-09 21:07:24 +00003504 if (Dependent) {
3505 if (ExecConfig) {
3506 return Owned(new (Context) CUDAKernelCallExpr(
3507 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3508 Context.DependentTy, VK_RValue, RParenLoc));
3509 } else {
3510 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3511 Context.DependentTy, VK_RValue,
3512 RParenLoc));
3513 }
3514 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003515
3516 // Determine whether this is a call to an object (C++ [over.call.object]).
3517 if (Fn->getType()->isRecordType())
3518 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003519 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003520
John McCall2979fe02011-04-12 00:42:48 +00003521 if (Fn->getType() == Context.UnknownAnyTy) {
3522 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3523 if (result.isInvalid()) return ExprError();
3524 Fn = result.take();
3525 }
3526
John McCall0009fcc2011-04-26 20:42:42 +00003527 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003528 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003529 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003530 }
John McCall0009fcc2011-04-26 20:42:42 +00003531 }
John McCall10eae182009-11-30 22:42:35 +00003532
John McCall0009fcc2011-04-26 20:42:42 +00003533 // Check for overloaded calls. This can happen even in C due to extensions.
3534 if (Fn->getType() == Context.OverloadTy) {
3535 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3536
3537 // We aren't supposed to apply this logic if there's an '&' involved.
3538 if (!find.IsAddressOfOperand) {
3539 OverloadExpr *ovl = find.Expression;
3540 if (isa<UnresolvedLookupExpr>(ovl)) {
3541 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3542 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3543 RParenLoc, ExecConfig);
3544 } else {
John McCall2d74de92009-12-01 22:10:20 +00003545 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003546 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003547 }
3548 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003549 }
3550
Douglas Gregore254f902009-02-04 00:32:51 +00003551 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003552
Eli Friedmane14b1992009-12-26 03:35:45 +00003553 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003554
John McCall57500772009-12-16 12:17:52 +00003555 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003556 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3557 if (UnOp->getOpcode() == UO_AddrOf)
3558 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3559
John McCall57500772009-12-16 12:17:52 +00003560 if (isa<DeclRefExpr>(NakedFn))
3561 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003562 else if (isa<MemberExpr>(NakedFn))
3563 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003564
Peter Collingbourne41f85462011-02-09 21:07:24 +00003565 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003566 ExecConfig, IsExecConfig);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003567}
3568
3569ExprResult
3570Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003571 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbourne41f85462011-02-09 21:07:24 +00003572 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3573 if (!ConfigDecl)
3574 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3575 << "cudaConfigureCall");
3576 QualType ConfigQTy = ConfigDecl->getType();
3577
3578 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3579 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3580
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003581 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3582 /*IsExecConfig=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003583}
3584
Tanya Lattner55808c12011-06-04 00:47:47 +00003585/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3586///
3587/// __builtin_astype( value, dst type )
3588///
Richard Trieuba63ce62011-09-09 01:45:06 +00003589ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00003590 SourceLocation BuiltinLoc,
3591 SourceLocation RParenLoc) {
3592 ExprValueKind VK = VK_RValue;
3593 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00003594 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3595 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00003596 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3597 return ExprError(Diag(BuiltinLoc,
3598 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003599 << DstTy
3600 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00003601 << E->getSourceRange());
3602 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieucfc491d2011-08-02 04:35:43 +00003603 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003604}
3605
John McCall57500772009-12-16 12:17:52 +00003606/// BuildResolvedCallExpr - Build a call to a resolved expression,
3607/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003608/// unary-convert to an expression of function-pointer or
3609/// block-pointer type.
3610///
3611/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003612ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003613Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3614 SourceLocation LParenLoc,
3615 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003616 SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003617 Expr *Config, bool IsExecConfig) {
John McCall2d74de92009-12-01 22:10:20 +00003618 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3619
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003620 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003621 ExprResult Result = UsualUnaryConversions(Fn);
3622 if (Result.isInvalid())
3623 return ExprError();
3624 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003625
Chris Lattner08464942007-12-28 05:29:59 +00003626 // Make the call expr early, before semantic checks. This guarantees cleanup
3627 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003628 CallExpr *TheCall;
3629 if (Config) {
3630 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3631 cast<CallExpr>(Config),
3632 Args, NumArgs,
3633 Context.BoolTy,
3634 VK_RValue,
3635 RParenLoc);
3636 } else {
3637 TheCall = new (Context) CallExpr(Context, Fn,
3638 Args, NumArgs,
3639 Context.BoolTy,
3640 VK_RValue,
3641 RParenLoc);
3642 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003643
John McCallbebede42011-02-26 05:39:39 +00003644 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3645
3646 // Bail out early if calling a builtin with custom typechecking.
3647 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3648 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3649
John McCall31996342011-04-07 08:22:57 +00003650 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003651 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003652 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003653 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3654 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003655 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003656 if (FuncT == 0)
3657 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3658 << Fn->getType() << Fn->getSourceRange());
3659 } else if (const BlockPointerType *BPT =
3660 Fn->getType()->getAs<BlockPointerType>()) {
3661 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3662 } else {
John McCall31996342011-04-07 08:22:57 +00003663 // Handle calls to expressions of unknown-any type.
3664 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003665 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003666 if (rewrite.isInvalid()) return ExprError();
3667 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003668 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003669 goto retry;
3670 }
3671
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003672 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3673 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003674 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003675
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003676 if (getLangOptions().CUDA) {
3677 if (Config) {
3678 // CUDA: Kernel calls must be to global functions
3679 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3680 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3681 << FDecl->getName() << Fn->getSourceRange());
3682
3683 // CUDA: Kernel function must have 'void' return type
3684 if (!FuncT->getResultType()->isVoidType())
3685 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3686 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne34a20b02011-10-02 23:49:15 +00003687 } else {
3688 // CUDA: Calls to global functions must be configured
3689 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
3690 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
3691 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003692 }
3693 }
3694
Eli Friedman3164fb12009-03-22 22:00:50 +00003695 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003696 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00003697 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003698 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003699 return ExprError();
3700
Chris Lattner08464942007-12-28 05:29:59 +00003701 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003702 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003703 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003704
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003705 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003706 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003707 RParenLoc, IsExecConfig))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003708 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003709 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003710 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003711
Douglas Gregord8e97de2009-04-02 15:37:10 +00003712 if (FDecl) {
3713 // Check if we have too few/too many template arguments, based
3714 // on our knowledge of the function definition.
3715 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003716 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003717 const FunctionProtoType *Proto
3718 = Def->getType()->getAs<FunctionProtoType>();
3719 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003720 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3721 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003722 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003723
3724 // If the function we're calling isn't a function prototype, but we have
3725 // a function prototype from a prior declaratiom, use that prototype.
3726 if (!FDecl->hasPrototype())
3727 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003728 }
3729
Steve Naroff0b661582007-08-28 23:30:39 +00003730 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003731 for (unsigned i = 0; i != NumArgs; i++) {
3732 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003733
3734 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003735 InitializedEntity Entity
3736 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003737 Proto->getArgType(i),
3738 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003739 ExprResult ArgE = PerformCopyInitialization(Entity,
3740 SourceLocation(),
3741 Owned(Arg));
3742 if (ArgE.isInvalid())
3743 return true;
3744
3745 Arg = ArgE.takeAs<Expr>();
3746
3747 } else {
John Wiegley01296292011-04-08 18:41:53 +00003748 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3749
3750 if (ArgE.isInvalid())
3751 return true;
3752
3753 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003754 }
3755
Douglas Gregor83025412010-10-26 05:45:40 +00003756 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3757 Arg->getType(),
3758 PDiag(diag::err_call_incomplete_argument)
3759 << Arg->getSourceRange()))
3760 return ExprError();
3761
Chris Lattner08464942007-12-28 05:29:59 +00003762 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003763 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003764 }
Chris Lattner08464942007-12-28 05:29:59 +00003765
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003766 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3767 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003768 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3769 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003770
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003771 // Check for sentinels
3772 if (NDecl)
3773 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003774
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003775 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003776 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003777 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003778 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003779
John McCallbebede42011-02-26 05:39:39 +00003780 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003781 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003782 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003783 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003784 return ExprError();
3785 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003786
John McCallb268a282010-08-23 23:25:46 +00003787 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003788}
3789
John McCalldadc5752010-08-24 06:29:42 +00003790ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003791Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003792 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003793 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003794 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003795 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003796
3797 TypeSourceInfo *TInfo;
3798 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3799 if (!TInfo)
3800 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3801
John McCallb268a282010-08-23 23:25:46 +00003802 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003803}
3804
John McCalldadc5752010-08-24 06:29:42 +00003805ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003806Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00003807 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003808 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003809
Eli Friedman37a186d2008-05-20 05:22:08 +00003810 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003811 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3812 PDiag(diag::err_illegal_decl_array_incomplete_type)
3813 << SourceRange(LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003814 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003815 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00003816 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003817 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00003818 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003819 } else if (!literalType->isDependentType() &&
3820 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003821 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003822 << SourceRange(LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003823 LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003824 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003825
Douglas Gregor85dabae2009-12-16 01:38:02 +00003826 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003827 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003828 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00003829 = InitializationKind::CreateCStyleCast(LParenLoc,
3830 SourceRange(LParenLoc, RParenLoc));
Richard Trieuba63ce62011-09-09 01:45:06 +00003831 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003832 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuba63ce62011-09-09 01:45:06 +00003833 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003834 &literalType);
3835 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003836 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00003837 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003838
Chris Lattner79413952008-12-04 23:50:19 +00003839 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003840 if (isFileScope) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00003841 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003842 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003843 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003844
John McCall7decc9e2010-11-18 06:31:45 +00003845 // In C, compound literals are l-values for some reason.
3846 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3847
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00003848 return MaybeBindToTemporary(
3849 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00003850 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003851}
3852
John McCalldadc5752010-08-24 06:29:42 +00003853ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00003854Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003855 SourceLocation RBraceLoc) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003856 unsigned NumInit = InitArgList.size();
3857 Expr **InitList = InitArgList.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00003858
Steve Naroff30d242c2007-09-15 18:49:24 +00003859 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003860 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003861
Ted Kremenekac034612010-04-13 23:39:13 +00003862 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3863 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003864 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003865 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003866}
3867
John McCallcd78e802011-09-10 01:16:55 +00003868/// Do an explicit extend of the given block pointer if we're in ARC.
3869static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
3870 assert(E.get()->getType()->isBlockPointerType());
3871 assert(E.get()->isRValue());
3872
3873 // Only do this in an r-value context.
3874 if (!S.getLangOptions().ObjCAutoRefCount) return;
3875
3876 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00003877 CK_ARCExtendBlockObject, E.get(),
John McCallcd78e802011-09-10 01:16:55 +00003878 /*base path*/ 0, VK_RValue);
3879 S.ExprNeedsCleanups = true;
3880}
3881
3882/// Prepare a conversion of the given expression to an ObjC object
3883/// pointer type.
3884CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
3885 QualType type = E.get()->getType();
3886 if (type->isObjCObjectPointerType()) {
3887 return CK_BitCast;
3888 } else if (type->isBlockPointerType()) {
3889 maybeExtendBlockObject(*this, E);
3890 return CK_BlockPointerToObjCPointerCast;
3891 } else {
3892 assert(type->isPointerType());
3893 return CK_CPointerToObjCPointerCast;
3894 }
3895}
3896
John McCalld7646252010-11-14 08:17:51 +00003897/// Prepares for a scalar cast, performing all the necessary stages
3898/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00003899static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00003900 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3901 // Also, callers should have filtered out the invalid cases with
3902 // pointers. Everything else should be possible.
3903
John Wiegley01296292011-04-08 18:41:53 +00003904 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00003905 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00003906 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00003907
John McCall9320b872011-09-09 05:25:32 +00003908 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00003909 case Type::STK_MemberPointer:
3910 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00003911
John McCall9320b872011-09-09 05:25:32 +00003912 case Type::STK_CPointer:
3913 case Type::STK_BlockPointer:
3914 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00003915 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00003916 case Type::STK_CPointer:
3917 return CK_BitCast;
3918 case Type::STK_BlockPointer:
3919 return (SrcKind == Type::STK_BlockPointer
3920 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
3921 case Type::STK_ObjCObjectPointer:
3922 if (SrcKind == Type::STK_ObjCObjectPointer)
3923 return CK_BitCast;
3924 else if (SrcKind == Type::STK_CPointer)
3925 return CK_CPointerToObjCPointerCast;
John McCallcd78e802011-09-10 01:16:55 +00003926 else {
3927 maybeExtendBlockObject(S, Src);
John McCall9320b872011-09-09 05:25:32 +00003928 return CK_BlockPointerToObjCPointerCast;
John McCallcd78e802011-09-10 01:16:55 +00003929 }
John McCall8cb679e2010-11-15 09:13:47 +00003930 case Type::STK_Bool:
3931 return CK_PointerToBoolean;
3932 case Type::STK_Integral:
3933 return CK_PointerToIntegral;
3934 case Type::STK_Floating:
3935 case Type::STK_FloatingComplex:
3936 case Type::STK_IntegralComplex:
3937 case Type::STK_MemberPointer:
3938 llvm_unreachable("illegal cast from pointer");
3939 }
3940 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003941
John McCall8cb679e2010-11-15 09:13:47 +00003942 case Type::STK_Bool: // casting from bool is like casting from an integer
3943 case Type::STK_Integral:
3944 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00003945 case Type::STK_CPointer:
3946 case Type::STK_ObjCObjectPointer:
3947 case Type::STK_BlockPointer:
Richard Trieucfc491d2011-08-02 04:35:43 +00003948 if (Src.get()->isNullPointerConstant(S.Context,
3949 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00003950 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00003951 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00003952 case Type::STK_Bool:
3953 return CK_IntegralToBoolean;
3954 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00003955 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00003956 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003957 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003958 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003959 Src = S.ImpCastExprToType(Src.take(),
3960 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003961 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00003962 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003963 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003964 Src = S.ImpCastExprToType(Src.take(),
3965 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003966 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00003967 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003968 case Type::STK_MemberPointer:
3969 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003970 }
3971 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003972
John McCall8cb679e2010-11-15 09:13:47 +00003973 case Type::STK_Floating:
3974 switch (DestTy->getScalarTypeKind()) {
3975 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003976 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00003977 case Type::STK_Bool:
3978 return CK_FloatingToBoolean;
3979 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00003980 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003981 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003982 Src = S.ImpCastExprToType(Src.take(),
3983 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003984 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00003985 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003986 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003987 Src = S.ImpCastExprToType(Src.take(),
3988 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003989 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00003990 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00003991 case Type::STK_CPointer:
3992 case Type::STK_ObjCObjectPointer:
3993 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00003994 llvm_unreachable("valid float->pointer cast?");
3995 case Type::STK_MemberPointer:
3996 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003997 }
3998 break;
3999
John McCall8cb679e2010-11-15 09:13:47 +00004000 case Type::STK_FloatingComplex:
4001 switch (DestTy->getScalarTypeKind()) {
4002 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004003 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004004 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004005 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004006 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00004007 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00004008 if (S.Context.hasSameType(ET, DestTy))
4009 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00004010 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004011 return CK_FloatingCast;
4012 }
John McCall8cb679e2010-11-15 09:13:47 +00004013 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004014 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004015 case Type::STK_Integral:
Richard Trieucfc491d2011-08-02 04:35:43 +00004016 Src = S.ImpCastExprToType(Src.take(),
4017 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00004018 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004019 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00004020 case Type::STK_CPointer:
4021 case Type::STK_ObjCObjectPointer:
4022 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004023 llvm_unreachable("valid complex float->pointer cast?");
4024 case Type::STK_MemberPointer:
4025 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004026 }
4027 break;
4028
John McCall8cb679e2010-11-15 09:13:47 +00004029 case Type::STK_IntegralComplex:
4030 switch (DestTy->getScalarTypeKind()) {
4031 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004032 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004033 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004034 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004035 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00004036 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00004037 if (S.Context.hasSameType(ET, DestTy))
4038 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00004039 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004040 return CK_IntegralCast;
4041 }
John McCall8cb679e2010-11-15 09:13:47 +00004042 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004043 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004044 case Type::STK_Floating:
Richard Trieucfc491d2011-08-02 04:35:43 +00004045 Src = S.ImpCastExprToType(Src.take(),
4046 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00004047 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004048 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00004049 case Type::STK_CPointer:
4050 case Type::STK_ObjCObjectPointer:
4051 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004052 llvm_unreachable("valid complex int->pointer cast?");
4053 case Type::STK_MemberPointer:
4054 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004055 }
4056 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00004057 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004058
John McCalld7646252010-11-14 08:17:51 +00004059 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00004060}
4061
John McCallb50451a2011-10-05 07:41:44 +00004062/// CheckCastTypes - Check type constraints for casting between types in C.
4063ExprResult Sema::CheckCCastTypes(SourceLocation CastStartLoc,
4064 SourceRange TypeRange, QualType CastType,
4065 Expr *CastExpr, CastKind &Kind) {
4066 assert(!getLangOptions().CPlusPlus);
4067
4068 if (CastExpr->getType() == Context.UnknownAnyTy) {
4069 // We can safely ignore these here because C never has base paths
4070 // or casts to l-values.
4071 CXXCastPath BasePath;
4072 ExprValueKind VK = VK_RValue;
Richard Trieuba63ce62011-09-09 01:45:06 +00004073 return checkUnknownAnyCast(TypeRange, CastType, CastExpr, Kind, VK,
4074 BasePath);
John McCallb50451a2011-10-05 07:41:44 +00004075 }
John McCall31996342011-04-07 08:22:57 +00004076
John McCallb50451a2011-10-05 07:41:44 +00004077 ExprResult Result = CheckPlaceholderExpr(CastExpr);
4078 if (Result.isInvalid())
4079 return ExprError();
4080 CastExpr = Result.take();
Sebastian Redl9f831db2009-07-25 15:41:38 +00004081
Richard Trieuba63ce62011-09-09 01:45:06 +00004082 assert(!CastExpr->getType()->isPlaceholderType());
John McCall3aef3d82011-04-10 19:13:55 +00004083
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004084 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4085 // type needs to be scalar.
Richard Trieuba63ce62011-09-09 01:45:06 +00004086 if (CastType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00004087 // We don't necessarily do lvalue-to-rvalue conversions on this.
Richard Trieuba63ce62011-09-09 01:45:06 +00004088 ExprResult castExprRes = IgnoredValueConversions(CastExpr);
John Wiegley01296292011-04-08 18:41:53 +00004089 if (castExprRes.isInvalid())
4090 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004091 CastExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00004092
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004093 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00004094 Kind = CK_ToVoid;
Richard Trieuba63ce62011-09-09 01:45:06 +00004095 return Owned(CastExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00004096 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004097
Richard Trieuba63ce62011-09-09 01:45:06 +00004098 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(CastExpr);
John Wiegley01296292011-04-08 18:41:53 +00004099 if (castExprRes.isInvalid())
4100 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004101 CastExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00004102
Richard Trieuba63ce62011-09-09 01:45:06 +00004103 if (RequireCompleteType(TypeRange.getBegin(), CastType,
Eli Friedmane98194d2010-07-17 20:43:49 +00004104 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00004105 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00004106
Richard Trieuba63ce62011-09-09 01:45:06 +00004107 if (!CastType->isScalarType() && !CastType->isVectorType()) {
4108 if (Context.hasSameUnqualifiedType(CastType, CastExpr->getType()) &&
4109 (CastType->isStructureType() || CastType->isUnionType())) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004110 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00004111 // FIXME: Check that the cast destination type is complete.
Richard Trieuba63ce62011-09-09 01:45:06 +00004112 Diag(TypeRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
4113 << CastType << CastExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004114 Kind = CK_NoOp;
Richard Trieuba63ce62011-09-09 01:45:06 +00004115 return Owned(CastExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00004116 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004117
Richard Trieuba63ce62011-09-09 01:45:06 +00004118 if (CastType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004119 // GCC cast to union extension
Richard Trieuba63ce62011-09-09 01:45:06 +00004120 RecordDecl *RD = CastType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004121 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004122 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004123 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004124 if (Context.hasSameUnqualifiedType(Field->getType(),
Richard Trieuba63ce62011-09-09 01:45:06 +00004125 CastExpr->getType()) &&
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00004126 !Field->isUnnamedBitfield()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004127 Diag(TypeRange.getBegin(), diag::ext_typecheck_cast_to_union)
4128 << CastExpr->getSourceRange();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004129 break;
4130 }
4131 }
John Wiegley01296292011-04-08 18:41:53 +00004132 if (Field == FieldEnd) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004133 Diag(TypeRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
4134 << CastExpr->getType() << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004135 return ExprError();
4136 }
John McCalle3027922010-08-25 11:45:40 +00004137 Kind = CK_ToUnion;
Richard Trieuba63ce62011-09-09 01:45:06 +00004138 return Owned(CastExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004139 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004140
Anders Carlsson525b76b2009-10-16 02:48:28 +00004141 // Reject any other conversions to non-scalar types.
Richard Trieuba63ce62011-09-09 01:45:06 +00004142 Diag(TypeRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
4143 << CastType << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004144 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004145 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004146
John McCalld7646252010-11-14 08:17:51 +00004147 // The type we're casting to is known to be a scalar or vector.
4148
4149 // Require the operand to be a scalar or vector.
Richard Trieuba63ce62011-09-09 01:45:06 +00004150 if (!CastExpr->getType()->isScalarType() &&
4151 !CastExpr->getType()->isVectorType()) {
4152 Diag(CastExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004153 diag::err_typecheck_expect_scalar_operand)
Richard Trieuba63ce62011-09-09 01:45:06 +00004154 << CastExpr->getType() << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004155 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004156 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004157
Richard Trieuba63ce62011-09-09 01:45:06 +00004158 if (CastType->isExtVectorType())
4159 return CheckExtVectorCast(TypeRange, CastType, CastExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004160
Richard Trieuba63ce62011-09-09 01:45:06 +00004161 if (CastType->isVectorType()) {
4162 if (CastType->getAs<VectorType>()->getVectorKind() ==
Anton Yartsev28ccef72011-03-27 09:32:40 +00004163 VectorType::AltiVecVector &&
Richard Trieuba63ce62011-09-09 01:45:06 +00004164 (CastExpr->getType()->isIntegerType() ||
4165 CastExpr->getType()->isFloatingType())) {
Anton Yartsev28ccef72011-03-27 09:32:40 +00004166 Kind = CK_VectorSplat;
Richard Trieuba63ce62011-09-09 01:45:06 +00004167 return Owned(CastExpr);
4168 } else if (CheckVectorCast(TypeRange, CastType, CastExpr->getType(),
4169 Kind)) {
John Wiegley01296292011-04-08 18:41:53 +00004170 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00004171 } else
Richard Trieuba63ce62011-09-09 01:45:06 +00004172 return Owned(CastExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00004173 }
Richard Trieuba63ce62011-09-09 01:45:06 +00004174 if (CastExpr->getType()->isVectorType()) {
4175 if (CheckVectorCast(TypeRange, CastExpr->getType(), CastType, Kind))
John Wiegley01296292011-04-08 18:41:53 +00004176 return ExprError();
4177 else
Richard Trieuba63ce62011-09-09 01:45:06 +00004178 return Owned(CastExpr);
John Wiegley01296292011-04-08 18:41:53 +00004179 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00004180
John McCalld7646252010-11-14 08:17:51 +00004181 // The source and target types are both scalars, i.e.
4182 // - arithmetic types (fundamental, enum, and complex)
4183 // - all kinds of pointers
4184 // Note that member pointers were filtered out with C++, above.
4185
Richard Trieuba63ce62011-09-09 01:45:06 +00004186 if (isa<ObjCSelectorExpr>(CastExpr)) {
4187 Diag(CastExpr->getLocStart(), diag::err_cast_selector_expr);
John Wiegley01296292011-04-08 18:41:53 +00004188 return ExprError();
4189 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004190
John McCalld7646252010-11-14 08:17:51 +00004191 // If either type is a pointer, the other type has to be either an
4192 // integer or a pointer.
Richard Trieuba63ce62011-09-09 01:45:06 +00004193 QualType CastExprType = CastExpr->getType();
4194 if (!CastType->isArithmeticType()) {
4195 if (!CastExprType->isIntegralType(Context) &&
4196 CastExprType->isArithmeticType()) {
4197 Diag(CastExpr->getLocStart(),
John Wiegley01296292011-04-08 18:41:53 +00004198 diag::err_cast_pointer_from_non_pointer_int)
Richard Trieuba63ce62011-09-09 01:45:06 +00004199 << CastExprType << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004200 return ExprError();
4201 }
Richard Trieuba63ce62011-09-09 01:45:06 +00004202 } else if (!CastExpr->getType()->isArithmeticType()) {
4203 if (!CastType->isIntegralType(Context) && CastType->isArithmeticType()) {
4204 Diag(CastExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
4205 << CastType << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004206 return ExprError();
4207 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004208 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004209
John McCallb50451a2011-10-05 07:41:44 +00004210 // ARC imposes extra restrictions on casts.
John McCall31168b02011-06-15 23:02:42 +00004211 if (getLangOptions().ObjCAutoRefCount) {
John McCallb50451a2011-10-05 07:41:44 +00004212 CheckObjCARCConversion(SourceRange(CastStartLoc, CastExpr->getLocEnd()),
Richard Trieuba63ce62011-09-09 01:45:06 +00004213 CastType, CastExpr, CCK_CStyleCast);
John McCall31168b02011-06-15 23:02:42 +00004214
Richard Trieuba63ce62011-09-09 01:45:06 +00004215 if (const PointerType *CastPtr = CastType->getAs<PointerType>()) {
4216 if (const PointerType *ExprPtr = CastExprType->getAs<PointerType>()) {
John McCall31168b02011-06-15 23:02:42 +00004217 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4218 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4219 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4220 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4221 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004222 Diag(CastExpr->getLocStart(),
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004223 diag::err_typecheck_incompatible_ownership)
Richard Trieuba63ce62011-09-09 01:45:06 +00004224 << CastExprType << CastType << AA_Casting
4225 << CastExpr->getSourceRange();
John McCall31168b02011-06-15 23:02:42 +00004226
4227 return ExprError();
4228 }
4229 }
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004230 }
Richard Trieuba63ce62011-09-09 01:45:06 +00004231 else if (!CheckObjCARCUnavailableWeakConversion(CastType, CastExprType)) {
4232 Diag(CastExpr->getLocStart(),
Fariborz Jahanianf2913402011-07-08 17:41:42 +00004233 diag::err_arc_convesion_of_weak_unavailable) << 1
Richard Trieuba63ce62011-09-09 01:45:06 +00004234 << CastExprType << CastType
4235 << CastExpr->getSourceRange();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004236 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00004237 }
4238 }
4239
Richard Trieuba63ce62011-09-09 01:45:06 +00004240 castExprRes = Owned(CastExpr);
4241 Kind = PrepareScalarCast(*this, castExprRes, CastType);
John Wiegley01296292011-04-08 18:41:53 +00004242 if (castExprRes.isInvalid())
4243 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004244 CastExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00004245
John McCalld7646252010-11-14 08:17:51 +00004246 if (Kind == CK_BitCast)
Richard Trieuba63ce62011-09-09 01:45:06 +00004247 CheckCastAlign(CastExpr, CastType, TypeRange);
John McCall2b5c1b22010-08-12 21:44:57 +00004248
Richard Trieuba63ce62011-09-09 01:45:06 +00004249 return Owned(CastExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004250}
4251
Anders Carlsson525b76b2009-10-16 02:48:28 +00004252bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004253 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004254 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004255
Anders Carlssonde71adf2007-11-27 05:51:55 +00004256 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004257 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004258 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004259 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004260 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004261 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004262 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004263 } else
4264 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004265 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004266 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004267
John McCalle3027922010-08-25 11:45:40 +00004268 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004269 return false;
4270}
4271
John Wiegley01296292011-04-08 18:41:53 +00004272ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4273 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004274 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004275
Anders Carlsson43d70f82009-10-16 05:23:41 +00004276 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004277
Nate Begemanc8961a42009-06-27 22:05:55 +00004278 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4279 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00004280 // In OpenCL, casts between vectors of different types are not allowed.
4281 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00004282 if (SrcTy->isVectorType()) {
Tobias Grosser766bcc22011-09-22 13:03:14 +00004283 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4284 || (getLangOptions().OpenCL &&
4285 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004286 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004287 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004288 return ExprError();
4289 }
John McCalle3027922010-08-25 11:45:40 +00004290 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004291 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004292 }
4293
Nate Begemanbd956c42009-06-28 02:36:38 +00004294 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004295 // conversion will take place first from scalar to elt type, and then
4296 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004297 if (SrcTy->isPointerType())
4298 return Diag(R.getBegin(),
4299 diag::err_invalid_conversion_between_vector_and_scalar)
4300 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004301
4302 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004303 ExprResult CastExprRes = Owned(CastExpr);
4304 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4305 if (CastExprRes.isInvalid())
4306 return ExprError();
4307 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004308
John McCalle3027922010-08-25 11:45:40 +00004309 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004310 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004311}
4312
John McCalldadc5752010-08-24 06:29:42 +00004313ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004314Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4315 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004316 SourceLocation RParenLoc, Expr *CastExpr) {
4317 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004318 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004319
Richard Trieuba63ce62011-09-09 01:45:06 +00004320 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004321 if (D.isInvalidType())
4322 return ExprError();
4323
4324 if (getLangOptions().CPlusPlus) {
4325 // Check that there are no default arguments (C++ only).
4326 CheckExtraCXXDefaultArguments(D);
4327 }
4328
John McCall42856de2011-10-01 05:17:03 +00004329 checkUnusedDeclAttributes(D);
4330
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004331 QualType castType = castTInfo->getType();
4332 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004333
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004334 bool isVectorLiteral = false;
4335
4336 // Check for an altivec or OpenCL literal,
4337 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00004338 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4339 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00004340 if ((getLangOptions().AltiVec || getLangOptions().OpenCL)
4341 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004342 if (PLE && PLE->getNumExprs() == 0) {
4343 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4344 return ExprError();
4345 }
4346 if (PE || PLE->getNumExprs() == 1) {
4347 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4348 if (!E->getType()->isVectorType())
4349 isVectorLiteral = true;
4350 }
4351 else
4352 isVectorLiteral = true;
4353 }
4354
4355 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4356 // then handle it as such.
4357 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00004358 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004359
Nate Begeman5ec4b312009-08-10 23:49:36 +00004360 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004361 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4362 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00004363 if (isa<ParenListExpr>(CastExpr)) {
4364 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004365 if (Result.isInvalid()) return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004366 CastExpr = Result.take();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004367 }
John McCallebe54742010-01-15 18:56:44 +00004368
Richard Trieuba63ce62011-09-09 01:45:06 +00004369 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00004370}
4371
John McCalldadc5752010-08-24 06:29:42 +00004372ExprResult
John McCallebe54742010-01-15 18:56:44 +00004373Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004374 SourceLocation RParenLoc, Expr *CastExpr) {
John McCallb50451a2011-10-05 07:41:44 +00004375 if (getLangOptions().CPlusPlus)
4376 return CXXBuildCStyleCastExpr(LParenLoc, Ty, RParenLoc, CastExpr);
4377
John McCall8cb679e2010-11-15 09:13:47 +00004378 CastKind Kind = CK_Invalid;
John Wiegley01296292011-04-08 18:41:53 +00004379 ExprResult CastResult =
John McCallb50451a2011-10-05 07:41:44 +00004380 CheckCCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc),
4381 Ty->getType(), CastExpr, Kind);
John Wiegley01296292011-04-08 18:41:53 +00004382 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004383 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004384 CastExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00004385
John McCallb50451a2011-10-05 07:41:44 +00004386 return Owned(CStyleCastExpr::Create(Context, Ty->getType(), VK_RValue, Kind,
4387 CastExpr, /*base path*/ 0, Ty,
4388 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004389}
4390
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004391ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4392 SourceLocation RParenLoc, Expr *E,
4393 TypeSourceInfo *TInfo) {
4394 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4395 "Expected paren or paren list expression");
4396
4397 Expr **exprs;
4398 unsigned numExprs;
4399 Expr *subExpr;
4400 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4401 exprs = PE->getExprs();
4402 numExprs = PE->getNumExprs();
4403 } else {
4404 subExpr = cast<ParenExpr>(E)->getSubExpr();
4405 exprs = &subExpr;
4406 numExprs = 1;
4407 }
4408
4409 QualType Ty = TInfo->getType();
4410 assert(Ty->isVectorType() && "Expected vector type");
4411
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004412 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004413 const VectorType *VTy = Ty->getAs<VectorType>();
4414 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4415
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004416 // '(...)' form of vector initialization in AltiVec: the number of
4417 // initializers must be one or must match the size of the vector.
4418 // If a single value is specified in the initializer then it will be
4419 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004420 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004421 // The number of initializers must be one or must match the size of the
4422 // vector. If a single value is specified in the initializer then it will
4423 // be replicated to all the components of the vector
4424 if (numExprs == 1) {
4425 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4426 ExprResult Literal = Owned(exprs[0]);
4427 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4428 PrepareScalarCast(*this, Literal, ElemTy));
4429 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4430 }
4431 else if (numExprs < numElems) {
4432 Diag(E->getExprLoc(),
4433 diag::err_incorrect_number_of_vector_initializers);
4434 return ExprError();
4435 }
4436 else
4437 for (unsigned i = 0, e = numExprs; i != e; ++i)
4438 initExprs.push_back(exprs[i]);
4439 }
Tanya Lattner83559382011-07-15 23:07:01 +00004440 else {
4441 // For OpenCL, when the number of initializers is a single value,
4442 // it will be replicated to all components of the vector.
4443 if (getLangOptions().OpenCL &&
4444 VTy->getVectorKind() == VectorType::GenericVector &&
4445 numExprs == 1) {
4446 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4447 ExprResult Literal = Owned(exprs[0]);
4448 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4449 PrepareScalarCast(*this, Literal, ElemTy));
4450 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4451 }
4452
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004453 for (unsigned i = 0, e = numExprs; i != e; ++i)
4454 initExprs.push_back(exprs[i]);
Tanya Lattner83559382011-07-15 23:07:01 +00004455 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004456 // FIXME: This means that pretty-printing the final AST will produce curly
4457 // braces instead of the original commas.
4458 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4459 &initExprs[0],
4460 initExprs.size(), RParenLoc);
4461 initE->setType(Ty);
4462 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4463}
4464
Nate Begeman5ec4b312009-08-10 23:49:36 +00004465/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4466/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004467ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004468Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4469 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004470 if (!E)
Richard Trieuba63ce62011-09-09 01:45:06 +00004471 return Owned(OrigExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004472
John McCalldadc5752010-08-24 06:29:42 +00004473 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004474
Nate Begeman5ec4b312009-08-10 23:49:36 +00004475 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004476 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4477 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004478
John McCallb268a282010-08-23 23:25:46 +00004479 if (Result.isInvalid()) return ExprError();
4480
4481 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004482}
4483
John McCalldadc5752010-08-24 06:29:42 +00004484ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Richard Trieuba63ce62011-09-09 01:45:06 +00004485 SourceLocation R,
4486 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004487 unsigned nexprs = Val.size();
4488 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004489 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4490 Expr *expr;
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004491 if (nexprs == 1)
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004492 expr = new (Context) ParenExpr(L, R, exprs[0]);
4493 else
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004494 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4495 exprs[nexprs-1]->getType());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004496 return Owned(expr);
4497}
4498
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004499/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004500/// constant and the other is not a pointer. Returns true if a diagnostic is
4501/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00004502bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004503 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004504 Expr *NullExpr = LHSExpr;
4505 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004506 Expr::NullPointerConstantKind NullKind =
4507 NullExpr->isNullPointerConstant(Context,
4508 Expr::NPC_ValueDependentIsNotNull);
4509
4510 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004511 NullExpr = RHSExpr;
4512 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004513 NullKind =
4514 NullExpr->isNullPointerConstant(Context,
4515 Expr::NPC_ValueDependentIsNotNull);
4516 }
4517
4518 if (NullKind == Expr::NPCK_NotNull)
4519 return false;
4520
4521 if (NullKind == Expr::NPCK_ZeroInteger) {
4522 // In this case, check to make sure that we got here from a "NULL"
4523 // string in the source code.
4524 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004525 SourceLocation loc = NullExpr->getExprLoc();
4526 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004527 return false;
4528 }
4529
4530 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4531 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4532 << NonPointerExpr->getType() << DiagType
4533 << NonPointerExpr->getSourceRange();
4534 return true;
4535}
4536
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004537/// \brief Return false if the condition expression is valid, true otherwise.
4538static bool checkCondition(Sema &S, Expr *Cond) {
4539 QualType CondTy = Cond->getType();
4540
4541 // C99 6.5.15p2
4542 if (CondTy->isScalarType()) return false;
4543
4544 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4545 if (S.getLangOptions().OpenCL && CondTy->isVectorType())
4546 return false;
4547
4548 // Emit the proper error message.
4549 S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ?
4550 diag::err_typecheck_cond_expect_scalar :
4551 diag::err_typecheck_cond_expect_scalar_or_vector)
4552 << CondTy;
4553 return true;
4554}
4555
4556/// \brief Return false if the two expressions can be converted to a vector,
4557/// true otherwise
4558static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4559 ExprResult &RHS,
4560 QualType CondTy) {
4561 // Both operands should be of scalar type.
4562 if (!LHS.get()->getType()->isScalarType()) {
4563 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4564 << CondTy;
4565 return true;
4566 }
4567 if (!RHS.get()->getType()->isScalarType()) {
4568 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4569 << CondTy;
4570 return true;
4571 }
4572
4573 // Implicity convert these scalars to the type of the condition.
4574 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4575 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4576 return false;
4577}
4578
4579/// \brief Handle when one or both operands are void type.
4580static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4581 ExprResult &RHS) {
4582 Expr *LHSExpr = LHS.get();
4583 Expr *RHSExpr = RHS.get();
4584
4585 if (!LHSExpr->getType()->isVoidType())
4586 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4587 << RHSExpr->getSourceRange();
4588 if (!RHSExpr->getType()->isVoidType())
4589 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4590 << LHSExpr->getSourceRange();
4591 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4592 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4593 return S.Context.VoidTy;
4594}
4595
4596/// \brief Return false if the NullExpr can be promoted to PointerTy,
4597/// true otherwise.
4598static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4599 QualType PointerTy) {
4600 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4601 !NullExpr.get()->isNullPointerConstant(S.Context,
4602 Expr::NPC_ValueDependentIsNull))
4603 return true;
4604
4605 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4606 return false;
4607}
4608
4609/// \brief Checks compatibility between two pointers and return the resulting
4610/// type.
4611static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4612 ExprResult &RHS,
4613 SourceLocation Loc) {
4614 QualType LHSTy = LHS.get()->getType();
4615 QualType RHSTy = RHS.get()->getType();
4616
4617 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4618 // Two identical pointers types are always compatible.
4619 return LHSTy;
4620 }
4621
4622 QualType lhptee, rhptee;
4623
4624 // Get the pointee types.
John McCall9320b872011-09-09 05:25:32 +00004625 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4626 lhptee = LHSBTy->getPointeeType();
4627 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004628 } else {
John McCall9320b872011-09-09 05:25:32 +00004629 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4630 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004631 }
4632
4633 if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4634 rhptee.getUnqualifiedType())) {
4635 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4636 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4637 << RHS.get()->getSourceRange();
4638 // In this situation, we assume void* type. No especially good
4639 // reason, but this is what gcc does, and we do have to pick
4640 // to get a consistent AST.
4641 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4642 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4643 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4644 return incompatTy;
4645 }
4646
4647 // The pointer types are compatible.
4648 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4649 // differently qualified versions of compatible types, the result type is
4650 // a pointer to an appropriately qualified version of the *composite*
4651 // type.
4652 // FIXME: Need to calculate the composite type.
4653 // FIXME: Need to add qualifiers
4654
4655 LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4656 RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4657 return LHSTy;
4658}
4659
4660/// \brief Return the resulting type when the operands are both block pointers.
4661static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4662 ExprResult &LHS,
4663 ExprResult &RHS,
4664 SourceLocation Loc) {
4665 QualType LHSTy = LHS.get()->getType();
4666 QualType RHSTy = RHS.get()->getType();
4667
4668 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4669 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4670 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4671 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4672 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4673 return destType;
4674 }
4675 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4676 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4677 << RHS.get()->getSourceRange();
4678 return QualType();
4679 }
4680
4681 // We have 2 block pointer types.
4682 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4683}
4684
4685/// \brief Return the resulting type when the operands are both pointers.
4686static QualType
4687checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4688 ExprResult &RHS,
4689 SourceLocation Loc) {
4690 // get the pointer types
4691 QualType LHSTy = LHS.get()->getType();
4692 QualType RHSTy = RHS.get()->getType();
4693
4694 // get the "pointed to" types
4695 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4696 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4697
4698 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4699 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4700 // Figure out necessary qualifiers (C99 6.5.15p6)
4701 QualType destPointee
4702 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4703 QualType destType = S.Context.getPointerType(destPointee);
4704 // Add qualifiers if necessary.
4705 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4706 // Promote to void*.
4707 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4708 return destType;
4709 }
4710 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4711 QualType destPointee
4712 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4713 QualType destType = S.Context.getPointerType(destPointee);
4714 // Add qualifiers if necessary.
4715 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4716 // Promote to void*.
4717 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4718 return destType;
4719 }
4720
4721 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4722}
4723
4724/// \brief Return false if the first expression is not an integer and the second
4725/// expression is not a pointer, true otherwise.
4726static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4727 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004728 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004729 if (!PointerExpr->getType()->isPointerType() ||
4730 !Int.get()->getType()->isIntegerType())
4731 return false;
4732
Richard Trieuba63ce62011-09-09 01:45:06 +00004733 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4734 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004735
4736 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4737 << Expr1->getType() << Expr2->getType()
4738 << Expr1->getSourceRange() << Expr2->getSourceRange();
4739 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4740 CK_IntegralToPointer);
4741 return true;
4742}
4743
Richard Trieud33e46e2011-09-06 20:06:39 +00004744/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4745/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004746/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004747QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4748 ExprResult &RHS, ExprValueKind &VK,
4749 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004750 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004751
Richard Trieud33e46e2011-09-06 20:06:39 +00004752 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4753 if (!LHSResult.isUsable()) return QualType();
4754 LHS = move(LHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004755
Richard Trieud33e46e2011-09-06 20:06:39 +00004756 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4757 if (!RHSResult.isUsable()) return QualType();
4758 RHS = move(RHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004759
Sebastian Redl1a99f442009-04-16 17:51:27 +00004760 // C++ is sufficiently different to merit its own checker.
4761 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004762 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004763
4764 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004765 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004766
John Wiegley01296292011-04-08 18:41:53 +00004767 Cond = UsualUnaryConversions(Cond.take());
4768 if (Cond.isInvalid())
4769 return QualType();
4770 LHS = UsualUnaryConversions(LHS.take());
4771 if (LHS.isInvalid())
4772 return QualType();
4773 RHS = UsualUnaryConversions(RHS.take());
4774 if (RHS.isInvalid())
4775 return QualType();
4776
4777 QualType CondTy = Cond.get()->getType();
4778 QualType LHSTy = LHS.get()->getType();
4779 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004780
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004781 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004782 if (checkCondition(*this, Cond.get()))
4783 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004784
Chris Lattnere2949f42008-01-06 22:42:25 +00004785 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004786 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004787 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004788
Nate Begemanabb5a732010-09-20 22:41:17 +00004789 // OpenCL: If the condition is a vector, and both operands are scalar,
4790 // attempt to implicity convert them to the vector type to act like the
4791 // built in select.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004792 if (getLangOptions().OpenCL && CondTy->isVectorType())
4793 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00004794 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00004795
Chris Lattnere2949f42008-01-06 22:42:25 +00004796 // If both operands have arithmetic type, do the usual arithmetic conversions
4797 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004798 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4799 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004800 if (LHS.isInvalid() || RHS.isInvalid())
4801 return QualType();
4802 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004803 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004804
Chris Lattnere2949f42008-01-06 22:42:25 +00004805 // If both operands are the same structure or union type, the result is that
4806 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004807 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4808 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004809 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004810 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004811 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004812 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004813 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004814 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004815
Chris Lattnere2949f42008-01-06 22:42:25 +00004816 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004817 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004818 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004819 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00004820 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004821
Steve Naroff039ad3c2008-01-08 01:11:38 +00004822 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4823 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004824 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4825 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004826
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004827 // All objective-c pointer type analysis is done here.
4828 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4829 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004830 if (LHS.isInvalid() || RHS.isInvalid())
4831 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004832 if (!compositeType.isNull())
4833 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004834
4835
Steve Naroff05efa972009-07-01 14:36:47 +00004836 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004837 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4838 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4839 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004840
Steve Naroff05efa972009-07-01 14:36:47 +00004841 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004842 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4843 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4844 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004845
John McCalle84af4e2010-11-13 01:35:44 +00004846 // GCC compatibility: soften pointer/integer mismatch. Note that
4847 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004848 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4849 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00004850 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004851 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4852 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00004853 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00004854
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004855 // Emit a better diagnostic if one of the expressions is a null pointer
4856 // constant and the other is not a pointer type. In this case, the user most
4857 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004858 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004859 return QualType();
4860
Chris Lattnere2949f42008-01-06 22:42:25 +00004861 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004862 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004863 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4864 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004865 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004866}
4867
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004868/// FindCompositeObjCPointerType - Helper method to find composite type of
4869/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004870QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00004871 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004872 QualType LHSTy = LHS.get()->getType();
4873 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004874
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004875 // Handle things like Class and struct objc_class*. Here we case the result
4876 // to the pseudo-builtin, because that will be implicitly cast back to the
4877 // redefinition type if an attempt is made to access its fields.
4878 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004879 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004880 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004881 return LHSTy;
4882 }
4883 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004884 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004885 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004886 return RHSTy;
4887 }
4888 // And the same for struct objc_object* / id
4889 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004890 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004891 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004892 return LHSTy;
4893 }
4894 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004895 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004896 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004897 return RHSTy;
4898 }
4899 // And the same for struct objc_selector* / SEL
4900 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004901 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004902 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004903 return LHSTy;
4904 }
4905 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004906 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004907 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004908 return RHSTy;
4909 }
4910 // Check constraints for Objective-C object pointers types.
4911 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004912
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004913 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4914 // Two identical object pointer types are always compatible.
4915 return LHSTy;
4916 }
John McCall9320b872011-09-09 05:25:32 +00004917 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
4918 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004919 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004920
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004921 // If both operands are interfaces and either operand can be
4922 // assigned to the other, use that type as the composite
4923 // type. This allows
4924 // xxx ? (A*) a : (B*) b
4925 // where B is a subclass of A.
4926 //
4927 // Additionally, as for assignment, if either type is 'id'
4928 // allow silent coercion. Finally, if the types are
4929 // incompatible then make sure to use 'id' as the composite
4930 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004931
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004932 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4933 // It could return the composite type.
4934 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4935 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4936 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4937 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4938 } else if ((LHSTy->isObjCQualifiedIdType() ||
4939 RHSTy->isObjCQualifiedIdType()) &&
4940 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4941 // Need to handle "id<xx>" explicitly.
4942 // GCC allows qualified id and any Objective-C type to devolve to
4943 // id. Currently localizing to here until clear this should be
4944 // part of ObjCQualifiedIdTypesAreCompatible.
4945 compositeType = Context.getObjCIdType();
4946 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4947 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004948 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004949 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4950 ;
4951 else {
4952 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4953 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004954 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004955 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004956 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4957 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004958 return incompatTy;
4959 }
4960 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004961 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4962 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004963 return compositeType;
4964 }
4965 // Check Objective-C object pointer types and 'void *'
4966 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4967 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4968 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4969 QualType destPointee
4970 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4971 QualType destType = Context.getPointerType(destPointee);
4972 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004973 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004974 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004975 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004976 return destType;
4977 }
4978 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4979 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4980 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4981 QualType destPointee
4982 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4983 QualType destType = Context.getPointerType(destPointee);
4984 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004985 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004986 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004987 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004988 return destType;
4989 }
4990 return QualType();
4991}
4992
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004993/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004994/// ParenRange in parentheses.
4995static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004996 const PartialDiagnostic &Note,
4997 SourceRange ParenRange) {
4998 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4999 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5000 EndLoc.isValid()) {
5001 Self.Diag(Loc, Note)
5002 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5003 << FixItHint::CreateInsertion(EndLoc, ")");
5004 } else {
5005 // We can't display the parentheses, so just show the bare note.
5006 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005007 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005008}
5009
5010static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5011 return Opc >= BO_Mul && Opc <= BO_Shr;
5012}
5013
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005014/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5015/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00005016/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5017/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005018static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00005019 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00005020 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5021 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005022 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00005023 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005024
5025 // Built-in binary operator.
5026 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5027 if (IsArithmeticOp(OP->getOpcode())) {
5028 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00005029 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005030 return true;
5031 }
5032 }
5033
5034 // Overloaded operator.
5035 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5036 if (Call->getNumArgs() != 2)
5037 return false;
5038
5039 // Make sure this is really a binary operator that is safe to pass into
5040 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5041 OverloadedOperatorKind OO = Call->getOperator();
5042 if (OO < OO_Plus || OO > OO_Arrow)
5043 return false;
5044
5045 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5046 if (IsArithmeticOp(OpKind)) {
5047 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00005048 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005049 return true;
5050 }
5051 }
5052
5053 return false;
5054}
5055
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005056static bool IsLogicOp(BinaryOperatorKind Opc) {
5057 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5058}
5059
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005060/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5061/// or is a logical expression such as (x==y) which has int type, but is
5062/// commonly interpreted as boolean.
5063static bool ExprLooksBoolean(Expr *E) {
5064 E = E->IgnoreParenImpCasts();
5065
5066 if (E->getType()->isBooleanType())
5067 return true;
5068 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5069 return IsLogicOp(OP->getOpcode());
5070 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5071 return OP->getOpcode() == UO_LNot;
5072
5073 return false;
5074}
5075
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005076/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5077/// and binary operator are mixed in a way that suggests the programmer assumed
5078/// the conditional operator has higher precedence, for example:
5079/// "int x = a + someBinaryCondition ? 1 : 2".
5080static void DiagnoseConditionalPrecedence(Sema &Self,
5081 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005082 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00005083 Expr *LHSExpr,
5084 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005085 BinaryOperatorKind CondOpcode;
5086 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005087
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005088 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005089 return;
5090 if (!ExprLooksBoolean(CondRHS))
5091 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005092
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005093 // The condition is an arithmetic binary expression, with a right-
5094 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005095
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005096 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005097 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005098 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005099
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005100 SuggestParentheses(Self, OpLoc,
5101 Self.PDiag(diag::note_precedence_conditional_silence)
5102 << BinaryOperator::getOpcodeStr(CondOpcode),
5103 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00005104
5105 SuggestParentheses(Self, OpLoc,
5106 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00005107 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005108}
5109
Steve Naroff83895f72007-09-16 03:34:24 +00005110/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005111/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005112ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005113 SourceLocation ColonLoc,
5114 Expr *CondExpr, Expr *LHSExpr,
5115 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005116 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5117 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005118 OpaqueValueExpr *opaqueValue = 0;
5119 Expr *commonExpr = 0;
5120 if (LHSExpr == 0) {
5121 commonExpr = CondExpr;
5122
5123 // We usually want to apply unary conversions *before* saving, except
5124 // in the special case of a C++ l-value conditional.
5125 if (!(getLangOptions().CPlusPlus
5126 && !commonExpr->isTypeDependent()
5127 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5128 && commonExpr->isGLValue()
5129 && commonExpr->isOrdinaryOrBitFieldObject()
5130 && RHSExpr->isOrdinaryOrBitFieldObject()
5131 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005132 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5133 if (commonRes.isInvalid())
5134 return ExprError();
5135 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005136 }
5137
5138 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5139 commonExpr->getType(),
5140 commonExpr->getValueKind(),
5141 commonExpr->getObjectKind());
5142 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005143 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005144
John McCall7decc9e2010-11-18 06:31:45 +00005145 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005146 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005147 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5148 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005149 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005150 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5151 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005152 return ExprError();
5153
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005154 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5155 RHS.get());
5156
John McCallc07a0c72011-02-17 10:25:35 +00005157 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005158 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5159 LHS.take(), ColonLoc,
5160 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005161
5162 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005163 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005164 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5165 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005166}
5167
John McCallaba90822011-01-31 23:13:11 +00005168// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005169// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005170// routine is it effectively iqnores the qualifiers on the top level pointee.
5171// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5172// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005173static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005174checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5175 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5176 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005177
Steve Naroff1f4d7272007-05-11 04:00:31 +00005178 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005179 const Type *lhptee, *rhptee;
5180 Qualifiers lhq, rhq;
Richard Trieua871b972011-09-06 20:21:22 +00005181 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5182 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005183
John McCallaba90822011-01-31 23:13:11 +00005184 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005185
5186 // C99 6.5.16.1p1: This following citation is common to constraints
5187 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5188 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005189 Qualifiers lq;
5190
John McCall31168b02011-06-15 23:02:42 +00005191 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5192 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5193 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5194 // Ignore lifetime for further calculation.
5195 lhq.removeObjCLifetime();
5196 rhq.removeObjCLifetime();
5197 }
5198
John McCall4fff8f62011-02-01 00:10:29 +00005199 if (!lhq.compatiblyIncludes(rhq)) {
5200 // Treat address-space mismatches as fatal. TODO: address subspaces
5201 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5202 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5203
John McCall31168b02011-06-15 23:02:42 +00005204 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005205 // and from void*.
John McCall31168b02011-06-15 23:02:42 +00005206 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5207 .compatiblyIncludes(
5208 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall78535952011-03-26 02:56:45 +00005209 && (lhptee->isVoidType() || rhptee->isVoidType()))
5210 ; // keep old
5211
John McCall31168b02011-06-15 23:02:42 +00005212 // Treat lifetime mismatches as fatal.
5213 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5214 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5215
John McCall4fff8f62011-02-01 00:10:29 +00005216 // For GCC compatibility, other qualifier mismatches are treated
5217 // as still compatible in C.
5218 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5219 }
Steve Naroff3f597292007-05-11 22:18:03 +00005220
Mike Stump4e1f26a2009-02-19 03:04:26 +00005221 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5222 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005223 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005224 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005225 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005226 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005227
Chris Lattner0a788432008-01-03 22:56:36 +00005228 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005229 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005230 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005231 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005232
Chris Lattner0a788432008-01-03 22:56:36 +00005233 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005234 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005235 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005236
5237 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005238 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005239 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005240 }
John McCall4fff8f62011-02-01 00:10:29 +00005241
Mike Stump4e1f26a2009-02-19 03:04:26 +00005242 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005243 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005244 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5245 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005246 // Check if the pointee types are compatible ignoring the sign.
5247 // We explicitly check for char so that we catch "char" vs
5248 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005249 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005250 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005251 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005252 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005253
Chris Lattnerec3a1562009-10-17 20:33:28 +00005254 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005255 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005256 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005257 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005258
John McCall4fff8f62011-02-01 00:10:29 +00005259 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005260 // Types are compatible ignoring the sign. Qualifier incompatibility
5261 // takes priority over sign incompatibility because the sign
5262 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005263 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005264 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005265
John McCallaba90822011-01-31 23:13:11 +00005266 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005267 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005268
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005269 // If we are a multi-level pointer, it's possible that our issue is simply
5270 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5271 // the eventual target type is the same and the pointers have the same
5272 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005273 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005274 do {
John McCall4fff8f62011-02-01 00:10:29 +00005275 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5276 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005277 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005278
John McCall4fff8f62011-02-01 00:10:29 +00005279 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005280 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005281 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005282
Eli Friedman80160bd2009-03-22 23:59:44 +00005283 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005284 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005285 }
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005286 if (!S.getLangOptions().CPlusPlus &&
5287 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5288 return Sema::IncompatiblePointer;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005289 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005290}
5291
John McCallaba90822011-01-31 23:13:11 +00005292/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005293/// block pointer types are compatible or whether a block and normal pointer
5294/// are compatible. It is more restrict than comparing two function pointer
5295// types.
John McCallaba90822011-01-31 23:13:11 +00005296static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005297checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5298 QualType RHSType) {
5299 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5300 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005301
Steve Naroff081c7422008-09-04 15:10:53 +00005302 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005303
Steve Naroff081c7422008-09-04 15:10:53 +00005304 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00005305 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5306 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005307
John McCallaba90822011-01-31 23:13:11 +00005308 // In C++, the types have to match exactly.
5309 if (S.getLangOptions().CPlusPlus)
5310 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005311
John McCallaba90822011-01-31 23:13:11 +00005312 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005313
Steve Naroff081c7422008-09-04 15:10:53 +00005314 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005315 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5316 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005317
Richard Trieua871b972011-09-06 20:21:22 +00005318 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005319 return Sema::IncompatibleBlockPointer;
5320
Steve Naroff081c7422008-09-04 15:10:53 +00005321 return ConvTy;
5322}
5323
John McCallaba90822011-01-31 23:13:11 +00005324/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005325/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005326static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005327checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5328 QualType RHSType) {
5329 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5330 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005331
Richard Trieua871b972011-09-06 20:21:22 +00005332 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005333 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005334 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5335 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005336 return Sema::IncompatiblePointer;
5337 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005338 }
Richard Trieua871b972011-09-06 20:21:22 +00005339 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00005340 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5341 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00005342 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00005343 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005344 }
Richard Trieua871b972011-09-06 20:21:22 +00005345 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5346 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005347
John McCallaba90822011-01-31 23:13:11 +00005348 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5349 return Sema::CompatiblePointerDiscardsQualifiers;
5350
Richard Trieua871b972011-09-06 20:21:22 +00005351 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005352 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00005353 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005354 return Sema::IncompatibleObjCQualifiedId;
5355 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005356}
5357
John McCall29600e12010-11-16 02:32:08 +00005358Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005359Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00005360 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00005361 // Fake up an opaque expression. We don't actually care about what
5362 // cast operations are required, so if CheckAssignmentConstraints
5363 // adds casts to this they'll be wasted, but fortunately that doesn't
5364 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00005365 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5366 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00005367 CastKind K = CK_Invalid;
5368
Richard Trieua871b972011-09-06 20:21:22 +00005369 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall29600e12010-11-16 02:32:08 +00005370}
5371
Mike Stump4e1f26a2009-02-19 03:04:26 +00005372/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5373/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005374/// pointers. Here are some objectionable examples that GCC considers warnings:
5375///
5376/// int a, *pint;
5377/// short *pshort;
5378/// struct foo *pfoo;
5379///
5380/// pint = pshort; // warning: assignment from incompatible pointer type
5381/// a = pint; // warning: assignment makes integer from pointer without a cast
5382/// pint = a; // warning: assignment makes pointer from integer without a cast
5383/// pint = pfoo; // warning: assignment from incompatible pointer type
5384///
5385/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005386/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005387///
John McCall8cb679e2010-11-15 09:13:47 +00005388/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005389Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00005390Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCall8cb679e2010-11-15 09:13:47 +00005391 CastKind &Kind) {
Richard Trieude4958f2011-09-06 20:30:53 +00005392 QualType RHSType = RHS.get()->getType();
5393 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00005394
Chris Lattnera52c2f22008-01-04 23:18:45 +00005395 // Get canonical types. We're not formatting these types, just comparing
5396 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00005397 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5398 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005399
Eli Friedman0dfb8892011-10-06 23:00:33 +00005400 // We can't do assignment from/to atomics yet.
5401 if (LHSType->isAtomicType())
5402 return Incompatible;
5403
John McCalle5255932011-01-31 22:28:28 +00005404 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00005405 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00005406 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005407 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005408 }
5409
Douglas Gregor6b754842008-10-28 00:22:11 +00005410 // If the left-hand side is a reference type, then we are in a
5411 // (rare!) case where we've allowed the use of references in C,
5412 // e.g., as a parameter type in a built-in function. In this case,
5413 // just make sure that the type referenced is compatible with the
5414 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00005415 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00005416 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00005417 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5418 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005419 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005420 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005421 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005422 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005423 }
John McCalle5255932011-01-31 22:28:28 +00005424
Nate Begemanbd956c42009-06-28 02:36:38 +00005425 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5426 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005427 if (LHSType->isExtVectorType()) {
5428 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005429 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00005430 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005431 // CK_VectorSplat does T -> vector T, so first cast to the
5432 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00005433 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5434 if (elType != RHSType) {
5435 Kind = PrepareScalarCast(*this, RHS, elType);
5436 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005437 }
5438 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005439 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005440 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005441 }
Mike Stump11289f42009-09-09 15:08:12 +00005442
John McCalle5255932011-01-31 22:28:28 +00005443 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005444 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5445 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005446 // Allow assignments of an AltiVec vector type to an equivalent GCC
5447 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00005448 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00005449 Kind = CK_BitCast;
5450 return Compatible;
5451 }
5452
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005453 // If we are allowing lax vector conversions, and LHS and RHS are both
5454 // vectors, the total size only needs to be the same. This is a bitcast;
5455 // no bits are changed but the result type is different.
5456 if (getLangOptions().LaxVectorConversions &&
Richard Trieude4958f2011-09-06 20:30:53 +00005457 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall3065d042010-11-15 10:08:00 +00005458 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005459 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005460 }
Chris Lattner881a2122008-01-04 23:32:24 +00005461 }
5462 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005463 }
Eli Friedman3360d892008-05-30 18:07:22 +00005464
John McCalle5255932011-01-31 22:28:28 +00005465 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00005466 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5467 !(getLangOptions().CPlusPlus && LHSType->isEnumeralType())) {
5468 Kind = PrepareScalarCast(*this, RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005469 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005470 }
Eli Friedman3360d892008-05-30 18:07:22 +00005471
John McCalle5255932011-01-31 22:28:28 +00005472 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005473 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005474 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005475 if (isa<PointerType>(RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005476 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005477 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005478 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005479
John McCalle5255932011-01-31 22:28:28 +00005480 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005481 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00005482 Kind = CK_IntegralToPointer; // FIXME: null?
5483 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005484 }
John McCalle5255932011-01-31 22:28:28 +00005485
5486 // C pointers are not compatible with ObjC object pointers,
5487 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005488 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005489 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00005490 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00005491 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00005492 return Compatible;
5493 }
5494
5495 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005496 if (RHSType->isObjCClassType() &&
5497 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005498 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005499 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005500 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005501 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00005502
John McCalle5255932011-01-31 22:28:28 +00005503 Kind = CK_BitCast;
5504 return IncompatiblePointer;
5505 }
5506
5507 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00005508 if (RHSType->getAs<BlockPointerType>()) {
5509 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00005510 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005511 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005512 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005513 }
John McCalle5255932011-01-31 22:28:28 +00005514
Steve Naroff081c7422008-09-04 15:10:53 +00005515 return Incompatible;
5516 }
5517
John McCalle5255932011-01-31 22:28:28 +00005518 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005519 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005520 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005521 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00005522 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005523 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00005524 }
5525
5526 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005527 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005528 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005529 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005530 }
5531
John McCalle5255932011-01-31 22:28:28 +00005532 // id -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005533 if (getLangOptions().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00005534 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005535 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005536 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005537
John McCalle5255932011-01-31 22:28:28 +00005538 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005539 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005540 if (RHSPT->getPointeeType()->isVoidType()) {
5541 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005542 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005543 }
John McCall8cb679e2010-11-15 09:13:47 +00005544
Chris Lattnera52c2f22008-01-04 23:18:45 +00005545 return Incompatible;
5546 }
5547
John McCalle5255932011-01-31 22:28:28 +00005548 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005549 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005550 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00005551 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005552 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005553 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00005554 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005555 if (getLangOptions().ObjCAutoRefCount &&
5556 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00005557 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005558 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005559 return result;
John McCalle5255932011-01-31 22:28:28 +00005560 }
5561
5562 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005563 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005564 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005565 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005566 }
5567
John McCalle5255932011-01-31 22:28:28 +00005568 // In general, C pointers are not compatible with ObjC object pointers,
5569 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005570 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00005571 Kind = CK_CPointerToObjCPointerCast;
5572
John McCalle5255932011-01-31 22:28:28 +00005573 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00005574 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005575 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005576 }
5577
5578 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005579 if (LHSType->isObjCClassType() &&
5580 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005581 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005582 return Compatible;
5583 }
5584
Steve Naroffaccc4882009-07-20 17:56:53 +00005585 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005586 }
John McCalle5255932011-01-31 22:28:28 +00005587
5588 // T^ -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005589 if (RHSType->isBlockPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00005590 maybeExtendBlockObject(*this, RHS);
John McCall9320b872011-09-09 05:25:32 +00005591 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005592 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005593 }
5594
Steve Naroff7cae42b2009-07-10 23:34:53 +00005595 return Incompatible;
5596 }
John McCalle5255932011-01-31 22:28:28 +00005597
5598 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005599 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005600 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005601 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005602 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005603 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005604 }
Eli Friedman3360d892008-05-30 18:07:22 +00005605
John McCalle5255932011-01-31 22:28:28 +00005606 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005607 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005608 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005609 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005610 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005611
Chris Lattnera52c2f22008-01-04 23:18:45 +00005612 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005613 }
John McCalle5255932011-01-31 22:28:28 +00005614
5615 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005616 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005617 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005618 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005619 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005620 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005621 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005622
John McCalle5255932011-01-31 22:28:28 +00005623 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005624 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005625 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005626 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005627 }
5628
Steve Naroff7cae42b2009-07-10 23:34:53 +00005629 return Incompatible;
5630 }
Eli Friedman3360d892008-05-30 18:07:22 +00005631
John McCalle5255932011-01-31 22:28:28 +00005632 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00005633 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5634 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005635 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005636 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005637 }
Bill Wendling216423b2007-05-30 06:30:29 +00005638 }
John McCalle5255932011-01-31 22:28:28 +00005639
Steve Naroff98cf3e92007-06-06 18:38:38 +00005640 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005641}
5642
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005643/// \brief Constructs a transparent union from an expression that is
5644/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005645static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5646 ExprResult &EResult, QualType UnionType,
5647 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005648 // Build an initializer list that designates the appropriate member
5649 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005650 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005651 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005652 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005653 SourceLocation());
5654 Initializer->setType(UnionType);
5655 Initializer->setInitializedFieldInUnion(Field);
5656
5657 // Build a compound literal constructing a value of the transparent
5658 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005659 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005660 EResult = S.Owned(
5661 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5662 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005663}
5664
5665Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005666Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00005667 ExprResult &RHS) {
5668 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005669
Mike Stump11289f42009-09-09 15:08:12 +00005670 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005671 // transparent_union GCC extension.
5672 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005673 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005674 return Incompatible;
5675
5676 // The field to initialize within the transparent union.
5677 RecordDecl *UD = UT->getDecl();
5678 FieldDecl *InitField = 0;
5679 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005680 for (RecordDecl::field_iterator it = UD->field_begin(),
5681 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005682 it != itend; ++it) {
5683 if (it->getType()->isPointerType()) {
5684 // If the transparent union contains a pointer type, we allow:
5685 // 1) void pointer
5686 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00005687 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00005688 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieueb299142011-09-06 20:40:12 +00005689 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005690 InitField = *it;
5691 break;
5692 }
Mike Stump11289f42009-09-09 15:08:12 +00005693
Richard Trieueb299142011-09-06 20:40:12 +00005694 if (RHS.get()->isNullPointerConstant(Context,
5695 Expr::NPC_ValueDependentIsNull)) {
5696 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5697 CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005698 InitField = *it;
5699 break;
5700 }
5701 }
5702
John McCall8cb679e2010-11-15 09:13:47 +00005703 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00005704 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005705 == Compatible) {
Richard Trieueb299142011-09-06 20:40:12 +00005706 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005707 InitField = *it;
5708 break;
5709 }
5710 }
5711
5712 if (!InitField)
5713 return Incompatible;
5714
Richard Trieueb299142011-09-06 20:40:12 +00005715 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005716 return Compatible;
5717}
5718
Chris Lattner9bad62c2008-01-04 18:04:52 +00005719Sema::AssignConvertType
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005720Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5721 bool Diagnose) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005722 if (getLangOptions().CPlusPlus) {
Eli Friedman0dfb8892011-10-06 23:00:33 +00005723 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005724 // C++ 5.17p3: If the left operand is not of class type, the
5725 // expression is implicitly converted (C++ 4) to the
5726 // cv-unqualified type of the left operand.
Richard Trieueb299142011-09-06 20:40:12 +00005727 ExprResult Res = PerformImplicitConversion(RHS.get(),
5728 LHSType.getUnqualifiedType(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005729 AA_Assigning, Diagnose);
John Wiegley01296292011-04-08 18:41:53 +00005730 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005731 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005732 Sema::AssignConvertType result = Compatible;
5733 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00005734 !CheckObjCARCUnavailableWeakConversion(LHSType,
5735 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005736 result = IncompatibleObjCWeakRef;
Richard Trieueb299142011-09-06 20:40:12 +00005737 RHS = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005738 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005739 }
5740
5741 // FIXME: Currently, we fall through and treat C++ classes like C
5742 // structures.
Eli Friedman0dfb8892011-10-06 23:00:33 +00005743 // FIXME: We also fall through for atomics; not sure what should
5744 // happen there, though.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005745 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005746
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005747 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5748 // a null pointer constant.
Richard Trieueb299142011-09-06 20:40:12 +00005749 if ((LHSType->isPointerType() ||
5750 LHSType->isObjCObjectPointerType() ||
5751 LHSType->isBlockPointerType())
5752 && RHS.get()->isNullPointerConstant(Context,
5753 Expr::NPC_ValueDependentIsNull)) {
5754 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005755 return Compatible;
5756 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005757
Chris Lattnere6dcd502007-10-16 02:55:40 +00005758 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005759 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005760 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005761 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005762 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005763 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00005764 if (!LHSType->isReferenceType()) {
5765 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5766 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005767 return Incompatible;
5768 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005769
John McCall8cb679e2010-11-15 09:13:47 +00005770 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005771 Sema::AssignConvertType result =
Richard Trieueb299142011-09-06 20:40:12 +00005772 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005773
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005774 // C99 6.5.16.1p2: The value of the right operand is converted to the
5775 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005776 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5777 // so that we can use references in built-in functions even in C.
5778 // The getNonReferenceType() call makes sure that the resulting expression
5779 // does not have reference type.
Richard Trieueb299142011-09-06 20:40:12 +00005780 if (result != Incompatible && RHS.get()->getType() != LHSType)
5781 RHS = ImpCastExprToType(RHS.take(),
5782 LHSType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005783 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005784}
5785
Richard Trieueb299142011-09-06 20:40:12 +00005786QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5787 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005788 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00005789 << LHS.get()->getType() << RHS.get()->getType()
5790 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005791 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005792}
5793
Richard Trieu859d23f2011-09-06 21:01:04 +00005794QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00005795 SourceLocation Loc, bool IsCompAssign) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005796 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005797 // For example, "const float" and "float" are equivalent.
Richard Trieu859d23f2011-09-06 21:01:04 +00005798 QualType LHSType =
5799 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5800 QualType RHSType =
5801 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005802
Nate Begeman191a6b12008-07-14 18:02:46 +00005803 // If the vector types are identical, return.
Richard Trieu859d23f2011-09-06 21:01:04 +00005804 if (LHSType == RHSType)
5805 return LHSType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005806
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005807 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu859d23f2011-09-06 21:01:04 +00005808 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5809 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5810 if (LHSType->isExtVectorType()) {
5811 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5812 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005813 }
5814
Richard Trieuba63ce62011-09-09 01:45:06 +00005815 if (!IsCompAssign)
Richard Trieu859d23f2011-09-06 21:01:04 +00005816 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5817 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005818 }
5819
Eli Friedman1408bc92011-06-23 18:10:35 +00005820 if (getLangOptions().LaxVectorConversions &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005821 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005822 // If we are allowing lax vector conversions, and LHS and RHS are both
5823 // vectors, the total size only needs to be the same. This is a
5824 // bitcast; no bits are changed but the result type is different.
5825 // FIXME: Should we really be allowing this?
Richard Trieu859d23f2011-09-06 21:01:04 +00005826 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5827 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005828 }
5829
Nate Begemanbd956c42009-06-28 02:36:38 +00005830 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5831 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5832 bool swapped = false;
Richard Trieuba63ce62011-09-09 01:45:06 +00005833 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005834 swapped = true;
Richard Trieu859d23f2011-09-06 21:01:04 +00005835 std::swap(RHS, LHS);
5836 std::swap(RHSType, LHSType);
Nate Begemanbd956c42009-06-28 02:36:38 +00005837 }
Mike Stump11289f42009-09-09 15:08:12 +00005838
Nate Begeman886448d2009-06-28 19:12:57 +00005839 // Handle the case of an ext vector and scalar.
Richard Trieu859d23f2011-09-06 21:01:04 +00005840 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005841 QualType EltTy = LV->getElementType();
Richard Trieu859d23f2011-09-06 21:01:04 +00005842 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5843 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005844 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005845 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005846 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005847 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5848 if (swapped) std::swap(RHS, LHS);
5849 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005850 }
5851 }
Richard Trieu859d23f2011-09-06 21:01:04 +00005852 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5853 RHSType->isRealFloatingType()) {
5854 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005855 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005856 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005857 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005858 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5859 if (swapped) std::swap(RHS, LHS);
5860 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005861 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005862 }
5863 }
Mike Stump11289f42009-09-09 15:08:12 +00005864
Nate Begeman886448d2009-06-28 19:12:57 +00005865 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu859d23f2011-09-06 21:01:04 +00005866 if (swapped) std::swap(RHS, LHS);
Chris Lattner377d1f82008-11-18 22:52:51 +00005867 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu859d23f2011-09-06 21:01:04 +00005868 << LHS.get()->getType() << RHS.get()->getType()
5869 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005870 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005871}
5872
Richard Trieuf8916e12011-09-16 00:53:10 +00005873// checkArithmeticNull - Detect when a NULL constant is used improperly in an
5874// expression. These are mainly cases where the null pointer is used as an
5875// integer instead of a pointer.
5876static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
5877 SourceLocation Loc, bool IsCompare) {
5878 // The canonical way to check for a GNU null is with isNullPointerConstant,
5879 // but we use a bit of a hack here for speed; this is a relatively
5880 // hot path, and isNullPointerConstant is slow.
5881 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
5882 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
5883
5884 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
5885
5886 // Avoid analyzing cases where the result will either be invalid (and
5887 // diagnosed as such) or entirely valid and not something to warn about.
5888 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
5889 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
5890 return;
5891
5892 // Comparison operations would not make sense with a null pointer no matter
5893 // what the other expression is.
5894 if (!IsCompare) {
5895 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
5896 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
5897 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
5898 return;
5899 }
5900
5901 // The rest of the operations only make sense with a null pointer
5902 // if the other expression is a pointer.
5903 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
5904 NonNullType->canDecayToPointerType())
5905 return;
5906
5907 S.Diag(Loc, diag::warn_null_in_comparison_operation)
5908 << LHSNull /* LHS is NULL */ << NonNullType
5909 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5910}
5911
Richard Trieu859d23f2011-09-06 21:01:04 +00005912QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00005913 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00005914 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005915 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5916
Richard Trieu859d23f2011-09-06 21:01:04 +00005917 if (LHS.get()->getType()->isVectorType() ||
5918 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00005919 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005920
Richard Trieuba63ce62011-09-09 01:45:06 +00005921 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005922 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005923 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005924
Richard Trieu859d23f2011-09-06 21:01:04 +00005925 if (!LHS.get()->getType()->isArithmeticType() ||
5926 !RHS.get()->getType()->isArithmeticType())
5927 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005928
Chris Lattnerfaa54172010-01-12 21:23:57 +00005929 // Check for division by zero.
Richard Trieuba63ce62011-09-09 01:45:06 +00005930 if (IsDiv &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005931 RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005932 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005933 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
5934 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005935
Chris Lattnerfaa54172010-01-12 21:23:57 +00005936 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005937}
5938
Chris Lattnerfaa54172010-01-12 21:23:57 +00005939QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00005940 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005941 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5942
Richard Trieu859d23f2011-09-06 21:01:04 +00005943 if (LHS.get()->getType()->isVectorType() ||
5944 RHS.get()->getType()->isVectorType()) {
5945 if (LHS.get()->getType()->hasIntegerRepresentation() &&
5946 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00005947 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005948 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005949 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005950
Richard Trieuba63ce62011-09-09 01:45:06 +00005951 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005952 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005953 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005954
Richard Trieu859d23f2011-09-06 21:01:04 +00005955 if (!LHS.get()->getType()->isIntegerType() ||
5956 !RHS.get()->getType()->isIntegerType())
5957 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005958
Chris Lattnerfaa54172010-01-12 21:23:57 +00005959 // Check for remainder by zero.
Richard Trieu859d23f2011-09-06 21:01:04 +00005960 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005961 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005962 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
5963 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005964
Chris Lattnerfaa54172010-01-12 21:23:57 +00005965 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005966}
5967
Chandler Carruthc9332212011-06-27 08:02:19 +00005968/// \brief Diagnose invalid arithmetic on two void pointers.
5969static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00005970 Expr *LHSExpr, Expr *RHSExpr) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005971 S.Diag(Loc, S.getLangOptions().CPlusPlus
5972 ? diag::err_typecheck_pointer_arith_void_type
5973 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00005974 << 1 /* two pointers */ << LHSExpr->getSourceRange()
5975 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00005976}
5977
5978/// \brief Diagnose invalid arithmetic on a void pointer.
5979static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5980 Expr *Pointer) {
5981 S.Diag(Loc, S.getLangOptions().CPlusPlus
5982 ? diag::err_typecheck_pointer_arith_void_type
5983 : diag::ext_gnu_void_ptr)
5984 << 0 /* one pointer */ << Pointer->getSourceRange();
5985}
5986
5987/// \brief Diagnose invalid arithmetic on two function pointers.
5988static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5989 Expr *LHS, Expr *RHS) {
5990 assert(LHS->getType()->isAnyPointerType());
5991 assert(RHS->getType()->isAnyPointerType());
5992 S.Diag(Loc, S.getLangOptions().CPlusPlus
5993 ? diag::err_typecheck_pointer_arith_function_type
5994 : diag::ext_gnu_ptr_func_arith)
5995 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5996 // We only show the second type if it differs from the first.
5997 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5998 RHS->getType())
5999 << RHS->getType()->getPointeeType()
6000 << LHS->getSourceRange() << RHS->getSourceRange();
6001}
6002
6003/// \brief Diagnose invalid arithmetic on a function pointer.
6004static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6005 Expr *Pointer) {
6006 assert(Pointer->getType()->isAnyPointerType());
6007 S.Diag(Loc, S.getLangOptions().CPlusPlus
6008 ? diag::err_typecheck_pointer_arith_function_type
6009 : diag::ext_gnu_ptr_func_arith)
6010 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6011 << 0 /* one pointer, so only one type */
6012 << Pointer->getSourceRange();
6013}
6014
Richard Trieu993f3ab2011-09-12 18:08:02 +00006015/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00006016///
6017/// \returns True if pointer has incomplete type
6018static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6019 Expr *Operand) {
6020 if ((Operand->getType()->isPointerType() &&
6021 !Operand->getType()->isDependentType()) ||
6022 Operand->getType()->isObjCObjectPointerType()) {
6023 QualType PointeeTy = Operand->getType()->getPointeeType();
6024 if (S.RequireCompleteType(
6025 Loc, PointeeTy,
6026 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6027 << PointeeTy << Operand->getSourceRange()))
6028 return true;
6029 }
6030 return false;
6031}
6032
Chandler Carruthc9332212011-06-27 08:02:19 +00006033/// \brief Check the validity of an arithmetic pointer operand.
6034///
6035/// If the operand has pointer type, this code will check for pointer types
6036/// which are invalid in arithmetic operations. These will be diagnosed
6037/// appropriately, including whether or not the use is supported as an
6038/// extension.
6039///
6040/// \returns True when the operand is valid to use (even if as an extension).
6041static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6042 Expr *Operand) {
6043 if (!Operand->getType()->isAnyPointerType()) return true;
6044
6045 QualType PointeeTy = Operand->getType()->getPointeeType();
6046 if (PointeeTy->isVoidType()) {
6047 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6048 return !S.getLangOptions().CPlusPlus;
6049 }
6050 if (PointeeTy->isFunctionType()) {
6051 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6052 return !S.getLangOptions().CPlusPlus;
6053 }
6054
Richard Trieuaba22802011-09-02 02:15:37 +00006055 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00006056
6057 return true;
6058}
6059
6060/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6061/// operands.
6062///
6063/// This routine will diagnose any invalid arithmetic on pointer operands much
6064/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6065/// for emitting a single diagnostic even for operations where both LHS and RHS
6066/// are (potentially problematic) pointers.
6067///
6068/// \returns True when the operand is valid to use (even if as an extension).
6069static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006070 Expr *LHSExpr, Expr *RHSExpr) {
6071 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6072 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006073 if (!isLHSPointer && !isRHSPointer) return true;
6074
6075 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00006076 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6077 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006078
6079 // Check for arithmetic on pointers to incomplete types.
6080 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6081 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6082 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006083 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6084 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6085 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006086
6087 return !S.getLangOptions().CPlusPlus;
6088 }
6089
6090 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6091 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6092 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006093 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6094 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6095 RHSExpr);
6096 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006097
6098 return !S.getLangOptions().CPlusPlus;
6099 }
6100
Richard Trieu4ae7e972011-09-06 21:13:51 +00006101 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
6102 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
Richard Trieuaba22802011-09-02 02:15:37 +00006103
Chandler Carruthc9332212011-06-27 08:02:19 +00006104 return true;
6105}
6106
Richard Trieub10c6312011-09-01 22:53:23 +00006107/// \brief Check bad cases where we step over interface counts.
6108static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
6109 SourceLocation OpLoc,
6110 Expr *Op) {
6111 assert(Op->getType()->isAnyPointerType());
6112 QualType PointeeTy = Op->getType()->getPointeeType();
6113 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
6114 return true;
6115
6116 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6117 << PointeeTy << Op->getSourceRange();
6118 return false;
6119}
6120
Richard Trieu993f3ab2011-09-12 18:08:02 +00006121/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00006122static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006123 Expr *LHSExpr, Expr *RHSExpr) {
6124 assert(LHSExpr->getType()->isAnyPointerType());
6125 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00006126 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006127 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6128 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00006129}
6130
Chris Lattnerfaa54172010-01-12 21:23:57 +00006131QualType Sema::CheckAdditionOperands( // C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006132 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006133 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6134
Richard Trieu4ae7e972011-09-06 21:13:51 +00006135 if (LHS.get()->getType()->isVectorType() ||
6136 RHS.get()->getType()->isVectorType()) {
6137 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006138 if (CompLHSTy) *CompLHSTy = compType;
6139 return compType;
6140 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006141
Richard Trieu4ae7e972011-09-06 21:13:51 +00006142 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6143 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006144 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006145
Steve Naroffe4718892007-04-27 18:30:00 +00006146 // handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006147 if (LHS.get()->getType()->isArithmeticType() &&
6148 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006149 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006150 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006151 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006152
Eli Friedman8e122982008-05-18 18:08:51 +00006153 // Put any potential pointer into PExp
Richard Trieu4ae7e972011-09-06 21:13:51 +00006154 Expr* PExp = LHS.get(), *IExp = RHS.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00006155 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006156 std::swap(PExp, IExp);
6157
Richard Trieub420bca2011-09-12 18:37:54 +00006158 if (!PExp->getType()->isAnyPointerType())
6159 return InvalidOperands(Loc, LHS, RHS);
Chandler Carruthc9332212011-06-27 08:02:19 +00006160
Richard Trieub420bca2011-09-12 18:37:54 +00006161 if (!IExp->getType()->isIntegerType())
6162 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006163
Richard Trieub420bca2011-09-12 18:37:54 +00006164 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6165 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006166
Richard Trieub420bca2011-09-12 18:37:54 +00006167 // Diagnose bad cases where we step over interface counts.
6168 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6169 return QualType();
6170
6171 // Check array bounds for pointer arithemtic
6172 CheckArrayAccess(PExp, IExp);
6173
6174 if (CompLHSTy) {
6175 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6176 if (LHSTy.isNull()) {
6177 LHSTy = LHS.get()->getType();
6178 if (LHSTy->isPromotableIntegerType())
6179 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006180 }
Richard Trieub420bca2011-09-12 18:37:54 +00006181 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00006182 }
6183
Richard Trieub420bca2011-09-12 18:37:54 +00006184 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006185}
6186
Chris Lattner2a3569b2008-04-07 05:30:13 +00006187// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006188QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006189 SourceLocation Loc,
6190 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006191 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6192
Richard Trieu4ae7e972011-09-06 21:13:51 +00006193 if (LHS.get()->getType()->isVectorType() ||
6194 RHS.get()->getType()->isVectorType()) {
6195 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006196 if (CompLHSTy) *CompLHSTy = compType;
6197 return compType;
6198 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006199
Richard Trieu4ae7e972011-09-06 21:13:51 +00006200 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6201 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006202 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006203
Chris Lattner4d62f422007-12-09 21:53:25 +00006204 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006205
Chris Lattner4d62f422007-12-09 21:53:25 +00006206 // Handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006207 if (LHS.get()->getType()->isArithmeticType() &&
6208 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006209 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006210 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006211 }
Mike Stump11289f42009-09-09 15:08:12 +00006212
Chris Lattner4d62f422007-12-09 21:53:25 +00006213 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006214 if (LHS.get()->getType()->isAnyPointerType()) {
6215 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006216
Chris Lattner12bdebb2009-04-24 23:50:08 +00006217 // Diagnose bad cases where we step over interface counts.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006218 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006219 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006220
Chris Lattner4d62f422007-12-09 21:53:25 +00006221 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006222 if (RHS.get()->getType()->isIntegerType()) {
6223 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006224 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006225
Richard Trieu4ae7e972011-09-06 21:13:51 +00006226 Expr *IExpr = RHS.get()->IgnoreParenCasts();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006227 UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6228 OK_Ordinary, IExpr->getExprLoc());
6229 // Check array bounds for pointer arithemtic
Richard Trieu4ae7e972011-09-06 21:13:51 +00006230 CheckArrayAccess(LHS.get()->IgnoreParenCasts(), &negRex);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006231
Richard Trieu4ae7e972011-09-06 21:13:51 +00006232 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6233 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006234 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006235
Chris Lattner4d62f422007-12-09 21:53:25 +00006236 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006237 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00006238 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006239 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006240
Eli Friedman168fe152009-05-16 13:54:38 +00006241 if (getLangOptions().CPlusPlus) {
6242 // Pointee types must be the same: C++ [expr.add]
6243 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006244 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006245 }
6246 } else {
6247 // Pointee types must be compatible C99 6.5.6p3
6248 if (!Context.typesAreCompatible(
6249 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6250 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006251 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006252 return QualType();
6253 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006254 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006255
Chandler Carruthc9332212011-06-27 08:02:19 +00006256 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006257 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006258 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006259
Richard Trieu4ae7e972011-09-06 21:13:51 +00006260 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006261 return Context.getPointerDiffType();
6262 }
6263 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006264
Richard Trieu4ae7e972011-09-06 21:13:51 +00006265 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006266}
6267
Douglas Gregor0bf31402010-10-08 23:50:27 +00006268static bool isScopedEnumerationType(QualType T) {
6269 if (const EnumType *ET = dyn_cast<EnumType>(T))
6270 return ET->getDecl()->isScoped();
6271 return false;
6272}
6273
Richard Trieue4a19fb2011-09-06 21:21:28 +00006274static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006275 SourceLocation Loc, unsigned Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00006276 QualType LHSType) {
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006277 llvm::APSInt Right;
6278 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00006279 if (RHS.get()->isValueDependent() ||
6280 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006281 return;
6282
6283 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006284 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006285 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006286 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006287 return;
6288 }
6289 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00006290 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006291 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006292 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006293 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006294 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006295 return;
6296 }
6297 if (Opc != BO_Shl)
6298 return;
6299
6300 // When left shifting an ICE which is signed, we can check for overflow which
6301 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6302 // integers have defined behavior modulo one more than the maximum value
6303 // representable in the result type, so never warn for those.
6304 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00006305 if (LHS.get()->isValueDependent() ||
6306 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6307 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006308 return;
6309 llvm::APInt ResultBits =
6310 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6311 if (LeftBits.uge(ResultBits))
6312 return;
6313 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6314 Result = Result.shl(Right);
6315
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006316 // Print the bit representation of the signed integer as an unsigned
6317 // hexadecimal number.
6318 llvm::SmallString<40> HexResult;
6319 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6320
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006321 // If we are only missing a sign bit, this is less likely to result in actual
6322 // bugs -- if the result is cast back to an unsigned type, it will have the
6323 // expected value. Thus we place this behind a different warning that can be
6324 // turned off separately if needed.
6325 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006326 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006327 << HexResult.str() << LHSType
6328 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006329 return;
6330 }
6331
6332 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006333 << HexResult.str() << Result.getMinSignedBits() << LHSType
6334 << Left.getBitWidth() << LHS.get()->getSourceRange()
6335 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006336}
6337
Chris Lattner2a3569b2008-04-07 05:30:13 +00006338// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00006339QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006340 SourceLocation Loc, unsigned Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006341 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006342 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6343
Chris Lattner5c11c412007-12-12 05:47:28 +00006344 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006345 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6346 !RHS.get()->getType()->hasIntegerRepresentation())
6347 return InvalidOperands(Loc, LHS, RHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006348
Douglas Gregor0bf31402010-10-08 23:50:27 +00006349 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6350 // hasIntegerRepresentation() above instead of this.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006351 if (isScopedEnumerationType(LHS.get()->getType()) ||
6352 isScopedEnumerationType(RHS.get()->getType())) {
6353 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006354 }
6355
Nate Begemane46ee9a2009-10-25 02:26:48 +00006356 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006357 if (LHS.get()->getType()->isVectorType() ||
6358 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006359 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006360
Chris Lattner5c11c412007-12-12 05:47:28 +00006361 // Shifts don't perform usual arithmetic conversions, they just do integer
6362 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006363
John McCall57cdd882010-12-16 19:28:59 +00006364 // For the LHS, do usual unary conversions, but then reset them away
6365 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006366 ExprResult OldLHS = LHS;
6367 LHS = UsualUnaryConversions(LHS.take());
6368 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006369 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00006370 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00006371 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00006372
6373 // The RHS is simpler.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006374 RHS = UsualUnaryConversions(RHS.take());
6375 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006376 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006377
Ryan Flynnf53fab82009-08-07 16:20:20 +00006378 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00006379 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006380
Chris Lattner5c11c412007-12-12 05:47:28 +00006381 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00006382 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006383}
6384
Chandler Carruth17773fc2010-07-10 12:30:03 +00006385static bool IsWithinTemplateSpecialization(Decl *D) {
6386 if (DeclContext *DC = D->getDeclContext()) {
6387 if (isa<ClassTemplateSpecializationDecl>(DC))
6388 return true;
6389 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6390 return FD->isFunctionTemplateSpecialization();
6391 }
6392 return false;
6393}
6394
Richard Trieueea56f72011-09-02 03:48:46 +00006395/// If two different enums are compared, raise a warning.
Richard Trieu1762d7c2011-09-06 21:27:33 +00006396static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6397 ExprResult &RHS) {
6398 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6399 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00006400
6401 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6402 if (!LHSEnumType)
6403 return;
6404 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6405 if (!RHSEnumType)
6406 return;
6407
6408 // Ignore anonymous enums.
6409 if (!LHSEnumType->getDecl()->getIdentifier())
6410 return;
6411 if (!RHSEnumType->getDecl()->getIdentifier())
6412 return;
6413
6414 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6415 return;
6416
6417 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6418 << LHSStrippedType << RHSStrippedType
Richard Trieu1762d7c2011-09-06 21:27:33 +00006419 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00006420}
6421
Richard Trieudd82a5c2011-09-02 02:55:45 +00006422/// \brief Diagnose bad pointer comparisons.
6423static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006424 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006425 bool IsError) {
6426 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00006427 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006428 << LHS.get()->getType() << RHS.get()->getType()
6429 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006430}
6431
6432/// \brief Returns false if the pointers are converted to a composite type,
6433/// true otherwise.
6434static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006435 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006436 // C++ [expr.rel]p2:
6437 // [...] Pointer conversions (4.10) and qualification
6438 // conversions (4.4) are performed on pointer operands (or on
6439 // a pointer operand and a null pointer constant) to bring
6440 // them to their composite pointer type. [...]
6441 //
6442 // C++ [expr.eq]p1 uses the same notion for (in)equality
6443 // comparisons of pointers.
6444
6445 // C++ [expr.eq]p2:
6446 // In addition, pointers to members can be compared, or a pointer to
6447 // member and a null pointer constant. Pointer to member conversions
6448 // (4.11) and qualification conversions (4.4) are performed to bring
6449 // them to a common type. If one operand is a null pointer constant,
6450 // the common type is the type of the other operand. Otherwise, the
6451 // common type is a pointer to member type similar (4.4) to the type
6452 // of one of the operands, with a cv-qualification signature (4.4)
6453 // that is the union of the cv-qualification signatures of the operand
6454 // types.
6455
Richard Trieu1762d7c2011-09-06 21:27:33 +00006456 QualType LHSType = LHS.get()->getType();
6457 QualType RHSType = RHS.get()->getType();
6458 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6459 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00006460
6461 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00006462 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00006463 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006464 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00006465 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006466 return true;
6467 }
6468
6469 if (NonStandardCompositeType)
6470 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006471 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6472 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006473
Richard Trieu1762d7c2011-09-06 21:27:33 +00006474 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6475 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006476 return false;
6477}
6478
6479static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006480 ExprResult &LHS,
6481 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006482 bool IsError) {
6483 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6484 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006485 << LHS.get()->getType() << RHS.get()->getType()
6486 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006487}
6488
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006489// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00006490QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006491 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006492 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006493 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6494
John McCalle3027922010-08-25 11:45:40 +00006495 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006496
Chris Lattner9a152e22009-12-05 05:40:13 +00006497 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00006498 if (LHS.get()->getType()->isVectorType() ||
6499 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006500 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006501
Richard Trieub80728f2011-09-06 21:43:51 +00006502 QualType LHSType = LHS.get()->getType();
6503 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00006504
Richard Trieub80728f2011-09-06 21:43:51 +00006505 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6506 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006507
Richard Trieub80728f2011-09-06 21:43:51 +00006508 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth712563b2011-02-17 08:37:06 +00006509
Richard Trieub80728f2011-09-06 21:43:51 +00006510 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00006511 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00006512 !LHS.get()->getLocStart().isMacroID() &&
6513 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006514 // For non-floating point types, check for self-comparisons of the form
6515 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6516 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006517 //
6518 // NOTE: Don't warn about comparison expressions resulting from macro
6519 // expansion. Also don't warn about comparisons which are only self
6520 // comparisons within a template specialization. The warnings should catch
6521 // obvious cases in the definition of the template anyways. The idea is to
6522 // warn when the typed comparison operator will always evaluate to the same
6523 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006524 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006525 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006526 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006527 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006528 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006529 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006530 << (Opc == BO_EQ
6531 || Opc == BO_LE
6532 || Opc == BO_GE));
Richard Trieub80728f2011-09-06 21:43:51 +00006533 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregorec170db2010-06-08 19:50:34 +00006534 !DRL->getDecl()->getType()->isReferenceType() &&
6535 !DRR->getDecl()->getType()->isReferenceType()) {
6536 // what is it always going to eval to?
6537 char always_evals_to;
6538 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006539 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006540 always_evals_to = 0; // false
6541 break;
John McCalle3027922010-08-25 11:45:40 +00006542 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006543 always_evals_to = 1; // true
6544 break;
6545 default:
6546 // best we can say is 'a constant'
6547 always_evals_to = 2; // e.g. array1 <= array2
6548 break;
6549 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006550 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006551 << 1 // array
6552 << always_evals_to);
6553 }
6554 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006555 }
Mike Stump11289f42009-09-09 15:08:12 +00006556
Chris Lattner222b8bd2009-03-08 19:39:53 +00006557 if (isa<CastExpr>(LHSStripped))
6558 LHSStripped = LHSStripped->IgnoreParenCasts();
6559 if (isa<CastExpr>(RHSStripped))
6560 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006561
Chris Lattner222b8bd2009-03-08 19:39:53 +00006562 // Warn about comparisons against a string constant (unless the other
6563 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006564 Expr *literalString = 0;
6565 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006566 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006567 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006568 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006569 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006570 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006571 } else if ((isa<StringLiteral>(RHSStripped) ||
6572 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006573 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006574 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006575 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006576 literalStringStripped = RHSStripped;
6577 }
6578
6579 if (literalString) {
6580 std::string resultComparison;
6581 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006582 case BO_LT: resultComparison = ") < 0"; break;
6583 case BO_GT: resultComparison = ") > 0"; break;
6584 case BO_LE: resultComparison = ") <= 0"; break;
6585 case BO_GE: resultComparison = ") >= 0"; break;
6586 case BO_EQ: resultComparison = ") == 0"; break;
6587 case BO_NE: resultComparison = ") != 0"; break;
David Blaikie83d382b2011-09-23 05:06:16 +00006588 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006589 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006590
Ted Kremenek3427fac2011-02-23 01:52:04 +00006591 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006592 PDiag(diag::warn_stringcompare)
6593 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006594 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006595 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006596 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006597
Douglas Gregorec170db2010-06-08 19:50:34 +00006598 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieub80728f2011-09-06 21:43:51 +00006599 if (LHS.get()->getType()->isArithmeticType() &&
6600 RHS.get()->getType()->isArithmeticType()) {
6601 UsualArithmeticConversions(LHS, RHS);
6602 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006603 return QualType();
6604 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006605 else {
Richard Trieub80728f2011-09-06 21:43:51 +00006606 LHS = UsualUnaryConversions(LHS.take());
6607 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006608 return QualType();
6609
Richard Trieub80728f2011-09-06 21:43:51 +00006610 RHS = UsualUnaryConversions(RHS.take());
6611 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006612 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006613 }
6614
Richard Trieub80728f2011-09-06 21:43:51 +00006615 LHSType = LHS.get()->getType();
6616 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006617
Douglas Gregorca63811b2008-11-19 03:25:36 +00006618 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006619 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006620
Richard Trieuba63ce62011-09-09 01:45:06 +00006621 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00006622 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006623 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006624 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006625 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00006626 if (LHSType->hasFloatingRepresentation())
6627 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006628
Richard Trieub80728f2011-09-06 21:43:51 +00006629 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006630 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006631 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006632
Richard Trieub80728f2011-09-06 21:43:51 +00006633 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006634 Expr::NPC_ValueDependentIsNull);
Richard Trieub80728f2011-09-06 21:43:51 +00006635 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006636 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006637
Douglas Gregorf267edd2010-06-15 21:38:40 +00006638 // All of the following pointer-related warnings are GCC extensions, except
6639 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00006640 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006641 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006642 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00006643 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006644 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006645
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006646 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006647 if (LCanPointeeTy == RCanPointeeTy)
6648 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00006649 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006650 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6651 // Valid unless comparison between non-null pointer and function pointer
6652 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006653 // In a SFINAE context, we treat this as a hard error to maintain
6654 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006655 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6656 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006657 diagnoseFunctionPointerToVoidComparison(
Richard Trieub80728f2011-09-06 21:43:51 +00006658 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00006659
6660 if (isSFINAEContext())
6661 return QualType();
6662
Richard Trieub80728f2011-09-06 21:43:51 +00006663 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006664 return ResultTy;
6665 }
6666 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006667
Richard Trieub80728f2011-09-06 21:43:51 +00006668 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006669 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006670 else
6671 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006672 }
Eli Friedman16c209612009-08-23 00:27:47 +00006673 // C99 6.5.9p2 and C99 6.5.8p2
6674 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6675 RCanPointeeTy.getUnqualifiedType())) {
6676 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00006677 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00006678 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00006679 << LHSType << RHSType << LHS.get()->getSourceRange()
6680 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006681 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006682 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00006683 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6684 // Valid unless comparison between non-null pointer and function pointer
6685 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00006686 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006687 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006688 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00006689 } else {
6690 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00006691 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00006692 }
John McCall7684dde2011-03-11 04:25:25 +00006693 if (LCanPointeeTy != RCanPointeeTy) {
6694 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006695 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006696 else
Richard Trieub80728f2011-09-06 21:43:51 +00006697 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006698 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006699 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006700 }
Mike Stump11289f42009-09-09 15:08:12 +00006701
Sebastian Redl576fd422009-05-10 18:38:11 +00006702 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006703 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00006704 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00006705 return ResultTy;
6706
Mike Stump11289f42009-09-09 15:08:12 +00006707 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006708 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006709 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006710 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006711 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006712 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
6713 RHS = ImpCastExprToType(RHS.take(), LHSType,
6714 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006715 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006716 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006717 return ResultTy;
6718 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006719 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006720 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006721 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006722 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
6723 LHS = ImpCastExprToType(LHS.take(), RHSType,
6724 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006725 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006726 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006727 return ResultTy;
6728 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006729
6730 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006731 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006732 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
6733 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006734 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006735 else
6736 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006737 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006738
6739 // Handle scoped enumeration types specifically, since they don't promote
6740 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00006741 if (LHS.get()->getType()->isEnumeralType() &&
6742 Context.hasSameUnqualifiedType(LHS.get()->getType(),
6743 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006744 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00006745 }
Mike Stump11289f42009-09-09 15:08:12 +00006746
Steve Naroff081c7422008-09-04 15:10:53 +00006747 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00006748 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00006749 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00006750 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
6751 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006752
Steve Naroff081c7422008-09-04 15:10:53 +00006753 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006754 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006755 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006756 << LHSType << RHSType << LHS.get()->getSourceRange()
6757 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006758 }
Richard Trieub80728f2011-09-06 21:43:51 +00006759 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006760 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006761 }
John Wiegley01296292011-04-08 18:41:53 +00006762
Steve Naroffe18f94c2008-09-28 01:11:11 +00006763 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00006764 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00006765 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
6766 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006767 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00006768 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006769 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00006770 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006771 ->getPointeeType()->isVoidType())))
6772 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006773 << LHSType << RHSType << LHS.get()->getSourceRange()
6774 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006775 }
John McCall7684dde2011-03-11 04:25:25 +00006776 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006777 LHS = ImpCastExprToType(LHS.take(), RHSType,
6778 RHSType->isPointerType() ? CK_BitCast
6779 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006780 else
John McCall9320b872011-09-09 05:25:32 +00006781 RHS = ImpCastExprToType(RHS.take(), LHSType,
6782 LHSType->isPointerType() ? CK_BitCast
6783 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006784 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006785 }
Steve Naroff081c7422008-09-04 15:10:53 +00006786
Richard Trieub80728f2011-09-06 21:43:51 +00006787 if (LHSType->isObjCObjectPointerType() ||
6788 RHSType->isObjCObjectPointerType()) {
6789 const PointerType *LPT = LHSType->getAs<PointerType>();
6790 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00006791 if (LPT || RPT) {
6792 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6793 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006794
Steve Naroff753567f2008-11-17 19:49:16 +00006795 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00006796 !Context.typesAreCompatible(LHSType, RHSType)) {
6797 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006798 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006799 }
John McCall7684dde2011-03-11 04:25:25 +00006800 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006801 LHS = ImpCastExprToType(LHS.take(), RHSType,
6802 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006803 else
John McCall9320b872011-09-09 05:25:32 +00006804 RHS = ImpCastExprToType(RHS.take(), LHSType,
6805 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006806 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006807 }
Richard Trieub80728f2011-09-06 21:43:51 +00006808 if (LHSType->isObjCObjectPointerType() &&
6809 RHSType->isObjCObjectPointerType()) {
6810 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
6811 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006812 /*isError*/false);
John McCall7684dde2011-03-11 04:25:25 +00006813 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006814 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006815 else
Richard Trieub80728f2011-09-06 21:43:51 +00006816 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006817 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006818 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006819 }
Richard Trieub80728f2011-09-06 21:43:51 +00006820 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
6821 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006822 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006823 bool isError = false;
Richard Trieub80728f2011-09-06 21:43:51 +00006824 if ((LHSIsNull && LHSType->isIntegerType()) ||
6825 (RHSIsNull && RHSType->isIntegerType())) {
Richard Trieuba63ce62011-09-09 01:45:06 +00006826 if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006827 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Richard Trieuba63ce62011-09-09 01:45:06 +00006828 } else if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006829 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006830 else if (getLangOptions().CPlusPlus) {
6831 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6832 isError = true;
6833 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006834 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006835
Chris Lattnerd99bd522009-08-23 00:03:44 +00006836 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006837 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00006838 << LHSType << RHSType << LHS.get()->getSourceRange()
6839 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006840 if (isError)
6841 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006842 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006843
Richard Trieub80728f2011-09-06 21:43:51 +00006844 if (LHSType->isIntegerType())
6845 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006846 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006847 else
Richard Trieub80728f2011-09-06 21:43:51 +00006848 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006849 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006850 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006851 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006852
Steve Naroff4b191572008-09-04 16:56:14 +00006853 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006854 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006855 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
6856 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006857 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006858 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006859 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006860 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
6861 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006862 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006863 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006864
Richard Trieub80728f2011-09-06 21:43:51 +00006865 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006866}
6867
Nate Begeman191a6b12008-07-14 18:02:46 +00006868/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006869/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006870/// like a scalar comparison, a vector comparison produces a vector of integer
6871/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00006872QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00006873 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006874 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006875 // Check to make sure we're operating on vectors of the same type and width,
6876 // Allowing one side to be a scalar of element type.
Richard Trieubcce2f72011-09-07 01:19:57 +00006877 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00006878 if (vType.isNull())
6879 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006880
Richard Trieubcce2f72011-09-07 01:19:57 +00006881 QualType LHSType = LHS.get()->getType();
6882 QualType RHSType = RHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006883
Anton Yartsev530deb92011-03-27 15:36:07 +00006884 // If AltiVec, the comparison results in a numeric type, i.e.
6885 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00006886 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00006887 return Context.getLogicalOperationType();
6888
Nate Begeman191a6b12008-07-14 18:02:46 +00006889 // For non-floating point types, check for self-comparisons of the form
6890 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6891 // often indicate logic errors in the program.
Richard Trieubcce2f72011-09-07 01:19:57 +00006892 if (!LHSType->hasFloatingRepresentation()) {
6893 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
6894 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00006895 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00006896 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00006897 PDiag(diag::warn_comparison_always)
6898 << 0 // self-
6899 << 2 // "a constant"
6900 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006901 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006902
Nate Begeman191a6b12008-07-14 18:02:46 +00006903 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00006904 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
Richard Trieubcce2f72011-09-07 01:19:57 +00006905 assert (RHSType->hasFloatingRepresentation());
6906 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00006907 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006908
Nate Begeman191a6b12008-07-14 18:02:46 +00006909 // Return the type for the comparison, which is the same as vector type for
6910 // integer vectors, or an integer type of identical size and number of
6911 // elements for floating point vectors.
Richard Trieubcce2f72011-09-07 01:19:57 +00006912 if (LHSType->hasIntegerRepresentation())
6913 return LHSType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006914
Richard Trieubcce2f72011-09-07 01:19:57 +00006915 const VectorType *VTy = LHSType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006916 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006917 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006918 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006919 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006920 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6921
Mike Stump4e1f26a2009-02-19 03:04:26 +00006922 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006923 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006924 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6925}
6926
Steve Naroff218bc2b2007-05-04 21:54:46 +00006927inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00006928 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006929 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6930
Richard Trieubcce2f72011-09-07 01:19:57 +00006931 if (LHS.get()->getType()->isVectorType() ||
6932 RHS.get()->getType()->isVectorType()) {
6933 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6934 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00006935 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006936
Richard Trieubcce2f72011-09-07 01:19:57 +00006937 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006938 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006939
Richard Trieubcce2f72011-09-07 01:19:57 +00006940 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
6941 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00006942 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00006943 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006944 return QualType();
Richard Trieubcce2f72011-09-07 01:19:57 +00006945 LHS = LHSResult.take();
6946 RHS = RHSResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006947
Richard Trieubcce2f72011-09-07 01:19:57 +00006948 if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6949 RHS.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006950 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00006951 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006952}
6953
Steve Naroff218bc2b2007-05-04 21:54:46 +00006954inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieubcce2f72011-09-07 01:19:57 +00006955 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00006956
6957 // Diagnose cases where the user write a logical and/or but probably meant a
6958 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6959 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00006960 if (LHS.get()->getType()->isIntegerType() &&
6961 !LHS.get()->getType()->isBooleanType() &&
6962 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00006963 // Don't warn in macros or template instantiations.
6964 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00006965 // If the RHS can be constant folded, and if it constant folds to something
6966 // that isn't 0 or 1 (which indicate a potential logical operation that
6967 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006968 // Parens on the RHS are ignored.
Chris Lattner938533d2010-07-24 01:10:11 +00006969 Expr::EvalResult Result;
Richard Trieubcce2f72011-09-07 01:19:57 +00006970 if (RHS.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6971 if ((getLangOptions().Bool && !RHS.get()->getType()->isBooleanType()) ||
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006972 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6973 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00006974 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006975 << (Opc == BO_LAnd ? "&&" : "||");
6976 // Suggest replacing the logical operator with the bitwise version
6977 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6978 << (Opc == BO_LAnd ? "&" : "|")
6979 << FixItHint::CreateReplacement(SourceRange(
6980 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6981 getLangOptions())),
6982 Opc == BO_LAnd ? "&" : "|");
6983 if (Opc == BO_LAnd)
6984 // Suggest replacing "Foo() && kNonZero" with "Foo()"
6985 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6986 << FixItHint::CreateRemoval(
6987 SourceRange(
Richard Trieubcce2f72011-09-07 01:19:57 +00006988 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006989 0, getSourceManager(),
6990 getLangOptions()),
Richard Trieubcce2f72011-09-07 01:19:57 +00006991 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006992 }
Chris Lattner938533d2010-07-24 01:10:11 +00006993 }
Chris Lattner8406c512010-07-13 19:41:32 +00006994
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006995 if (!Context.getLangOptions().CPlusPlus) {
Richard Trieubcce2f72011-09-07 01:19:57 +00006996 LHS = UsualUnaryConversions(LHS.take());
6997 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006998 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006999
Richard Trieubcce2f72011-09-07 01:19:57 +00007000 RHS = UsualUnaryConversions(RHS.take());
7001 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007002 return QualType();
7003
Richard Trieubcce2f72011-09-07 01:19:57 +00007004 if (!LHS.get()->getType()->isScalarType() ||
7005 !RHS.get()->getType()->isScalarType())
7006 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007007
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007008 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007009 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007010
John McCall4a2429a2010-06-04 00:29:51 +00007011 // The following is safe because we only use this method for
7012 // non-overloadable operands.
7013
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007014 // C++ [expr.log.and]p1
7015 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007016 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00007017 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7018 if (LHSRes.isInvalid())
7019 return InvalidOperands(Loc, LHS, RHS);
7020 LHS = move(LHSRes);
John Wiegley01296292011-04-08 18:41:53 +00007021
Richard Trieubcce2f72011-09-07 01:19:57 +00007022 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7023 if (RHSRes.isInvalid())
7024 return InvalidOperands(Loc, LHS, RHS);
7025 RHS = move(RHSRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007026
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007027 // C++ [expr.log.and]p2
7028 // C++ [expr.log.or]p2
7029 // The result is a bool.
7030 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007031}
7032
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007033/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7034/// is a read-only property; return true if so. A readonly property expression
7035/// depends on various declarations and thus must be treated specially.
7036///
Mike Stump11289f42009-09-09 15:08:12 +00007037static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007038 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7039 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00007040 if (PropExpr->isImplicitProperty()) return false;
7041
7042 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7043 QualType BaseType = PropExpr->isSuperReceiver() ?
7044 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007045 PropExpr->getBase()->getType();
7046
John McCallb7bd14f2010-12-02 01:19:52 +00007047 if (const ObjCObjectPointerType *OPT =
7048 BaseType->getAsObjCInterfacePointerType())
7049 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7050 if (S.isPropertyReadonly(PDecl, IFace))
7051 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007052 }
7053 return false;
7054}
7055
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007056static bool IsConstProperty(Expr *E, Sema &S) {
7057 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7058 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
7059 if (PropExpr->isImplicitProperty()) return false;
7060
7061 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7062 QualType T = PDecl->getType();
7063 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00007064 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007065 CanQualType CT = S.Context.getCanonicalType(T);
7066 return CT.isConstQualified();
7067 }
7068 return false;
7069}
7070
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007071static bool IsReadonlyMessage(Expr *E, Sema &S) {
7072 if (E->getStmtClass() != Expr::MemberExprClass)
7073 return false;
7074 const MemberExpr *ME = cast<MemberExpr>(E);
7075 NamedDecl *Member = ME->getMemberDecl();
7076 if (isa<FieldDecl>(Member)) {
7077 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
7078 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
7079 return false;
7080 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
7081 }
7082 return false;
7083}
7084
Chris Lattner30bd3272008-11-18 01:22:49 +00007085/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7086/// emit an error and return true. If so, return false.
7087static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007088 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007089 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007090 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007091 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7092 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007093 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7094 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007095 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7096 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007097 if (IsLV == Expr::MLV_Valid)
7098 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007099
Chris Lattner30bd3272008-11-18 01:22:49 +00007100 unsigned Diag = 0;
7101 bool NeedType = false;
7102 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00007103 case Expr::MLV_ConstQualified:
7104 Diag = diag::err_typecheck_assign_const;
7105
John McCalld4631322011-06-17 06:42:21 +00007106 // In ARC, use some specialized diagnostics for occasions where we
7107 // infer 'const'. These are always pseudo-strong variables.
John McCall31168b02011-06-15 23:02:42 +00007108 if (S.getLangOptions().ObjCAutoRefCount) {
7109 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7110 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7111 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7112
John McCalld4631322011-06-17 06:42:21 +00007113 // Use the normal diagnostic if it's pseudo-__strong but the
7114 // user actually wrote 'const'.
7115 if (var->isARCPseudoStrong() &&
7116 (!var->getTypeSourceInfo() ||
7117 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7118 // There are two pseudo-strong cases:
7119 // - self
John McCall31168b02011-06-15 23:02:42 +00007120 ObjCMethodDecl *method = S.getCurMethodDecl();
7121 if (method && var == method->getSelfDecl())
7122 Diag = diag::err_typecheck_arr_assign_self;
John McCalld4631322011-06-17 06:42:21 +00007123
7124 // - fast enumeration variables
7125 else
John McCall31168b02011-06-15 23:02:42 +00007126 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00007127
John McCall31168b02011-06-15 23:02:42 +00007128 SourceRange Assign;
7129 if (Loc != OrigLoc)
7130 Assign = SourceRange(OrigLoc, OrigLoc);
7131 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7132 // We need to preserve the AST regardless, so migration tool
7133 // can do its job.
7134 return false;
7135 }
7136 }
7137 }
7138
7139 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007140 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007141 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7142 NeedType = true;
7143 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007144 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007145 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7146 NeedType = true;
7147 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007148 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007149 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7150 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007151 case Expr::MLV_Valid:
7152 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007153 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007154 case Expr::MLV_MemberFunction:
7155 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007156 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7157 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007158 case Expr::MLV_IncompleteType:
7159 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007160 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007161 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00007162 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00007163 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007164 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7165 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00007166 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00007167 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7168 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007169 case Expr::MLV_ReadonlyProperty:
7170 Diag = diag::error_readonly_property_assignment;
7171 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007172 case Expr::MLV_NoSetterProperty:
7173 Diag = diag::error_nosetter_property_assignment;
7174 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007175 case Expr::MLV_InvalidMessageExpression:
7176 Diag = diag::error_readonly_message_assignment;
7177 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007178 case Expr::MLV_SubObjCPropertySetting:
7179 Diag = diag::error_no_subobject_property_setting;
7180 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007181 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007182
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007183 SourceRange Assign;
7184 if (Loc != OrigLoc)
7185 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007186 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007187 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007188 else
Mike Stump11289f42009-09-09 15:08:12 +00007189 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007190 return true;
7191}
7192
7193
7194
7195// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00007196QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007197 SourceLocation Loc,
7198 QualType CompoundType) {
7199 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007200 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007201 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007202
Richard Trieuda4f43a62011-09-07 01:33:52 +00007203 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00007204 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7205 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007206 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007207 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007208 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007209 // Simple assignment "x = y".
Richard Trieuda4f43a62011-09-07 01:33:52 +00007210 if (LHSExpr->getObjectKind() == OK_ObjCProperty) {
7211 ExprResult LHSResult = Owned(LHSExpr);
John Wiegley01296292011-04-08 18:41:53 +00007212 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7213 if (LHSResult.isInvalid())
7214 return QualType();
Richard Trieuda4f43a62011-09-07 01:33:52 +00007215 LHSExpr = LHSResult.take();
John Wiegley01296292011-04-08 18:41:53 +00007216 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007217 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007218 if (RHS.isInvalid())
7219 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007220 // Special case of NSObject attributes on c-style pointer types.
7221 if (ConvTy == IncompatiblePointer &&
7222 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007223 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007224 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007225 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007226 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007227
John McCall7decc9e2010-11-18 06:31:45 +00007228 if (ConvTy == Compatible &&
7229 getLangOptions().ObjCNonFragileABI &&
7230 LHSType->isObjCObjectType())
7231 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7232 << LHSType;
7233
Chris Lattnerea714382008-08-21 18:04:13 +00007234 // If the RHS is a unary plus or minus, check to see if they = and + are
7235 // right next to each other. If so, the user may have typo'd "x =+ 4"
7236 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00007237 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00007238 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7239 RHSCheck = ICE->getSubExpr();
7240 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007241 if ((UO->getOpcode() == UO_Plus ||
7242 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007243 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007244 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007245 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00007246 // And there is a space or other character before the subexpr of the
7247 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007248 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00007249 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007250 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007251 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007252 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007253 }
Chris Lattnerea714382008-08-21 18:04:13 +00007254 }
John McCall31168b02011-06-15 23:02:42 +00007255
7256 if (ConvTy == Compatible) {
7257 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007258 checkRetainCycles(LHSExpr, RHS.get());
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007259 else if (getLangOptions().ObjCAutoRefCount)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007260 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00007261 }
Chris Lattnerea714382008-08-21 18:04:13 +00007262 } else {
7263 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007264 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007265 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007266
Chris Lattner326f7572008-11-18 01:30:42 +00007267 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007268 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007269 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007270
Richard Trieuda4f43a62011-09-07 01:33:52 +00007271 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007272
Steve Naroff98cf3e92007-06-06 18:38:38 +00007273 // C99 6.5.16p3: The type of an assignment expression is the type of the
7274 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007275 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007276 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7277 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007278 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007279 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007280 return (getLangOptions().CPlusPlus
7281 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007282}
7283
Chris Lattner326f7572008-11-18 01:30:42 +00007284// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007285static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007286 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00007287 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007288
John McCall3aef3d82011-04-10 19:13:55 +00007289 LHS = S.CheckPlaceholderExpr(LHS.take());
7290 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007291 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007292 return QualType();
7293
John McCall73d36182010-10-12 07:14:40 +00007294 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7295 // operands, but not unary promotions.
7296 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007297
John McCall34376a62010-12-04 03:47:34 +00007298 // So we treat the LHS as a ignored value, and in C++ we allow the
7299 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007300 LHS = S.IgnoredValueConversions(LHS.take());
7301 if (LHS.isInvalid())
7302 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007303
7304 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007305 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7306 if (RHS.isInvalid())
7307 return QualType();
7308 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007309 S.RequireCompleteType(Loc, RHS.get()->getType(),
7310 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007311 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007312
John Wiegley01296292011-04-08 18:41:53 +00007313 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007314}
7315
Steve Naroff7a5af782007-07-13 16:58:59 +00007316/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7317/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007318static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7319 ExprValueKind &VK,
7320 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007321 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007322 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007323 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007324
Chris Lattner6b0cf142008-11-21 07:05:48 +00007325 QualType ResType = Op->getType();
7326 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007327
John McCall4bc41ae2010-11-18 19:01:18 +00007328 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007329 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +00007330 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007331 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007332 return QualType();
7333 }
7334 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007335 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007336 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007337 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007338 } else if (ResType->isAnyPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007339 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007340 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007341 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007342
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007343 // Diagnose bad cases where we step over interface counts.
Richard Trieub10c6312011-09-01 22:53:23 +00007344 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007345 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00007346 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007347 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007348 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007349 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007350 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007351 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007352 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007353 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007354 IsInc, IsPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007355 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7356 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007357 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007358 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +00007359 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007360 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007361 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007362 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007363 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007364 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007365 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007366 // In C++, a prefix increment is the same type as the operand. Otherwise
7367 // (in C or with postfix), the increment is the unqualified type of the
7368 // operand.
Richard Trieuba63ce62011-09-09 01:45:06 +00007369 if (IsPrefix && S.getLangOptions().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007370 VK = VK_LValue;
7371 return ResType;
7372 } else {
7373 VK = VK_RValue;
7374 return ResType.getUnqualifiedType();
7375 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007376}
7377
John Wiegley01296292011-04-08 18:41:53 +00007378ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00007379 assert(E->getValueKind() == VK_LValue &&
7380 E->getObjectKind() == OK_ObjCProperty);
7381 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7382
Douglas Gregor33823722011-06-11 01:09:30 +00007383 QualType T = E->getType();
7384 QualType ReceiverType;
7385 if (PRE->isObjectReceiver())
7386 ReceiverType = PRE->getBase()->getType();
7387 else if (PRE->isSuperReceiver())
7388 ReceiverType = PRE->getSuperReceiverType();
7389 else
7390 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
7391
John McCall34376a62010-12-04 03:47:34 +00007392 ExprValueKind VK = VK_RValue;
7393 if (PRE->isImplicitProperty()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007394 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007395 PRE->getImplicitPropertyGetter()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007396 T = getMessageSendResultType(ReceiverType, GetterMethod,
7397 PRE->isClassReceiver(),
7398 PRE->isSuperReceiver());
7399 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007400 }
7401 else {
7402 Diag(PRE->getLocation(), diag::err_getter_not_found)
7403 << PRE->getBase()->getType();
7404 }
John McCall34376a62010-12-04 03:47:34 +00007405 }
Fariborz Jahanian082a6a12011-10-03 17:58:21 +00007406 else {
7407 // lvalue-ness of an explicit property is determined by
7408 // property type.
7409 ObjCPropertyDecl *PDecl = PRE->getExplicitProperty();
7410 VK = Expr::getValueKindForType(PDecl->getType());
7411 }
7412
Douglas Gregor33823722011-06-11 01:09:30 +00007413 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCall34376a62010-12-04 03:47:34 +00007414 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007415
7416 ExprResult Result = MaybeBindToTemporary(E);
7417 if (!Result.isInvalid())
7418 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00007419
7420 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00007421}
7422
Richard Trieucfc491d2011-08-02 04:35:43 +00007423void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
7424 QualType &LHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00007425 assert(LHS.get()->getValueKind() == VK_LValue &&
7426 LHS.get()->getObjectKind() == OK_ObjCProperty);
7427 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00007428
John McCall31168b02011-06-15 23:02:42 +00007429 bool Consumed = false;
7430
John Wiegley01296292011-04-08 18:41:53 +00007431 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00007432 // If using property-dot syntax notation for assignment, and there is a
7433 // setter, RHS expression is being passed to the setter argument. So,
7434 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00007435 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00007436 ObjCMethodDecl::param_const_iterator P = SetterMD->param_begin();
John McCall34376a62010-12-04 03:47:34 +00007437 LHSTy = (*P)->getType();
John McCall31168b02011-06-15 23:02:42 +00007438 Consumed = (getLangOptions().ObjCAutoRefCount &&
7439 (*P)->hasAttr<NSConsumedAttr>());
John McCall34376a62010-12-04 03:47:34 +00007440
7441 // Otherwise, if the getter returns an l-value, just call that.
7442 } else {
John Wiegley01296292011-04-08 18:41:53 +00007443 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00007444 ExprValueKind VK = Expr::getValueKindForType(Result);
7445 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00007446 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7447 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00007448 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007449 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007450 }
John McCall31168b02011-06-15 23:02:42 +00007451 } else if (getLangOptions().ObjCAutoRefCount) {
7452 const ObjCMethodDecl *setter
7453 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7454 if (setter) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00007455 ObjCMethodDecl::param_const_iterator P = setter->param_begin();
John McCall31168b02011-06-15 23:02:42 +00007456 LHSTy = (*P)->getType();
7457 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7458 }
John McCall34376a62010-12-04 03:47:34 +00007459 }
7460
John McCall31168b02011-06-15 23:02:42 +00007461 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7462 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007463 InitializedEntity Entity =
John McCall31168b02011-06-15 23:02:42 +00007464 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley01296292011-04-08 18:41:53 +00007465 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCall31168b02011-06-15 23:02:42 +00007466 if (!ArgE.isInvalid()) {
John Wiegley01296292011-04-08 18:41:53 +00007467 RHS = ArgE;
John McCall31168b02011-06-15 23:02:42 +00007468 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7469 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7470 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007471 }
7472}
7473
7474
Anders Carlsson806700f2008-02-01 07:15:58 +00007475/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007476/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007477/// where the declaration is needed for type checking. We only need to
7478/// handle cases when the expression references a function designator
7479/// or is an lvalue. Here are some examples:
7480/// - &(x) => x
7481/// - &*****f => f for f a function designator.
7482/// - &s.xx => s
7483/// - &s.zz[1].yy -> s, if zz is an array
7484/// - *(x + 1) -> x, if x is an array
7485/// - &"123"[2] -> 0
7486/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007487static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007488 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007489 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007490 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007491 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007492 // If this is an arrow operator, the address is an offset from
7493 // the base's value, so the object the base refers to is
7494 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007495 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007496 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007497 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007498 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007499 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007500 // FIXME: This code shouldn't be necessary! We should catch the implicit
7501 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007502 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7503 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7504 if (ICE->getSubExpr()->getType()->isArrayType())
7505 return getPrimaryDecl(ICE->getSubExpr());
7506 }
7507 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007508 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007509 case Stmt::UnaryOperatorClass: {
7510 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007511
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007512 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007513 case UO_Real:
7514 case UO_Imag:
7515 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007516 return getPrimaryDecl(UO->getSubExpr());
7517 default:
7518 return 0;
7519 }
7520 }
Steve Naroff47500512007-04-19 23:00:49 +00007521 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007522 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007523 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007524 // If the result of an implicit cast is an l-value, we care about
7525 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007526 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007527 default:
7528 return 0;
7529 }
7530}
7531
Richard Trieu5f376f62011-09-07 21:46:33 +00007532namespace {
7533 enum {
7534 AO_Bit_Field = 0,
7535 AO_Vector_Element = 1,
7536 AO_Property_Expansion = 2,
7537 AO_Register_Variable = 3,
7538 AO_No_Error = 4
7539 };
7540}
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007541/// \brief Diagnose invalid operand for address of operations.
7542///
7543/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007544static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7545 Expr *E, unsigned Type) {
7546 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7547}
7548
Steve Naroff47500512007-04-19 23:00:49 +00007549/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007550/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007551/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007552/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007553/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007554/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007555/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007556static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7557 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007558 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007559 return S.Context.DependentTy;
7560 if (OrigOp->getType() == S.Context.OverloadTy)
7561 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00007562 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7563 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00007564 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7565 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7566 << OrigOp->getSourceRange();
7567 return QualType();
7568 }
John McCall8d08b9b2010-08-27 09:08:28 +00007569
John McCall2979fe02011-04-12 00:42:48 +00007570 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007571
John McCall8d08b9b2010-08-27 09:08:28 +00007572 // Make sure to ignore parentheses in subsequent checks
7573 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007574
John McCall4bc41ae2010-11-18 19:01:18 +00007575 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007576 // Implement C99-only parts of addressof rules.
7577 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007578 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007579 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7580 // (assuming the deref expression is valid).
7581 return uOp->getSubExpr()->getType();
7582 }
7583 // Technically, there should be a check for array subscript
7584 // expressions here, but the result of one is always an lvalue anyway.
7585 }
John McCallf3a88602011-02-03 08:15:49 +00007586 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007587 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5f376f62011-09-07 21:46:33 +00007588 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +00007589
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007590 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007591 bool sfinae = S.isSFINAEContext();
7592 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7593 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007594 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007595 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007596 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007597 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007598 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007599 } else if (lval == Expr::LV_MemberFunction) {
7600 // If it's an instance method, make a member pointer.
7601 // The expression must have exactly the form &A::foo.
7602
7603 // If the underlying expression isn't a decl ref, give up.
7604 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007605 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007606 << OrigOp->getSourceRange();
7607 return QualType();
7608 }
7609 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7610 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7611
7612 // The id-expression was parenthesized.
7613 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007614 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007615 << OrigOp->getSourceRange();
7616
7617 // The method was named without a qualifier.
7618 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007619 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007620 << op->getSourceRange();
7621 }
7622
John McCall4bc41ae2010-11-18 19:01:18 +00007623 return S.Context.getMemberPointerType(op->getType(),
7624 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007625 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007626 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007627 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007628 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007629 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007630 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007631 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007632 return QualType();
7633 }
John McCall086a4642010-11-24 05:12:34 +00007634 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007635 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +00007636 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +00007637 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007638 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +00007639 AddressOfError = AO_Vector_Element;
John McCall086a4642010-11-24 05:12:34 +00007640 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007641 // cannot take address of a property expression.
Richard Trieu5f376f62011-09-07 21:46:33 +00007642 AddressOfError = AO_Property_Expansion;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007643 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007644 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007645 // with the register storage-class specifier.
7646 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007647 // in C++ it is not error to take address of a register
7648 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007649 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007650 !S.getLangOptions().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +00007651 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +00007652 }
John McCalld14a8642009-11-21 08:51:07 +00007653 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007654 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007655 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007656 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007657 // Could be a pointer to member, though, if there is an explicit
7658 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007659 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007660 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007661 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007662 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007663 S.Diag(OpLoc,
7664 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007665 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007666 return QualType();
7667 }
Mike Stump11289f42009-09-09 15:08:12 +00007668
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007669 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7670 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007671 return S.Context.getMemberPointerType(op->getType(),
7672 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007673 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007674 }
Eli Friedman755c0c92011-08-26 20:28:17 +00007675 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +00007676 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007677 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007678
Richard Trieu5f376f62011-09-07 21:46:33 +00007679 if (AddressOfError != AO_No_Error) {
7680 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7681 return QualType();
7682 }
7683
Eli Friedmance7f9002009-05-16 23:27:50 +00007684 if (lval == Expr::LV_IncompleteVoidType) {
7685 // Taking the address of a void variable is technically illegal, but we
7686 // allow it in cases which are otherwise valid.
7687 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007688 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007689 }
7690
Steve Naroff47500512007-04-19 23:00:49 +00007691 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007692 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007693 return S.Context.getObjCObjectPointerType(op->getType());
7694 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007695}
7696
Chris Lattner9156f1b2010-07-05 19:17:26 +00007697/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007698static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7699 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007700 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007701 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007702
John Wiegley01296292011-04-08 18:41:53 +00007703 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7704 if (ConvResult.isInvalid())
7705 return QualType();
7706 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007707 QualType OpTy = Op->getType();
7708 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007709
7710 if (isa<CXXReinterpretCastExpr>(Op)) {
7711 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7712 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7713 Op->getSourceRange());
7714 }
7715
Chris Lattner9156f1b2010-07-05 19:17:26 +00007716 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7717 // is an incomplete type or void. It would be possible to warn about
7718 // dereferencing a void pointer, but it's completely well-defined, and such a
7719 // warning is unlikely to catch any mistakes.
7720 if (const PointerType *PT = OpTy->getAs<PointerType>())
7721 Result = PT->getPointeeType();
7722 else if (const ObjCObjectPointerType *OPT =
7723 OpTy->getAs<ObjCObjectPointerType>())
7724 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007725 else {
John McCall3aef3d82011-04-10 19:13:55 +00007726 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007727 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007728 if (PR.take() != Op)
7729 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007730 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007731
Chris Lattner9156f1b2010-07-05 19:17:26 +00007732 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007733 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007734 << OpTy << Op->getSourceRange();
7735 return QualType();
7736 }
John McCall4bc41ae2010-11-18 19:01:18 +00007737
7738 // Dereferences are usually l-values...
7739 VK = VK_LValue;
7740
7741 // ...except that certain expressions are never l-values in C.
Douglas Gregor5476205b2011-06-23 00:49:38 +00007742 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007743 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007744
7745 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007746}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007747
John McCalle3027922010-08-25 11:45:40 +00007748static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007749 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007750 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007751 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007752 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007753 case tok::periodstar: Opc = BO_PtrMemD; break;
7754 case tok::arrowstar: Opc = BO_PtrMemI; break;
7755 case tok::star: Opc = BO_Mul; break;
7756 case tok::slash: Opc = BO_Div; break;
7757 case tok::percent: Opc = BO_Rem; break;
7758 case tok::plus: Opc = BO_Add; break;
7759 case tok::minus: Opc = BO_Sub; break;
7760 case tok::lessless: Opc = BO_Shl; break;
7761 case tok::greatergreater: Opc = BO_Shr; break;
7762 case tok::lessequal: Opc = BO_LE; break;
7763 case tok::less: Opc = BO_LT; break;
7764 case tok::greaterequal: Opc = BO_GE; break;
7765 case tok::greater: Opc = BO_GT; break;
7766 case tok::exclaimequal: Opc = BO_NE; break;
7767 case tok::equalequal: Opc = BO_EQ; break;
7768 case tok::amp: Opc = BO_And; break;
7769 case tok::caret: Opc = BO_Xor; break;
7770 case tok::pipe: Opc = BO_Or; break;
7771 case tok::ampamp: Opc = BO_LAnd; break;
7772 case tok::pipepipe: Opc = BO_LOr; break;
7773 case tok::equal: Opc = BO_Assign; break;
7774 case tok::starequal: Opc = BO_MulAssign; break;
7775 case tok::slashequal: Opc = BO_DivAssign; break;
7776 case tok::percentequal: Opc = BO_RemAssign; break;
7777 case tok::plusequal: Opc = BO_AddAssign; break;
7778 case tok::minusequal: Opc = BO_SubAssign; break;
7779 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7780 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7781 case tok::ampequal: Opc = BO_AndAssign; break;
7782 case tok::caretequal: Opc = BO_XorAssign; break;
7783 case tok::pipeequal: Opc = BO_OrAssign; break;
7784 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007785 }
7786 return Opc;
7787}
7788
John McCalle3027922010-08-25 11:45:40 +00007789static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007790 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007791 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007792 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007793 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007794 case tok::plusplus: Opc = UO_PreInc; break;
7795 case tok::minusminus: Opc = UO_PreDec; break;
7796 case tok::amp: Opc = UO_AddrOf; break;
7797 case tok::star: Opc = UO_Deref; break;
7798 case tok::plus: Opc = UO_Plus; break;
7799 case tok::minus: Opc = UO_Minus; break;
7800 case tok::tilde: Opc = UO_Not; break;
7801 case tok::exclaim: Opc = UO_LNot; break;
7802 case tok::kw___real: Opc = UO_Real; break;
7803 case tok::kw___imag: Opc = UO_Imag; break;
7804 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007805 }
7806 return Opc;
7807}
7808
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007809/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7810/// This warning is only emitted for builtin assignment operations. It is also
7811/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007812static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007813 SourceLocation OpLoc) {
7814 if (!S.ActiveTemplateInstantiations.empty())
7815 return;
7816 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7817 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007818 LHSExpr = LHSExpr->IgnoreParenImpCasts();
7819 RHSExpr = RHSExpr->IgnoreParenImpCasts();
7820 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
7821 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
7822 if (!LHSDeclRef || !RHSDeclRef ||
7823 LHSDeclRef->getLocation().isMacroID() ||
7824 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007825 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007826 const ValueDecl *LHSDecl =
7827 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
7828 const ValueDecl *RHSDecl =
7829 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
7830 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007831 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007832 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007833 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007834 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007835 if (RefTy->getPointeeType().isVolatileQualified())
7836 return;
7837
7838 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007839 << LHSDeclRef->getType()
7840 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007841}
7842
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007843/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7844/// operator @p Opc at location @c TokLoc. This routine only supports
7845/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007846ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007847 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007848 Expr *LHSExpr, Expr *RHSExpr) {
7849 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007850 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007851 // The following two variables are used for compound assignment operators
7852 QualType CompLHSTy; // Type of LHS after promotions for computation
7853 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007854 ExprValueKind VK = VK_RValue;
7855 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007856
Douglas Gregor1beec452011-03-12 01:48:56 +00007857 // Check if a 'foo<int>' involved in a binary op, identifies a single
7858 // function unambiguously (i.e. an lvalue ala 13.4)
7859 // But since an assignment can trigger target based overload, exclude it in
7860 // our blind search. i.e:
7861 // template<class T> void f(); template<class T, class U> void f(U);
7862 // f<int> == 0; // resolve f<int> blindly
7863 // void (*p)(int); p = f<int>; // resolve f<int> using target
7864 if (Opc != BO_Assign) {
Richard Trieu4a287fb2011-09-07 01:49:20 +00007865 ExprResult resolvedLHS = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00007866 if (!resolvedLHS.isUsable()) return ExprError();
Richard Trieu4a287fb2011-09-07 01:49:20 +00007867 LHS = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00007868
Richard Trieu4a287fb2011-09-07 01:49:20 +00007869 ExprResult resolvedRHS = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00007870 if (!resolvedRHS.isUsable()) return ExprError();
Richard Trieu4a287fb2011-09-07 01:49:20 +00007871 RHS = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00007872 }
7873
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007874 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007875 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007876 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007877 if (getLangOptions().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +00007878 LHS.get()->getObjectKind() != OK_ObjCProperty) {
7879 VK = LHS.get()->getValueKind();
7880 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007881 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007882 if (!ResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00007883 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007884 break;
John McCalle3027922010-08-25 11:45:40 +00007885 case BO_PtrMemD:
7886 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007887 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007888 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007889 break;
John McCalle3027922010-08-25 11:45:40 +00007890 case BO_Mul:
7891 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007892 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007893 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007894 break;
John McCalle3027922010-08-25 11:45:40 +00007895 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007896 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007897 break;
John McCalle3027922010-08-25 11:45:40 +00007898 case BO_Add:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007899 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007900 break;
John McCalle3027922010-08-25 11:45:40 +00007901 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007902 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007903 break;
John McCalle3027922010-08-25 11:45:40 +00007904 case BO_Shl:
7905 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007906 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007907 break;
John McCalle3027922010-08-25 11:45:40 +00007908 case BO_LE:
7909 case BO_LT:
7910 case BO_GE:
7911 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007912 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007913 break;
John McCalle3027922010-08-25 11:45:40 +00007914 case BO_EQ:
7915 case BO_NE:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007916 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007917 break;
John McCalle3027922010-08-25 11:45:40 +00007918 case BO_And:
7919 case BO_Xor:
7920 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007921 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007922 break;
John McCalle3027922010-08-25 11:45:40 +00007923 case BO_LAnd:
7924 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007925 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007926 break;
John McCalle3027922010-08-25 11:45:40 +00007927 case BO_MulAssign:
7928 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007929 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007930 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007931 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007932 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7933 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007934 break;
John McCalle3027922010-08-25 11:45:40 +00007935 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007936 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007937 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007938 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7939 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007940 break;
John McCalle3027922010-08-25 11:45:40 +00007941 case BO_AddAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007942 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7943 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7944 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007945 break;
John McCalle3027922010-08-25 11:45:40 +00007946 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007947 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7948 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7949 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007950 break;
John McCalle3027922010-08-25 11:45:40 +00007951 case BO_ShlAssign:
7952 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007953 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007954 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007955 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7956 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007957 break;
John McCalle3027922010-08-25 11:45:40 +00007958 case BO_AndAssign:
7959 case BO_XorAssign:
7960 case BO_OrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007961 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007962 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007963 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7964 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007965 break;
John McCalle3027922010-08-25 11:45:40 +00007966 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007967 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
7968 if (getLangOptions().CPlusPlus && !RHS.isInvalid()) {
7969 VK = RHS.get()->getValueKind();
7970 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007971 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007972 break;
7973 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00007974 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007975 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007976
7977 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +00007978 CheckArrayAccess(LHS.get());
7979 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007980
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007981 if (CompResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00007982 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00007983 ResultTy, VK, OK, OpLoc));
Richard Trieu4a287fb2011-09-07 01:49:20 +00007984 if (getLangOptions().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +00007985 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007986 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007987 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007988 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00007989 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00007990 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00007991 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007992}
7993
Sebastian Redl44615072009-10-27 12:10:02 +00007994/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7995/// operators are mixed in a way that suggests that the programmer forgot that
7996/// comparison operators have higher precedence. The most typical example of
7997/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007998static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007999 SourceLocation OpLoc, Expr *LHSExpr,
8000 Expr *RHSExpr) {
Sebastian Redl44615072009-10-27 12:10:02 +00008001 typedef BinaryOperator BinOp;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008002 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8003 RHSopc = static_cast<BinOp::Opcode>(-1);
8004 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8005 LHSopc = BO->getOpcode();
8006 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8007 RHSopc = BO->getOpcode();
Sebastian Redl43028242009-10-26 15:24:15 +00008008
8009 // Subs are not binary operators.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008010 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl43028242009-10-26 15:24:15 +00008011 return;
8012
8013 // Bitwise operations are sometimes used as eager logical ops.
8014 // Don't diagnose this.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008015 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8016 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008017 return;
8018
Richard Trieu4a287fb2011-09-07 01:49:20 +00008019 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8020 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008021 if (!isLeftComp && !isRightComp) return;
8022
Richard Trieu4a287fb2011-09-07 01:49:20 +00008023 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8024 OpLoc)
8025 : SourceRange(OpLoc, RHSExpr->getLocEnd());
8026 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8027 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008028 SourceRange ParensRange = isLeftComp ?
Richard Trieu4a287fb2011-09-07 01:49:20 +00008029 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8030 RHSExpr->getLocEnd())
8031 : SourceRange(LHSExpr->getLocStart(),
8032 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu73088052011-08-10 22:41:34 +00008033
8034 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8035 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8036 SuggestParentheses(Self, OpLoc,
8037 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008038 RHSExpr->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +00008039 SuggestParentheses(Self, OpLoc,
8040 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8041 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00008042}
8043
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008044/// \brief It accepts a '&' expr that is inside a '|' one.
8045/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8046/// in parentheses.
8047static void
8048EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8049 BinaryOperator *Bop) {
8050 assert(Bop->getOpcode() == BO_And);
8051 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8052 << Bop->getSourceRange() << OpLoc;
8053 SuggestParentheses(Self, Bop->getOperatorLoc(),
8054 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8055 Bop->getSourceRange());
8056}
8057
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008058/// \brief It accepts a '&&' expr that is inside a '||' one.
8059/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8060/// in parentheses.
8061static void
8062EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008063 BinaryOperator *Bop) {
8064 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008065 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8066 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008067 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008068 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008069 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008070}
8071
8072/// \brief Returns true if the given expression can be evaluated as a constant
8073/// 'true'.
8074static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8075 bool Res;
8076 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8077}
8078
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008079/// \brief Returns true if the given expression can be evaluated as a constant
8080/// 'false'.
8081static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8082 bool Res;
8083 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8084}
8085
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008086/// \brief Look for '&&' in the left hand of a '||' expr.
8087static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008088 Expr *LHSExpr, Expr *RHSExpr) {
8089 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008090 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008091 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008092 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008093 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008094 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8095 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8096 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8097 } else if (Bop->getOpcode() == BO_LOr) {
8098 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8099 // If it's "a || b && 1 || c" we didn't warn earlier for
8100 // "a || b && 1", but warn now.
8101 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8102 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8103 }
8104 }
8105 }
8106}
8107
8108/// \brief Look for '&&' in the right hand of a '||' expr.
8109static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008110 Expr *LHSExpr, Expr *RHSExpr) {
8111 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008112 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008113 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008114 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008115 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008116 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8117 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8118 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008119 }
8120 }
8121}
8122
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008123/// \brief Look for '&' in the left or right hand of a '|' expr.
8124static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8125 Expr *OrArg) {
8126 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8127 if (Bop->getOpcode() == BO_And)
8128 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8129 }
8130}
8131
Sebastian Redl43028242009-10-26 15:24:15 +00008132/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008133/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008134static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008135 SourceLocation OpLoc, Expr *LHSExpr,
8136 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008137 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008138 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008139 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008140
8141 // Diagnose "arg1 & arg2 | arg3"
8142 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008143 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8144 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008145 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008146
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008147 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8148 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008149 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008150 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8151 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008152 }
Sebastian Redl43028242009-10-26 15:24:15 +00008153}
8154
Steve Naroff218bc2b2007-05-04 21:54:46 +00008155// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008156ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008157 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008158 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +00008159 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008160 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8161 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008162
Sebastian Redl43028242009-10-26 15:24:15 +00008163 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008164 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00008165
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008166 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +00008167}
8168
John McCalldadc5752010-08-24 06:29:42 +00008169ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008170 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008171 Expr *LHSExpr, Expr *RHSExpr) {
John McCall622114c2010-12-06 05:26:58 +00008172 if (getLangOptions().CPlusPlus) {
8173 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008174
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008175 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) {
John McCall622114c2010-12-06 05:26:58 +00008176 UseBuiltinOperator = false;
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008177 } else if (Opc == BO_Assign &&
8178 LHSExpr->getObjectKind() == OK_ObjCProperty) {
John McCall622114c2010-12-06 05:26:58 +00008179 UseBuiltinOperator = true;
8180 } else {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008181 UseBuiltinOperator = !LHSExpr->getType()->isOverloadableType() &&
8182 !RHSExpr->getType()->isOverloadableType();
John McCall622114c2010-12-06 05:26:58 +00008183 }
8184
8185 if (!UseBuiltinOperator) {
8186 // Find all of the overloaded operators visible from this
8187 // point. We perform both an operator-name lookup from the local
8188 // scope and an argument-dependent lookup based on the types of
8189 // the arguments.
8190 UnresolvedSet<16> Functions;
8191 OverloadedOperatorKind OverOp
8192 = BinaryOperator::getOverloadedOperator(Opc);
8193 if (S && OverOp != OO_None)
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008194 LookupOverloadedOperatorName(OverOp, S, LHSExpr->getType(),
8195 RHSExpr->getType(), Functions);
John McCall622114c2010-12-06 05:26:58 +00008196
8197 // Build the (potentially-overloaded, potentially-dependent)
8198 // binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008199 return CreateOverloadedBinOp(OpLoc, Opc, Functions, LHSExpr, RHSExpr);
John McCall622114c2010-12-06 05:26:58 +00008200 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00008201 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008202
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008203 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008204 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008205}
8206
John McCalldadc5752010-08-24 06:29:42 +00008207ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008208 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008209 Expr *InputExpr) {
8210 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008211 ExprValueKind VK = VK_RValue;
8212 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008213 QualType resultType;
8214 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008215 case UO_PreInc:
8216 case UO_PreDec:
8217 case UO_PostInc:
8218 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008219 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008220 Opc == UO_PreInc ||
8221 Opc == UO_PostInc,
8222 Opc == UO_PreInc ||
8223 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008224 break;
John McCalle3027922010-08-25 11:45:40 +00008225 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00008226 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008227 break;
John McCall31996342011-04-07 08:22:57 +00008228 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00008229 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00008230 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008231 Input = move(resolved);
8232 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8233 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008234 break;
John McCall31996342011-04-07 08:22:57 +00008235 }
John McCalle3027922010-08-25 11:45:40 +00008236 case UO_Plus:
8237 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008238 Input = UsualUnaryConversions(Input.take());
8239 if (Input.isInvalid()) return ExprError();
8240 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008241 if (resultType->isDependentType())
8242 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008243 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8244 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008245 break;
8246 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8247 resultType->isEnumeralType())
8248 break;
8249 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008250 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008251 resultType->isPointerType())
8252 break;
John McCall36226622010-10-12 02:09:17 +00008253 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008254 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008255 if (Input.isInvalid()) return ExprError();
8256 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008257 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008258
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008259 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008260 << resultType << Input.get()->getSourceRange());
8261
John McCalle3027922010-08-25 11:45:40 +00008262 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008263 Input = UsualUnaryConversions(Input.take());
8264 if (Input.isInvalid()) return ExprError();
8265 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008266 if (resultType->isDependentType())
8267 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008268 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8269 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8270 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008271 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008272 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008273 else if (resultType->hasIntegerRepresentation())
8274 break;
8275 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008276 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008277 if (Input.isInvalid()) return ExprError();
8278 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008279 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008280 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008281 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008282 }
Steve Naroff35d85152007-05-07 00:24:15 +00008283 break;
John Wiegley01296292011-04-08 18:41:53 +00008284
John McCalle3027922010-08-25 11:45:40 +00008285 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008286 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008287 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8288 if (Input.isInvalid()) return ExprError();
8289 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008290 if (resultType->isDependentType())
8291 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008292 if (resultType->isScalarType()) {
8293 // C99 6.5.3.3p1: ok, fallthrough;
8294 if (Context.getLangOptions().CPlusPlus) {
8295 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8296 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008297 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8298 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008299 }
John McCall36226622010-10-12 02:09:17 +00008300 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008301 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008302 if (Input.isInvalid()) return ExprError();
8303 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008304 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008305 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008306 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008307 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008308
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008309 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008310 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008311 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008312 break;
John McCalle3027922010-08-25 11:45:40 +00008313 case UO_Real:
8314 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008315 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008316 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00008317 if (Input.isInvalid()) return ExprError();
8318 if (Input.get()->getValueKind() != VK_RValue &&
8319 Input.get()->getObjectKind() == OK_Ordinary)
8320 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008321 break;
John McCalle3027922010-08-25 11:45:40 +00008322 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008323 resultType = Input.get()->getType();
8324 VK = Input.get()->getValueKind();
8325 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008326 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008327 }
John Wiegley01296292011-04-08 18:41:53 +00008328 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008329 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008330
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008331 // Check for array bounds violations in the operand of the UnaryOperator,
8332 // except for the '*' and '&' operators that have to be handled specially
8333 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8334 // that are explicitly defined as valid by the standard).
8335 if (Opc != UO_AddrOf && Opc != UO_Deref)
8336 CheckArrayAccess(Input.get());
8337
John Wiegley01296292011-04-08 18:41:53 +00008338 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008339 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008340}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008341
John McCalldadc5752010-08-24 06:29:42 +00008342ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008343 UnaryOperatorKind Opc, Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008344 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008345 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008346 // Find all of the overloaded operators visible from this
8347 // point. We perform both an operator-name lookup from the local
8348 // scope and an argument-dependent lookup based on the types of
8349 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008350 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008351 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008352 if (S && OverOp != OO_None)
8353 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8354 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008355
John McCallb268a282010-08-23 23:25:46 +00008356 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008357 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008358
John McCallb268a282010-08-23 23:25:46 +00008359 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008360}
8361
Douglas Gregor5287f092009-11-05 00:51:44 +00008362// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008363ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008364 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008365 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008366}
8367
Steve Naroff66356bd2007-09-16 14:56:35 +00008368/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008369ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008370 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008371 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008372 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008373 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008374 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008375}
8376
John McCall31168b02011-06-15 23:02:42 +00008377/// Given the last statement in a statement-expression, check whether
8378/// the result is a producing expression (like a call to an
8379/// ns_returns_retained function) and, if so, rebuild it to hoist the
8380/// release out of the full-expression. Otherwise, return null.
8381/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +00008382static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +00008383 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +00008384 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCall31168b02011-06-15 23:02:42 +00008385 if (!cleanups) return 0;
8386
8387 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +00008388 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCall31168b02011-06-15 23:02:42 +00008389 return 0;
8390
8391 // Splice out the cast. This shouldn't modify any interesting
8392 // features of the statement.
8393 Expr *producer = cast->getSubExpr();
8394 assert(producer->getType() == cast->getType());
8395 assert(producer->getValueKind() == cast->getValueKind());
8396 cleanups->setSubExpr(producer);
8397 return cleanups;
8398}
8399
John McCalldadc5752010-08-24 06:29:42 +00008400ExprResult
John McCallb268a282010-08-23 23:25:46 +00008401Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008402 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008403 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8404 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8405
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008406 bool isFileScope
8407 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008408 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008409 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008410
Chris Lattner366727f2007-07-24 16:58:17 +00008411 // FIXME: there are a variety of strange constraints to enforce here, for
8412 // example, it is not possible to goto into a stmt expression apparently.
8413 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008414
Chris Lattner366727f2007-07-24 16:58:17 +00008415 // If there are sub stmts in the compound stmt, take the type of the last one
8416 // as the type of the stmtexpr.
8417 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008418 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008419 if (!Compound->body_empty()) {
8420 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008421 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008422 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008423 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8424 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008425 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008426 }
John McCall31168b02011-06-15 23:02:42 +00008427
John Wiegley01296292011-04-08 18:41:53 +00008428 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008429 // Do function/array conversion on the last expression, but not
8430 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008431 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8432 if (LastExpr.isInvalid())
8433 return ExprError();
8434 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008435
John Wiegley01296292011-04-08 18:41:53 +00008436 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008437 // In ARC, if the final expression ends in a consume, splice
8438 // the consume out and bind it later. In the alternate case
8439 // (when dealing with a retainable type), the result
8440 // initialization will create a produce. In both cases the
8441 // result will be +1, and we'll need to balance that out with
8442 // a bind.
8443 if (Expr *rebuiltLastStmt
8444 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8445 LastExpr = rebuiltLastStmt;
8446 } else {
8447 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008448 InitializedEntity::InitializeResult(LPLoc,
8449 Ty,
8450 false),
8451 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008452 LastExpr);
8453 }
8454
John Wiegley01296292011-04-08 18:41:53 +00008455 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008456 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008457 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008458 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008459 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008460 else
John Wiegley01296292011-04-08 18:41:53 +00008461 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008462 StmtExprMayBindToTemp = true;
8463 }
8464 }
8465 }
Chris Lattner944d3062008-07-26 19:51:01 +00008466 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008467
Eli Friedmanba961a92009-03-23 00:24:07 +00008468 // FIXME: Check that expression type is complete/non-abstract; statement
8469 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008470 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8471 if (StmtExprMayBindToTemp)
8472 return MaybeBindToTemporary(ResStmtExpr);
8473 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008474}
Steve Naroff78864672007-08-01 22:05:33 +00008475
John McCalldadc5752010-08-24 06:29:42 +00008476ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008477 TypeSourceInfo *TInfo,
8478 OffsetOfComponent *CompPtr,
8479 unsigned NumComponents,
8480 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008481 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008482 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008483 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008484
Chris Lattnerf17bd422007-08-30 17:45:32 +00008485 // We must have at least one component that refers to the type, and the first
8486 // one is known to be a field designator. Verify that the ArgTy represents
8487 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008488 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008489 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8490 << ArgTy << TypeRange);
8491
8492 // Type must be complete per C99 7.17p3 because a declaring a variable
8493 // with an incomplete type would be ill-formed.
8494 if (!Dependent
8495 && RequireCompleteType(BuiltinLoc, ArgTy,
8496 PDiag(diag::err_offsetof_incomplete_type)
8497 << TypeRange))
8498 return ExprError();
8499
Chris Lattner78502cf2007-08-31 21:49:13 +00008500 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8501 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008502 // FIXME: This diagnostic isn't actually visible because the location is in
8503 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008504 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008505 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8506 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008507
8508 bool DidWarnAboutNonPOD = false;
8509 QualType CurrentType = ArgTy;
8510 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008511 SmallVector<OffsetOfNode, 4> Comps;
8512 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008513 for (unsigned i = 0; i != NumComponents; ++i) {
8514 const OffsetOfComponent &OC = CompPtr[i];
8515 if (OC.isBrackets) {
8516 // Offset of an array sub-field. TODO: Should we allow vector elements?
8517 if (!CurrentType->isDependentType()) {
8518 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8519 if(!AT)
8520 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8521 << CurrentType);
8522 CurrentType = AT->getElementType();
8523 } else
8524 CurrentType = Context.DependentTy;
8525
8526 // The expression must be an integral expression.
8527 // FIXME: An integral constant expression?
8528 Expr *Idx = static_cast<Expr*>(OC.U.E);
8529 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8530 !Idx->getType()->isIntegerType())
8531 return ExprError(Diag(Idx->getLocStart(),
8532 diag::err_typecheck_subscript_not_integer)
8533 << Idx->getSourceRange());
8534
8535 // Record this array index.
8536 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8537 Exprs.push_back(Idx);
8538 continue;
8539 }
8540
8541 // Offset of a field.
8542 if (CurrentType->isDependentType()) {
8543 // We have the offset of a field, but we can't look into the dependent
8544 // type. Just record the identifier of the field.
8545 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8546 CurrentType = Context.DependentTy;
8547 continue;
8548 }
8549
8550 // We need to have a complete type to look into.
8551 if (RequireCompleteType(OC.LocStart, CurrentType,
8552 diag::err_offsetof_incomplete_type))
8553 return ExprError();
8554
8555 // Look for the designated field.
8556 const RecordType *RC = CurrentType->getAs<RecordType>();
8557 if (!RC)
8558 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8559 << CurrentType);
8560 RecordDecl *RD = RC->getDecl();
8561
8562 // C++ [lib.support.types]p5:
8563 // The macro offsetof accepts a restricted set of type arguments in this
8564 // International Standard. type shall be a POD structure or a POD union
8565 // (clause 9).
8566 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8567 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008568 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008569 PDiag(diag::warn_offsetof_non_pod_type)
8570 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8571 << CurrentType))
8572 DidWarnAboutNonPOD = true;
8573 }
8574
8575 // Look for the field.
8576 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8577 LookupQualifiedName(R, RD);
8578 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008579 IndirectFieldDecl *IndirectMemberDecl = 0;
8580 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008581 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008582 MemberDecl = IndirectMemberDecl->getAnonField();
8583 }
8584
Douglas Gregor882211c2010-04-28 22:16:22 +00008585 if (!MemberDecl)
8586 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8587 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8588 OC.LocEnd));
8589
Douglas Gregor10982ea2010-04-28 22:36:06 +00008590 // C99 7.17p3:
8591 // (If the specified member is a bit-field, the behavior is undefined.)
8592 //
8593 // We diagnose this as an error.
8594 if (MemberDecl->getBitWidth()) {
8595 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8596 << MemberDecl->getDeclName()
8597 << SourceRange(BuiltinLoc, RParenLoc);
8598 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8599 return ExprError();
8600 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008601
8602 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008603 if (IndirectMemberDecl)
8604 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008605
Douglas Gregord1702062010-04-29 00:18:15 +00008606 // If the member was found in a base class, introduce OffsetOfNodes for
8607 // the base class indirections.
8608 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8609 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008610 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008611 CXXBasePath &Path = Paths.front();
8612 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8613 B != BEnd; ++B)
8614 Comps.push_back(OffsetOfNode(B->Base));
8615 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008616
Francois Pichet783dd6e2010-11-21 06:08:52 +00008617 if (IndirectMemberDecl) {
8618 for (IndirectFieldDecl::chain_iterator FI =
8619 IndirectMemberDecl->chain_begin(),
8620 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8621 assert(isa<FieldDecl>(*FI));
8622 Comps.push_back(OffsetOfNode(OC.LocStart,
8623 cast<FieldDecl>(*FI), OC.LocEnd));
8624 }
8625 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008626 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008627
Douglas Gregor882211c2010-04-28 22:16:22 +00008628 CurrentType = MemberDecl->getType().getNonReferenceType();
8629 }
8630
8631 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8632 TInfo, Comps.data(), Comps.size(),
8633 Exprs.data(), Exprs.size(), RParenLoc));
8634}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008635
John McCalldadc5752010-08-24 06:29:42 +00008636ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008637 SourceLocation BuiltinLoc,
8638 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008639 ParsedType ParsedArgTy,
John McCall36226622010-10-12 02:09:17 +00008640 OffsetOfComponent *CompPtr,
8641 unsigned NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008642 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +00008643
Douglas Gregor882211c2010-04-28 22:16:22 +00008644 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00008645 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +00008646 if (ArgTy.isNull())
8647 return ExprError();
8648
Eli Friedman06dcfd92010-08-05 10:15:45 +00008649 if (!ArgTInfo)
8650 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8651
8652 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008653 RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008654}
8655
8656
John McCalldadc5752010-08-24 06:29:42 +00008657ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008658 Expr *CondExpr,
8659 Expr *LHSExpr, Expr *RHSExpr,
8660 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008661 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8662
John McCall7decc9e2010-11-18 06:31:45 +00008663 ExprValueKind VK = VK_RValue;
8664 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008665 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008666 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008667 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008668 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008669 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008670 } else {
8671 // The conditional expression is required to be a constant expression.
8672 llvm::APSInt condEval(32);
8673 SourceLocation ExpLoc;
8674 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008675 return ExprError(Diag(ExpLoc,
8676 diag::err_typecheck_choose_expr_requires_constant)
8677 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008678
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008679 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008680 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8681
8682 resType = ActiveExpr->getType();
8683 ValueDependent = ActiveExpr->isValueDependent();
8684 VK = ActiveExpr->getValueKind();
8685 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008686 }
8687
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008688 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008689 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008690 resType->isDependentType(),
8691 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008692}
8693
Steve Naroffc540d662008-09-03 18:15:37 +00008694//===----------------------------------------------------------------------===//
8695// Clang Extensions.
8696//===----------------------------------------------------------------------===//
8697
8698/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +00008699void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008700 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuba63ce62011-09-09 01:45:06 +00008701 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008702 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +00008703 if (CurScope)
8704 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008705 else
8706 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008707}
8708
Mike Stump82f071f2009-02-04 22:31:32 +00008709void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008710 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008711 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008712 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008713
John McCall8cb7bdf2010-06-04 23:28:52 +00008714 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008715 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008716
John McCall3882ace2011-01-05 12:14:39 +00008717 // GetTypeForDeclarator always produces a function type for a block
8718 // literal signature. Furthermore, it is always a FunctionProtoType
8719 // unless the function was written with a typedef.
8720 assert(T->isFunctionType() &&
8721 "GetTypeForDeclarator made a non-function block signature");
8722
8723 // Look for an explicit signature in that function type.
8724 FunctionProtoTypeLoc ExplicitSignature;
8725
8726 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8727 if (isa<FunctionProtoTypeLoc>(tmp)) {
8728 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8729
8730 // Check whether that explicit signature was synthesized by
8731 // GetTypeForDeclarator. If so, don't save that as part of the
8732 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008733 if (ExplicitSignature.getLocalRangeBegin() ==
8734 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008735 // This would be much cheaper if we stored TypeLocs instead of
8736 // TypeSourceInfos.
8737 TypeLoc Result = ExplicitSignature.getResultLoc();
8738 unsigned Size = Result.getFullDataSize();
8739 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8740 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8741
8742 ExplicitSignature = FunctionProtoTypeLoc();
8743 }
John McCalla3ccba02010-06-04 11:21:44 +00008744 }
Mike Stump11289f42009-09-09 15:08:12 +00008745
John McCall3882ace2011-01-05 12:14:39 +00008746 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8747 CurBlock->FunctionType = T;
8748
8749 const FunctionType *Fn = T->getAs<FunctionType>();
8750 QualType RetTy = Fn->getResultType();
8751 bool isVariadic =
8752 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8753
John McCall8e346702010-06-04 19:02:56 +00008754 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008755
John McCalla3ccba02010-06-04 11:21:44 +00008756 // Don't allow returning a objc interface by value.
8757 if (RetTy->isObjCObjectType()) {
8758 Diag(ParamInfo.getSourceRange().getBegin(),
8759 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8760 return;
8761 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008762
John McCalla3ccba02010-06-04 11:21:44 +00008763 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008764 // return type. TODO: what should we do with declarators like:
8765 // ^ * { ... }
8766 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008767 if (RetTy != Context.DependentTy)
8768 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008769
John McCalla3ccba02010-06-04 11:21:44 +00008770 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008771 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008772 if (ExplicitSignature) {
8773 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8774 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008775 if (Param->getIdentifier() == 0 &&
8776 !Param->isImplicit() &&
8777 !Param->isInvalidDecl() &&
8778 !getLangOptions().CPlusPlus)
8779 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008780 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008781 }
John McCalla3ccba02010-06-04 11:21:44 +00008782
8783 // Fake up parameter variables if we have a typedef, like
8784 // ^ fntype { ... }
8785 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8786 for (FunctionProtoType::arg_type_iterator
8787 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8788 ParmVarDecl *Param =
8789 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8790 ParamInfo.getSourceRange().getBegin(),
8791 *I);
John McCall8e346702010-06-04 19:02:56 +00008792 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008793 }
Steve Naroffc540d662008-09-03 18:15:37 +00008794 }
John McCalla3ccba02010-06-04 11:21:44 +00008795
John McCall8e346702010-06-04 19:02:56 +00008796 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008797 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +00008798 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +00008799 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8800 CurBlock->TheDecl->param_end(),
8801 /*CheckParameterNames=*/false);
8802 }
8803
John McCalla3ccba02010-06-04 11:21:44 +00008804 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008805 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008806
John McCall8e346702010-06-04 19:02:56 +00008807 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008808 Diag(ParamInfo.getAttributes()->getLoc(),
8809 diag::warn_attribute_sentinel_not_variadic) << 1;
8810 // FIXME: remove the attribute.
8811 }
8812
8813 // Put the parameter variables in scope. We can bail out immediately
8814 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008815 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008816 return;
8817
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008818 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008819 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8820 (*AI)->setOwningFunction(CurBlock->TheDecl);
8821
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008822 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008823 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008824 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008825
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008826 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008827 }
John McCallf7b2fb52010-01-22 00:28:27 +00008828 }
Steve Naroffc540d662008-09-03 18:15:37 +00008829}
8830
8831/// ActOnBlockError - If there is an error parsing a block, this callback
8832/// is invoked to pop the information about the block from the action impl.
8833void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008834 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008835 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008836 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008837}
8838
8839/// ActOnBlockStmtExpr - This is called when the body of a block statement
8840/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008841ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008842 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008843 // If blocks are disabled, emit an error.
8844 if (!LangOpts.Blocks)
8845 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008846
Douglas Gregor9a28e842010-03-01 23:15:13 +00008847 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008848
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008849 PopDeclContext();
8850
Steve Naroffc540d662008-09-03 18:15:37 +00008851 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008852 if (!BSI->ReturnType.isNull())
8853 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008854
Mike Stump3bf1ab42009-07-28 22:04:01 +00008855 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008856 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008857
John McCallc63de662011-02-02 13:00:07 +00008858 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008859 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8860 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00008861
John McCall8e346702010-06-04 19:02:56 +00008862 // If the user wrote a function type in some form, try to use that.
8863 if (!BSI->FunctionType.isNull()) {
8864 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8865
8866 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8867 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8868
8869 // Turn protoless block types into nullary block types.
8870 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008871 FunctionProtoType::ExtProtoInfo EPI;
8872 EPI.ExtInfo = Ext;
8873 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008874
8875 // Otherwise, if we don't need to change anything about the function type,
8876 // preserve its sugar structure.
8877 } else if (FTy->getResultType() == RetTy &&
8878 (!NoReturn || FTy->getNoReturnAttr())) {
8879 BlockTy = BSI->FunctionType;
8880
8881 // Otherwise, make the minimal modifications to the function type.
8882 } else {
8883 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008884 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8885 EPI.TypeQuals = 0; // FIXME: silently?
8886 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008887 BlockTy = Context.getFunctionType(RetTy,
8888 FPT->arg_type_begin(),
8889 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008890 EPI);
John McCall8e346702010-06-04 19:02:56 +00008891 }
8892
8893 // If we don't have a function type, just build one from nothing.
8894 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008895 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00008896 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008897 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008898 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008899
John McCall8e346702010-06-04 19:02:56 +00008900 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8901 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008902 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008903
Chris Lattner45542ea2009-04-19 05:28:12 +00008904 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00008905 if (getCurFunction()->NeedsScopeChecking() &&
8906 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008907 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008908
Chris Lattner60f84492011-02-17 23:58:47 +00008909 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008910
Fariborz Jahanian256d39d2011-07-11 18:04:54 +00008911 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8912 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8913 const VarDecl *variable = ci->getVariable();
8914 QualType T = variable->getType();
8915 QualType::DestructionKind destructKind = T.isDestructedType();
8916 if (destructKind != QualType::DK_none)
8917 getCurFunction()->setHasBranchProtectedScope();
8918 }
8919
Douglas Gregor49695f02011-09-06 20:46:03 +00008920 computeNRVO(Body, getCurBlock());
8921
Benjamin Kramera4fb8362011-07-12 14:11:05 +00008922 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8923 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8924 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8925
Douglas Gregor9a28e842010-03-01 23:15:13 +00008926 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008927}
8928
John McCalldadc5752010-08-24 06:29:42 +00008929ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008930 Expr *E, ParsedType Ty,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008931 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008932 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00008933 GetTypeFromParser(Ty, &TInfo);
8934 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008935}
8936
John McCalldadc5752010-08-24 06:29:42 +00008937ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008938 Expr *E, TypeSourceInfo *TInfo,
8939 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008940 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008941
Eli Friedman121ba0c2008-08-09 23:32:40 +00008942 // Get the va_list type
8943 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008944 if (VaListType->isArrayType()) {
8945 // Deal with implicit array decay; for example, on x86-64,
8946 // va_list is an array, but it's supposed to decay to
8947 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008948 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008949 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00008950 ExprResult Result = UsualUnaryConversions(E);
8951 if (Result.isInvalid())
8952 return ExprError();
8953 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00008954 } else {
8955 // Otherwise, the va_list argument must be an l-value because
8956 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008957 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008958 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008959 return ExprError();
8960 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008961
Douglas Gregorad3150c2009-05-19 23:10:31 +00008962 if (!E->isTypeDependent() &&
8963 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008964 return ExprError(Diag(E->getLocStart(),
8965 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008966 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008967 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008968
David Majnemerc75d1a12011-06-14 05:17:32 +00008969 if (!TInfo->getType()->isDependentType()) {
8970 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8971 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8972 << TInfo->getTypeLoc().getSourceRange()))
8973 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00008974
David Majnemerc75d1a12011-06-14 05:17:32 +00008975 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8976 TInfo->getType(),
8977 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8978 << TInfo->getTypeLoc().getSourceRange()))
8979 return ExprError();
8980
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008981 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00008982 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008983 TInfo->getType()->isObjCLifetimeType()
8984 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8985 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00008986 << TInfo->getType()
8987 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008988 }
Eli Friedman6290ae42011-07-11 21:45:59 +00008989
8990 // Check for va_arg where arguments of the given type will be promoted
8991 // (i.e. this va_arg is guaranteed to have undefined behavior).
8992 QualType PromoteType;
8993 if (TInfo->getType()->isPromotableIntegerType()) {
8994 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8995 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8996 PromoteType = QualType();
8997 }
8998 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8999 PromoteType = Context.DoubleTy;
9000 if (!PromoteType.isNull())
9001 Diag(TInfo->getTypeLoc().getBeginLoc(),
9002 diag::warn_second_parameter_to_va_arg_never_compatible)
9003 << TInfo->getType()
9004 << PromoteType
9005 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00009006 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009007
Abramo Bagnara27db2392010-08-10 10:06:15 +00009008 QualType T = TInfo->getType().getNonLValueExprType(Context);
9009 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009010}
9011
John McCalldadc5752010-08-24 06:29:42 +00009012ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009013 // The type of __null will be int or long, depending on the size of
9014 // pointers on the target.
9015 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009016 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9017 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009018 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009019 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009020 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009021 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009022 Ty = Context.LongLongTy;
9023 else {
David Blaikie83d382b2011-09-23 05:06:16 +00009024 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009025 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009026
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009027 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009028}
9029
Alexis Huntc46382e2010-04-28 23:02:27 +00009030static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009031 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00009032 if (!SemaRef.getLangOptions().ObjC1)
9033 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009034
Anders Carlssonace5d072009-11-10 04:46:30 +00009035 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9036 if (!PT)
9037 return;
9038
9039 // Check if the destination is of type 'id'.
9040 if (!PT->isObjCIdType()) {
9041 // Check if the destination is the 'NSString' interface.
9042 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9043 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9044 return;
9045 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009046
Anders Carlssonace5d072009-11-10 04:46:30 +00009047 // Strip off any parens and casts.
9048 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregorfb65e592011-07-27 05:40:30 +00009049 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00009050 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009051
Douglas Gregora771f462010-03-31 17:46:05 +00009052 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009053}
9054
Chris Lattner9bad62c2008-01-04 18:04:52 +00009055bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9056 SourceLocation Loc,
9057 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009058 Expr *SrcExpr, AssignmentAction Action,
9059 bool *Complained) {
9060 if (Complained)
9061 *Complained = false;
9062
Chris Lattner9bad62c2008-01-04 18:04:52 +00009063 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00009064 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009065 bool isInvalid = false;
9066 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00009067 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00009068 ConversionFixItGenerator ConvHints;
9069 bool MayHaveConvFixit = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009070
Chris Lattner9bad62c2008-01-04 18:04:52 +00009071 switch (ConvTy) {
David Blaikie83d382b2011-09-23 05:06:16 +00009072 default: llvm_unreachable("Unknown conversion type");
Chris Lattner9bad62c2008-01-04 18:04:52 +00009073 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009074 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009075 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00009076 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9077 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009078 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009079 case IntToPointer:
9080 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00009081 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9082 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009083 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009084 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009085 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009086 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00009087 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9088 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00009089 if (Hint.isNull() && !CheckInferredResultType) {
9090 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9091 }
9092 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009093 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009094 case IncompatiblePointerSign:
9095 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9096 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009097 case FunctionVoidPointer:
9098 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9099 break;
John McCall4fff8f62011-02-01 00:10:29 +00009100 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009101 // Perform array-to-pointer decay if necessary.
9102 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9103
John McCall4fff8f62011-02-01 00:10:29 +00009104 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9105 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9106 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9107 DiagKind = diag::err_typecheck_incompatible_address_space;
9108 break;
John McCall31168b02011-06-15 23:02:42 +00009109
9110
9111 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009112 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00009113 break;
John McCall4fff8f62011-02-01 00:10:29 +00009114 }
9115
9116 llvm_unreachable("unknown error case for discarding qualifiers!");
9117 // fallthrough
9118 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009119 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009120 // If the qualifiers lost were because we were applying the
9121 // (deprecated) C++ conversion from a string literal to a char*
9122 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9123 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009124 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009125 // bit of refactoring (so that the second argument is an
9126 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009127 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009128 // C++ semantics.
9129 if (getLangOptions().CPlusPlus &&
9130 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9131 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009132 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9133 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009134 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009135 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009136 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009137 case IntToBlockPointer:
9138 DiagKind = diag::err_int_to_block_pointer;
9139 break;
9140 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009141 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009142 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009143 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009144 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009145 // it can give a more specific diagnostic.
9146 DiagKind = diag::warn_incompatible_qualified_id;
9147 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009148 case IncompatibleVectors:
9149 DiagKind = diag::warn_incompatible_vectors;
9150 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00009151 case IncompatibleObjCWeakRef:
9152 DiagKind = diag::err_arc_weak_unavailable_assign;
9153 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009154 case Incompatible:
9155 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00009156 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9157 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009158 isInvalid = true;
9159 break;
9160 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009161
Douglas Gregorc68e1402010-04-09 00:35:39 +00009162 QualType FirstType, SecondType;
9163 switch (Action) {
9164 case AA_Assigning:
9165 case AA_Initializing:
9166 // The destination type comes first.
9167 FirstType = DstType;
9168 SecondType = SrcType;
9169 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009170
Douglas Gregorc68e1402010-04-09 00:35:39 +00009171 case AA_Returning:
9172 case AA_Passing:
9173 case AA_Converting:
9174 case AA_Sending:
9175 case AA_Casting:
9176 // The source type comes first.
9177 FirstType = SrcType;
9178 SecondType = DstType;
9179 break;
9180 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009181
Anna Zaks3b402712011-07-28 19:51:27 +00009182 PartialDiagnostic FDiag = PDiag(DiagKind);
9183 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9184
9185 // If we can fix the conversion, suggest the FixIts.
9186 assert(ConvHints.isNull() || Hint.isNull());
9187 if (!ConvHints.isNull()) {
9188 for (llvm::SmallVector<FixItHint, 1>::iterator
9189 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
9190 HI != HE; ++HI)
9191 FDiag << *HI;
9192 } else {
9193 FDiag << Hint;
9194 }
9195 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9196
9197 Diag(Loc, FDiag);
9198
Douglas Gregor33823722011-06-11 01:09:30 +00009199 if (CheckInferredResultType)
9200 EmitRelatedResultTypeNote(SrcExpr);
9201
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009202 if (Complained)
9203 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009204 return isInvalid;
9205}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009206
Chris Lattnerc71d08b2009-04-25 21:59:05 +00009207bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009208 llvm::APSInt ICEResult;
9209 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9210 if (Result)
9211 *Result = ICEResult;
9212 return false;
9213 }
9214
Anders Carlssone54e8a12008-11-30 19:50:32 +00009215 Expr::EvalResult EvalResult;
9216
Mike Stump4e1f26a2009-02-19 03:04:26 +00009217 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00009218 EvalResult.HasSideEffects) {
9219 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9220
9221 if (EvalResult.Diag) {
9222 // We only show the note if it's not the usual "invalid subexpression"
9223 // or if it's actually in a subexpression.
9224 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9225 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9226 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9227 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009228
Anders Carlssone54e8a12008-11-30 19:50:32 +00009229 return true;
9230 }
9231
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009232 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9233 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009234
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009235 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009236 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
David Blaikie9c902b52011-09-25 23:23:43 +00009237 != DiagnosticsEngine::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009238 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009239
Anders Carlssone54e8a12008-11-30 19:50:32 +00009240 if (Result)
9241 *Result = EvalResult.Val.getInt();
9242 return false;
9243}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009244
Douglas Gregorff790f12009-11-26 00:44:06 +00009245void
Mike Stump11289f42009-09-09 15:08:12 +00009246Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009247 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00009248 ExpressionEvaluationContextRecord(NewContext,
9249 ExprTemporaries.size(),
9250 ExprNeedsCleanups));
9251 ExprNeedsCleanups = false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009252}
9253
Richard Trieucfc491d2011-08-02 04:35:43 +00009254void Sema::PopExpressionEvaluationContext() {
Douglas Gregorff790f12009-11-26 00:44:06 +00009255 // Pop the current expression evaluation context off the stack.
9256 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9257 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009258
Douglas Gregorfab31f42009-12-12 07:57:52 +00009259 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9260 if (Rec.PotentiallyReferenced) {
9261 // Mark any remaining declarations in the current position of the stack
9262 // as "referenced". If they were not meant to be referenced, semantic
9263 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009264 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009265 I = Rec.PotentiallyReferenced->begin(),
9266 IEnd = Rec.PotentiallyReferenced->end();
9267 I != IEnd; ++I)
9268 MarkDeclarationReferenced(I->first, I->second);
9269 }
9270
9271 if (Rec.PotentiallyDiagnosed) {
9272 // Emit any pending diagnostics.
9273 for (PotentiallyEmittedDiagnostics::iterator
9274 I = Rec.PotentiallyDiagnosed->begin(),
9275 IEnd = Rec.PotentiallyDiagnosed->end();
9276 I != IEnd; ++I)
9277 Diag(I->first, I->second);
9278 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009279 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009280
9281 // When are coming out of an unevaluated context, clear out any
9282 // temporaries that we may have created as part of the evaluation of
9283 // the expression in that context: they aren't relevant because they
9284 // will never be constructed.
John McCall31168b02011-06-15 23:02:42 +00009285 if (Rec.Context == Unevaluated) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009286 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9287 ExprTemporaries.end());
John McCall31168b02011-06-15 23:02:42 +00009288 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9289
9290 // Otherwise, merge the contexts together.
9291 } else {
9292 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9293 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009294
9295 // Destroy the popped expression evaluation record.
9296 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009297}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009298
John McCall31168b02011-06-15 23:02:42 +00009299void Sema::DiscardCleanupsInEvaluationContext() {
9300 ExprTemporaries.erase(
9301 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
9302 ExprTemporaries.end());
9303 ExprNeedsCleanups = false;
9304}
9305
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009306/// \brief Note that the given declaration was referenced in the source code.
9307///
9308/// This routine should be invoke whenever a given declaration is referenced
9309/// in the source code, and where that reference occurred. If this declaration
9310/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9311/// C99 6.9p3), then the declaration will be marked as used.
9312///
9313/// \param Loc the location where the declaration was referenced.
9314///
9315/// \param D the declaration that has been referenced by the source code.
9316void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9317 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009318
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00009319 D->setReferenced();
9320
Douglas Gregorebada0772010-06-17 23:14:26 +00009321 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009322 return;
Mike Stump11289f42009-09-09 15:08:12 +00009323
Richard Trieucfc491d2011-08-02 04:35:43 +00009324 // Mark a parameter or variable declaration "used", regardless of whether
9325 // we're in a template or not. The reason for this is that unevaluated
9326 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9327 // (-Wunused-variables and -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009328 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009329 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009330 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009331 return;
9332 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009333
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009334 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9335 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009336
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009337 // Do not mark anything as "used" within a dependent context; wait for
9338 // an instantiation.
9339 if (CurContext->isDependentContext())
9340 return;
Mike Stump11289f42009-09-09 15:08:12 +00009341
Douglas Gregorff790f12009-11-26 00:44:06 +00009342 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009343 case Unevaluated:
9344 // We are in an expression that is not potentially evaluated; do nothing.
9345 return;
Mike Stump11289f42009-09-09 15:08:12 +00009346
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009347 case PotentiallyEvaluated:
9348 // We are in a potentially-evaluated expression, so this declaration is
9349 // "used"; handle this below.
9350 break;
Mike Stump11289f42009-09-09 15:08:12 +00009351
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009352 case PotentiallyPotentiallyEvaluated:
9353 // We are in an expression that may be potentially evaluated; queue this
9354 // declaration reference until we know whether the expression is
9355 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009356 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009357 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009358
9359 case PotentiallyEvaluatedIfUsed:
9360 // Referenced declarations will only be used if the construct in the
9361 // containing expression is used.
9362 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009363 }
Mike Stump11289f42009-09-09 15:08:12 +00009364
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009365 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009366 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009367 if (Constructor->isDefaulted()) {
9368 if (Constructor->isDefaultConstructor()) {
9369 if (Constructor->isTrivial())
9370 return;
9371 if (!Constructor->isUsed(false))
9372 DefineImplicitDefaultConstructor(Loc, Constructor);
9373 } else if (Constructor->isCopyConstructor()) {
9374 if (!Constructor->isUsed(false))
9375 DefineImplicitCopyConstructor(Loc, Constructor);
9376 } else if (Constructor->isMoveConstructor()) {
9377 if (!Constructor->isUsed(false))
9378 DefineImplicitMoveConstructor(Loc, Constructor);
9379 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009380 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009381
Douglas Gregor88d292c2010-05-13 16:44:06 +00009382 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009383 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Alexis Huntf91729462011-05-12 22:46:25 +00009384 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009385 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009386 if (Destructor->isVirtual())
9387 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009388 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Alexis Huntc9a55732011-05-14 05:23:28 +00009389 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009390 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009391 if (!MethodDecl->isUsed(false)) {
9392 if (MethodDecl->isCopyAssignmentOperator())
9393 DefineImplicitCopyAssignment(Loc, MethodDecl);
9394 else
9395 DefineImplicitMoveAssignment(Loc, MethodDecl);
9396 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00009397 } else if (MethodDecl->isVirtual())
9398 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009399 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009400 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009401 // Recursive functions should be marked when used from another function.
9402 if (CurContext == Function) return;
9403
Mike Stump11289f42009-09-09 15:08:12 +00009404 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009405 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009406 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009407 bool AlreadyInstantiated = false;
9408 if (FunctionTemplateSpecializationInfo *SpecInfo
9409 = Function->getTemplateSpecializationInfo()) {
9410 if (SpecInfo->getPointOfInstantiation().isInvalid())
9411 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009412 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009413 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009414 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009415 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009416 = Function->getMemberSpecializationInfo()) {
9417 if (MSInfo->getPointOfInstantiation().isInvalid())
9418 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009419 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009420 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009421 AlreadyInstantiated = true;
9422 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009423
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009424 if (!AlreadyInstantiated) {
9425 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9426 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9427 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9428 Loc));
9429 else
Chandler Carruth54080172010-08-25 08:44:16 +00009430 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009431 }
John McCall83779672011-02-19 02:53:41 +00009432 } else {
9433 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009434 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9435 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009436 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009437 MarkDeclarationReferenced(Loc, *i);
9438 }
John McCall83779672011-02-19 02:53:41 +00009439 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009440
John McCall83779672011-02-19 02:53:41 +00009441 // Keep track of used but undefined functions.
9442 if (!Function->isPure() && !Function->hasBody() &&
9443 Function->getLinkage() != ExternalLinkage) {
9444 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9445 if (old.isInvalid()) old = Loc;
9446 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009447
John McCall83779672011-02-19 02:53:41 +00009448 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009449 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009450 }
Mike Stump11289f42009-09-09 15:08:12 +00009451
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009452 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009453 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009454 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009455 Var->getInstantiatedFromStaticDataMember()) {
9456 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9457 assert(MSInfo && "Missing member specialization information?");
9458 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9459 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9460 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redl2ac2c722011-04-29 08:19:30 +00009461 // This is a modification of an existing AST node. Notify listeners.
9462 if (ASTMutationListener *L = getASTMutationListener())
9463 L->StaticDataMemberInstantiated(Var);
Chandler Carruth54080172010-08-25 08:44:16 +00009464 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009465 }
9466 }
Mike Stump11289f42009-09-09 15:08:12 +00009467
John McCall15dd4042011-02-21 19:25:48 +00009468 // Keep track of used but undefined variables. We make a hole in
9469 // the warning for static const data members with in-line
9470 // initializers.
John McCall83779672011-02-19 02:53:41 +00009471 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009472 && Var->getLinkage() != ExternalLinkage
9473 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009474 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9475 if (old.isInvalid()) old = Loc;
9476 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009477
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009478 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009479 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009480 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009481}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009482
Douglas Gregor5597ab42010-05-07 23:12:07 +00009483namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009484 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009485 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009486 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009487 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9488 Sema &S;
9489 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009490
Douglas Gregor5597ab42010-05-07 23:12:07 +00009491 public:
9492 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009493
Douglas Gregor5597ab42010-05-07 23:12:07 +00009494 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009495
9496 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9497 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009498 };
9499}
9500
Chandler Carruthaf80f662010-06-09 08:17:30 +00009501bool MarkReferencedDecls::TraverseTemplateArgument(
9502 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009503 if (Arg.getKind() == TemplateArgument::Declaration) {
9504 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9505 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009506
9507 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009508}
9509
Chandler Carruthaf80f662010-06-09 08:17:30 +00009510bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009511 if (ClassTemplateSpecializationDecl *Spec
9512 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9513 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009514 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009515 }
9516
Chandler Carruthc65667c2010-06-10 10:31:57 +00009517 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009518}
9519
9520void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9521 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009522 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009523}
9524
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009525namespace {
9526 /// \brief Helper class that marks all of the declarations referenced by
9527 /// potentially-evaluated subexpressions as "referenced".
9528 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9529 Sema &S;
9530
9531 public:
9532 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9533
9534 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9535
9536 void VisitDeclRefExpr(DeclRefExpr *E) {
9537 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9538 }
9539
9540 void VisitMemberExpr(MemberExpr *E) {
9541 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009542 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009543 }
9544
9545 void VisitCXXNewExpr(CXXNewExpr *E) {
9546 if (E->getConstructor())
9547 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9548 if (E->getOperatorNew())
9549 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9550 if (E->getOperatorDelete())
9551 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009552 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009553 }
9554
9555 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9556 if (E->getOperatorDelete())
9557 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009558 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9559 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9560 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9561 S.MarkDeclarationReferenced(E->getLocStart(),
9562 S.LookupDestructor(Record));
9563 }
9564
Douglas Gregor32b3de52010-09-11 23:32:50 +00009565 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009566 }
9567
9568 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9569 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009570 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009571 }
9572
9573 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9574 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9575 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009576
9577 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9578 Visit(E->getExpr());
9579 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009580 };
9581}
9582
9583/// \brief Mark any declarations that appear within this expression or any
9584/// potentially-evaluated subexpressions as "referenced".
9585void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9586 EvaluatedExprMarker(*this).Visit(E);
9587}
9588
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009589/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9590/// of the program being compiled.
9591///
9592/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009593/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009594/// possibility that the code will actually be executable. Code in sizeof()
9595/// expressions, code used only during overload resolution, etc., are not
9596/// potentially evaluated. This routine will suppress such diagnostics or,
9597/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009598/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009599/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009600///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009601/// This routine should be used for all diagnostics that describe the run-time
9602/// behavior of a program, such as passing a non-POD value through an ellipsis.
9603/// Failure to do so will likely result in spurious diagnostics or failures
9604/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +00009605bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009606 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +00009607 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009608 case Unevaluated:
9609 // The argument will never be evaluated, so don't complain.
9610 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009611
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009612 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009613 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +00009614 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00009615 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +00009616 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +00009617 }
9618 else
9619 Diag(Loc, PD);
9620
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009621 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009622
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009623 case PotentiallyPotentiallyEvaluated:
9624 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9625 break;
9626 }
9627
9628 return false;
9629}
9630
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009631bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9632 CallExpr *CE, FunctionDecl *FD) {
9633 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9634 return false;
9635
9636 PartialDiagnostic Note =
9637 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9638 << FD->getDeclName() : PDiag();
9639 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009640
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009641 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009642 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009643 PDiag(diag::err_call_function_incomplete_return)
9644 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009645 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009646 << CE->getSourceRange(),
9647 std::make_pair(NoteLoc, Note)))
9648 return true;
9649
9650 return false;
9651}
9652
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009653// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009654// will prevent this condition from triggering, which is what we want.
9655void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9656 SourceLocation Loc;
9657
John McCall0506e4a2009-11-11 02:41:58 +00009658 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009659 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009660
Chandler Carruthf87d6c02011-08-16 22:30:10 +00009661 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009662 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009663 return;
9664
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009665 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9666
John McCallb0e419e2009-11-12 00:06:05 +00009667 // Greylist some idioms by putting them into a warning subcategory.
9668 if (ObjCMessageExpr *ME
9669 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9670 Selector Sel = ME->getSelector();
9671
John McCallb0e419e2009-11-12 00:06:05 +00009672 // self = [<foo> init...]
Douglas Gregor486b74e2011-09-27 16:10:05 +00009673 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009674 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9675
9676 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009677 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009678 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9679 }
John McCall0506e4a2009-11-11 02:41:58 +00009680
John McCalld5707ab2009-10-12 21:59:07 +00009681 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +00009682 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009683 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009684 return;
9685
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009686 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009687 Loc = Op->getOperatorLoc();
9688 } else {
9689 // Not an assignment.
9690 return;
9691 }
9692
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009693 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009694
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009695 SourceLocation Open = E->getSourceRange().getBegin();
9696 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9697 Diag(Loc, diag::note_condition_assign_silence)
9698 << FixItHint::CreateInsertion(Open, "(")
9699 << FixItHint::CreateInsertion(Close, ")");
9700
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009701 if (IsOrAssign)
9702 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9703 << FixItHint::CreateReplacement(Loc, "!=");
9704 else
9705 Diag(Loc, diag::note_condition_assign_to_comparison)
9706 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00009707}
9708
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009709/// \brief Redundant parentheses over an equality comparison can indicate
9710/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +00009711void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009712 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +00009713 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009714 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9715 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009716 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00009717 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009718 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009719
Richard Trieuba63ce62011-09-09 01:45:06 +00009720 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009721
9722 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009723 if (opE->getOpcode() == BO_EQ &&
9724 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9725 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009726 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009727
Ted Kremenekae022092011-02-02 02:20:30 +00009728 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +00009729 Diag(Loc, diag::note_equality_comparison_silence)
Richard Trieuba63ce62011-09-09 01:45:06 +00009730 << FixItHint::CreateRemoval(ParenE->getSourceRange().getBegin())
9731 << FixItHint::CreateRemoval(ParenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009732 Diag(Loc, diag::note_equality_comparison_to_assign)
9733 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009734 }
9735}
9736
John Wiegley01296292011-04-08 18:41:53 +00009737ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +00009738 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009739 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9740 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009741
John McCall0009fcc2011-04-26 20:42:42 +00009742 ExprResult result = CheckPlaceholderExpr(E);
9743 if (result.isInvalid()) return ExprError();
9744 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009745
John McCall0009fcc2011-04-26 20:42:42 +00009746 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +00009747 if (getLangOptions().CPlusPlus)
9748 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9749
John Wiegley01296292011-04-08 18:41:53 +00009750 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9751 if (ERes.isInvalid())
9752 return ExprError();
9753 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +00009754
9755 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +00009756 if (!T->isScalarType()) { // C99 6.8.4.1p1
9757 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9758 << T << E->getSourceRange();
9759 return ExprError();
9760 }
John McCalld5707ab2009-10-12 21:59:07 +00009761 }
9762
John Wiegley01296292011-04-08 18:41:53 +00009763 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +00009764}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009765
John McCalldadc5752010-08-24 06:29:42 +00009766ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009767 Expr *SubExpr) {
9768 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009769 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009770
Richard Trieuba63ce62011-09-09 01:45:06 +00009771 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +00009772}
John McCall36e7fe32010-10-12 00:20:44 +00009773
John McCall31996342011-04-07 08:22:57 +00009774namespace {
John McCall2979fe02011-04-12 00:42:48 +00009775 /// A visitor for rebuilding a call to an __unknown_any expression
9776 /// to have an appropriate type.
9777 struct RebuildUnknownAnyFunction
9778 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9779
9780 Sema &S;
9781
9782 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9783
9784 ExprResult VisitStmt(Stmt *S) {
9785 llvm_unreachable("unexpected statement!");
9786 return ExprError();
9787 }
9788
Richard Trieu10162ab2011-09-09 03:59:41 +00009789 ExprResult VisitExpr(Expr *E) {
9790 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
9791 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +00009792 return ExprError();
9793 }
9794
9795 /// Rebuild an expression which simply semantically wraps another
9796 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +00009797 template <class T> ExprResult rebuildSugarExpr(T *E) {
9798 ExprResult SubResult = Visit(E->getSubExpr());
9799 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +00009800
Richard Trieu10162ab2011-09-09 03:59:41 +00009801 Expr *SubExpr = SubResult.take();
9802 E->setSubExpr(SubExpr);
9803 E->setType(SubExpr->getType());
9804 E->setValueKind(SubExpr->getValueKind());
9805 assert(E->getObjectKind() == OK_Ordinary);
9806 return E;
John McCall2979fe02011-04-12 00:42:48 +00009807 }
9808
Richard Trieu10162ab2011-09-09 03:59:41 +00009809 ExprResult VisitParenExpr(ParenExpr *E) {
9810 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +00009811 }
9812
Richard Trieu10162ab2011-09-09 03:59:41 +00009813 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9814 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +00009815 }
9816
Richard Trieu10162ab2011-09-09 03:59:41 +00009817 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9818 ExprResult SubResult = Visit(E->getSubExpr());
9819 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +00009820
Richard Trieu10162ab2011-09-09 03:59:41 +00009821 Expr *SubExpr = SubResult.take();
9822 E->setSubExpr(SubExpr);
9823 E->setType(S.Context.getPointerType(SubExpr->getType()));
9824 assert(E->getValueKind() == VK_RValue);
9825 assert(E->getObjectKind() == OK_Ordinary);
9826 return E;
John McCall2979fe02011-04-12 00:42:48 +00009827 }
9828
Richard Trieu10162ab2011-09-09 03:59:41 +00009829 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
9830 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +00009831
Richard Trieu10162ab2011-09-09 03:59:41 +00009832 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +00009833
Richard Trieu10162ab2011-09-09 03:59:41 +00009834 assert(E->getValueKind() == VK_RValue);
John McCall2979fe02011-04-12 00:42:48 +00009835 if (S.getLangOptions().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +00009836 !(isa<CXXMethodDecl>(VD) &&
9837 cast<CXXMethodDecl>(VD)->isInstance()))
9838 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +00009839
Richard Trieu10162ab2011-09-09 03:59:41 +00009840 return E;
John McCall2979fe02011-04-12 00:42:48 +00009841 }
9842
Richard Trieu10162ab2011-09-09 03:59:41 +00009843 ExprResult VisitMemberExpr(MemberExpr *E) {
9844 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +00009845 }
9846
Richard Trieu10162ab2011-09-09 03:59:41 +00009847 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9848 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +00009849 }
9850 };
9851}
9852
9853/// Given a function expression of unknown-any type, try to rebuild it
9854/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +00009855static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
9856 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
9857 if (Result.isInvalid()) return ExprError();
9858 return S.DefaultFunctionArrayConversion(Result.take());
John McCall2979fe02011-04-12 00:42:48 +00009859}
9860
9861namespace {
John McCall2d2e8702011-04-11 07:02:50 +00009862 /// A visitor for rebuilding an expression of type __unknown_anytype
9863 /// into one which resolves the type directly on the referring
9864 /// expression. Strict preservation of the original source
9865 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +00009866 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +00009867 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +00009868
9869 Sema &S;
9870
9871 /// The current destination type.
9872 QualType DestType;
9873
Richard Trieu10162ab2011-09-09 03:59:41 +00009874 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
9875 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +00009876
John McCall39439732011-04-09 22:50:59 +00009877 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +00009878 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +00009879 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009880 }
9881
Richard Trieu10162ab2011-09-09 03:59:41 +00009882 ExprResult VisitExpr(Expr *E) {
9883 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9884 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +00009885 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009886 }
9887
Richard Trieu10162ab2011-09-09 03:59:41 +00009888 ExprResult VisitCallExpr(CallExpr *E);
9889 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +00009890
John McCall39439732011-04-09 22:50:59 +00009891 /// Rebuild an expression which simply semantically wraps another
9892 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +00009893 template <class T> ExprResult rebuildSugarExpr(T *E) {
9894 ExprResult SubResult = Visit(E->getSubExpr());
9895 if (SubResult.isInvalid()) return ExprError();
9896 Expr *SubExpr = SubResult.take();
9897 E->setSubExpr(SubExpr);
9898 E->setType(SubExpr->getType());
9899 E->setValueKind(SubExpr->getValueKind());
9900 assert(E->getObjectKind() == OK_Ordinary);
9901 return E;
John McCall39439732011-04-09 22:50:59 +00009902 }
John McCall31996342011-04-07 08:22:57 +00009903
Richard Trieu10162ab2011-09-09 03:59:41 +00009904 ExprResult VisitParenExpr(ParenExpr *E) {
9905 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +00009906 }
9907
Richard Trieu10162ab2011-09-09 03:59:41 +00009908 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9909 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +00009910 }
9911
Richard Trieu10162ab2011-09-09 03:59:41 +00009912 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9913 const PointerType *Ptr = DestType->getAs<PointerType>();
9914 if (!Ptr) {
9915 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
9916 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +00009917 return ExprError();
9918 }
Richard Trieu10162ab2011-09-09 03:59:41 +00009919 assert(E->getValueKind() == VK_RValue);
9920 assert(E->getObjectKind() == OK_Ordinary);
9921 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +00009922
9923 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +00009924 DestType = Ptr->getPointeeType();
9925 ExprResult SubResult = Visit(E->getSubExpr());
9926 if (SubResult.isInvalid()) return ExprError();
9927 E->setSubExpr(SubResult.take());
9928 return E;
John McCall2979fe02011-04-12 00:42:48 +00009929 }
9930
Richard Trieu10162ab2011-09-09 03:59:41 +00009931 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +00009932
Richard Trieu10162ab2011-09-09 03:59:41 +00009933 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +00009934
Richard Trieu10162ab2011-09-09 03:59:41 +00009935 ExprResult VisitMemberExpr(MemberExpr *E) {
9936 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +00009937 }
John McCall39439732011-04-09 22:50:59 +00009938
Richard Trieu10162ab2011-09-09 03:59:41 +00009939 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9940 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +00009941 }
9942 };
9943}
9944
John McCall2d2e8702011-04-11 07:02:50 +00009945/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +00009946ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
9947 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +00009948
9949 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +00009950 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +00009951 FK_FunctionPointer,
9952 FK_BlockPointer
9953 };
9954
Richard Trieu10162ab2011-09-09 03:59:41 +00009955 FnKind Kind;
9956 QualType CalleeType = CalleeExpr->getType();
9957 if (CalleeType == S.Context.BoundMemberTy) {
9958 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
9959 Kind = FK_MemberFunction;
9960 CalleeType = Expr::findBoundMemberType(CalleeExpr);
9961 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
9962 CalleeType = Ptr->getPointeeType();
9963 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +00009964 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +00009965 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
9966 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +00009967 }
Richard Trieu10162ab2011-09-09 03:59:41 +00009968 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +00009969
9970 // Verify that this is a legal result type of a function.
9971 if (DestType->isArrayType() || DestType->isFunctionType()) {
9972 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +00009973 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +00009974 diagID = diag::err_block_returning_array_function;
9975
Richard Trieu10162ab2011-09-09 03:59:41 +00009976 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +00009977 << DestType->isFunctionType() << DestType;
9978 return ExprError();
9979 }
9980
9981 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +00009982 E->setType(DestType.getNonLValueExprType(S.Context));
9983 E->setValueKind(Expr::getValueKindForType(DestType));
9984 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +00009985
9986 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu10162ab2011-09-09 03:59:41 +00009987 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall2d2e8702011-04-11 07:02:50 +00009988 DestType = S.Context.getFunctionType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +00009989 Proto->arg_type_begin(),
9990 Proto->getNumArgs(),
9991 Proto->getExtProtoInfo());
John McCall2d2e8702011-04-11 07:02:50 +00009992 else
9993 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +00009994 FnType->getExtInfo());
John McCall2d2e8702011-04-11 07:02:50 +00009995
9996 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +00009997 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +00009998 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +00009999 // Nothing to do.
10000 break;
10001
10002 case FK_FunctionPointer:
10003 DestType = S.Context.getPointerType(DestType);
10004 break;
10005
10006 case FK_BlockPointer:
10007 DestType = S.Context.getBlockPointerType(DestType);
10008 break;
10009 }
10010
10011 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +000010012 ExprResult CalleeResult = Visit(CalleeExpr);
10013 if (!CalleeResult.isUsable()) return ExprError();
10014 E->setCallee(CalleeResult.take());
John McCall2d2e8702011-04-11 07:02:50 +000010015
10016 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +000010017 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000010018}
10019
Richard Trieu10162ab2011-09-09 03:59:41 +000010020ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000010021 // Verify that this is a legal result type of a call.
10022 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +000010023 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +000010024 << DestType->isFunctionType() << DestType;
10025 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010026 }
10027
John McCall3f4138c2011-07-13 17:56:40 +000010028 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +000010029 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
10030 assert(Method->getResultType() == S.Context.UnknownAnyTy);
10031 Method->setResultType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +000010032 }
John McCall2979fe02011-04-12 00:42:48 +000010033
John McCall2d2e8702011-04-11 07:02:50 +000010034 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +000010035 E->setType(DestType.getNonReferenceType());
10036 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000010037
Richard Trieu10162ab2011-09-09 03:59:41 +000010038 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000010039}
10040
Richard Trieu10162ab2011-09-09 03:59:41 +000010041ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000010042 // The only case we should ever see here is a function-to-pointer decay.
Richard Trieu10162ab2011-09-09 03:59:41 +000010043 assert(E->getCastKind() == CK_FunctionToPointerDecay);
10044 assert(E->getValueKind() == VK_RValue);
10045 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000010046
Richard Trieu10162ab2011-09-09 03:59:41 +000010047 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +000010048
John McCall2d2e8702011-04-11 07:02:50 +000010049 // Rebuild the sub-expression as the pointee (function) type.
10050 DestType = DestType->castAs<PointerType>()->getPointeeType();
10051
Richard Trieu10162ab2011-09-09 03:59:41 +000010052 ExprResult Result = Visit(E->getSubExpr());
10053 if (!Result.isUsable()) return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010054
Richard Trieu10162ab2011-09-09 03:59:41 +000010055 E->setSubExpr(Result.take());
10056 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000010057}
10058
Richard Trieu10162ab2011-09-09 03:59:41 +000010059ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
10060 ExprValueKind ValueKind = VK_LValue;
10061 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +000010062
10063 // We know how to make this work for certain kinds of decls:
10064
10065 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +000010066 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
10067 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
10068 DestType = Ptr->getPointeeType();
10069 ExprResult Result = resolveDecl(E, VD);
10070 if (Result.isInvalid()) return ExprError();
10071 return S.ImpCastExprToType(Result.take(), Type,
John McCall9a877fe2011-08-10 04:12:23 +000010072 CK_FunctionToPointerDecay, VK_RValue);
10073 }
10074
Richard Trieu10162ab2011-09-09 03:59:41 +000010075 if (!Type->isFunctionType()) {
10076 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
10077 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000010078 return ExprError();
10079 }
John McCall2d2e8702011-04-11 07:02:50 +000010080
Richard Trieu10162ab2011-09-09 03:59:41 +000010081 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
10082 if (MD->isInstance()) {
10083 ValueKind = VK_RValue;
10084 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000010085 }
10086
John McCall2d2e8702011-04-11 07:02:50 +000010087 // Function references aren't l-values in C.
10088 if (!S.getLangOptions().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000010089 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000010090
10091 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000010092 } else if (isa<VarDecl>(VD)) {
10093 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
10094 Type = RefTy->getPointeeType();
10095 } else if (Type->isFunctionType()) {
10096 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
10097 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000010098 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010099 }
10100
10101 // - nothing else
10102 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000010103 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10104 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000010105 return ExprError();
10106 }
10107
Richard Trieu10162ab2011-09-09 03:59:41 +000010108 VD->setType(DestType);
10109 E->setType(Type);
10110 E->setValueKind(ValueKind);
10111 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000010112}
10113
John McCall31996342011-04-07 08:22:57 +000010114/// Check a cast of an unknown-any type. We intentionally only
10115/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000010116ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
10117 Expr *CastExpr, CastKind &CastKind,
10118 ExprValueKind &VK, CXXCastPath &Path) {
John McCall31996342011-04-07 08:22:57 +000010119 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000010120 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000010121 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000010122
Richard Trieuba63ce62011-09-09 01:45:06 +000010123 CastExpr = result.take();
10124 VK = CastExpr->getValueKind();
10125 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000010126
Richard Trieuba63ce62011-09-09 01:45:06 +000010127 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000010128}
10129
Richard Trieuba63ce62011-09-09 01:45:06 +000010130static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
10131 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000010132 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000010133 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000010134 E = E->IgnoreParenImpCasts();
10135 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
10136 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000010137 diagID = diag::err_uncasted_call_of_unknown_any;
10138 } else {
John McCall31996342011-04-07 08:22:57 +000010139 break;
John McCall2d2e8702011-04-11 07:02:50 +000010140 }
John McCall31996342011-04-07 08:22:57 +000010141 }
10142
John McCall2d2e8702011-04-11 07:02:50 +000010143 SourceLocation loc;
10144 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000010145 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010146 loc = ref->getLocation();
10147 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000010148 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010149 loc = mem->getMemberLoc();
10150 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000010151 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010152 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidisa6011e22011-10-03 06:36:51 +000010153 loc = msg->getSelectorStartLoc();
John McCall2d2e8702011-04-11 07:02:50 +000010154 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000010155 if (!d) {
10156 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
10157 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
10158 << orig->getSourceRange();
10159 return ExprError();
10160 }
John McCall2d2e8702011-04-11 07:02:50 +000010161 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000010162 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10163 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000010164 return ExprError();
10165 }
10166
10167 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000010168
10169 // Never recoverable.
10170 return ExprError();
10171}
10172
John McCall36e7fe32010-10-12 00:20:44 +000010173/// Check for operands with placeholder types and complain if found.
10174/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000010175ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +000010176 // Placeholder types are always *exactly* the appropriate builtin type.
10177 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +000010178
John McCall31996342011-04-07 08:22:57 +000010179 // Overloaded expressions.
10180 if (type == Context.OverloadTy)
10181 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010182 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +000010183 QualType(),
10184 diag::err_ovl_unresolvable);
10185
John McCall0009fcc2011-04-26 20:42:42 +000010186 // Bound member functions.
10187 if (type == Context.BoundMemberTy) {
10188 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
10189 << E->getSourceRange();
10190 return ExprError();
10191 }
10192
John McCall31996342011-04-07 08:22:57 +000010193 // Expressions of unknown type.
10194 if (type == Context.UnknownAnyTy)
10195 return diagnoseUnknownAnyExpr(*this, E);
10196
10197 assert(!type->isPlaceholderType());
10198 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +000010199}
Richard Trieu2c850c02011-04-21 21:44:26 +000010200
Richard Trieuba63ce62011-09-09 01:45:06 +000010201bool Sema::CheckCaseExpression(Expr *E) {
10202 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000010203 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000010204 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
10205 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000010206 return false;
10207}