blob: 0d4c7bea171ad831876a66046cd2ea07f42bd76f [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
John McCall27584242010-12-06 20:48:59 +0000345 // Create a load out of an ObjCProperty l-value, if necessary.
346 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +0000347 ExprResult Res = ConvertPropertyForRValue(E);
348 if (Res.isInvalid())
349 return Owned(E);
350 E = Res.take();
John McCall27584242010-12-06 20:48:59 +0000351 if (!E->isGLValue())
John Wiegley01296292011-04-08 18:41:53 +0000352 return Owned(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000353 }
John McCall27584242010-12-06 20:48:59 +0000354
355 // We don't want to throw lvalue-to-rvalue casts on top of
356 // expressions of certain types in C++.
357 if (getLangOptions().CPlusPlus &&
358 (E->getType() == Context.OverloadTy ||
359 T->isDependentType() ||
360 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000361 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000362
363 // The C standard is actually really unclear on this point, and
364 // DR106 tells us what the result should be but not why. It's
365 // generally best to say that void types just doesn't undergo
366 // lvalue-to-rvalue at all. Note that expressions of unqualified
367 // 'void' type are never l-values, but qualified void can be.
368 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000369 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000370
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000371 CheckForNullPointerDereference(*this, E);
372
John McCall27584242010-12-06 20:48:59 +0000373 // C++ [conv.lval]p1:
374 // [...] If T is a non-class type, the type of the prvalue is the
375 // cv-unqualified version of T. Otherwise, the type of the
376 // rvalue is T.
377 //
378 // C99 6.3.2.1p2:
379 // If the lvalue has qualified type, the value has the unqualified
380 // version of the type of the lvalue; otherwise, the value has the
381 // type of the lvalue.
382 if (T.hasQualifiers())
383 T = T.getUnqualifiedType();
Ted Kremenek64699be2011-02-16 01:57:07 +0000384
John Wiegley01296292011-04-08 18:41:53 +0000385 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
386 E, 0, VK_RValue));
John McCall27584242010-12-06 20:48:59 +0000387}
388
John Wiegley01296292011-04-08 18:41:53 +0000389ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
390 ExprResult Res = DefaultFunctionArrayConversion(E);
391 if (Res.isInvalid())
392 return ExprError();
393 Res = DefaultLvalueConversion(Res.take());
394 if (Res.isInvalid())
395 return ExprError();
396 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000397}
398
399
Chris Lattner513165e2008-07-25 21:10:04 +0000400/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000401/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000402/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000403/// apply if the array is an argument to the sizeof or address (&) operators.
404/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000405ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000406 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000407 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
408 if (Res.isInvalid())
409 return Owned(E);
410 E = Res.take();
John McCallf3735e02010-12-01 04:43:34 +0000411
412 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000413 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000414
415 // Try to perform integral promotions if the object has a theoretically
416 // promotable type.
417 if (Ty->isIntegralOrUnscopedEnumerationType()) {
418 // C99 6.3.1.1p2:
419 //
420 // The following may be used in an expression wherever an int or
421 // unsigned int may be used:
422 // - an object or expression with an integer type whose integer
423 // conversion rank is less than or equal to the rank of int
424 // and unsigned int.
425 // - A bit-field of type _Bool, int, signed int, or unsigned int.
426 //
427 // If an int can represent all values of the original type, the
428 // value is converted to an int; otherwise, it is converted to an
429 // unsigned int. These are called the integer promotions. All
430 // other types are unchanged by the integer promotions.
431
432 QualType PTy = Context.isPromotableBitField(E);
433 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000434 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
435 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000436 }
437 if (Ty->isPromotableIntegerType()) {
438 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000439 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
440 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000441 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000442 }
John Wiegley01296292011-04-08 18:41:53 +0000443 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000444}
445
Chris Lattner2ce500f2008-07-25 22:25:12 +0000446/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000447/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000448/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000449ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
450 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000451 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000452
John Wiegley01296292011-04-08 18:41:53 +0000453 ExprResult Res = UsualUnaryConversions(E);
454 if (Res.isInvalid())
455 return Owned(E);
456 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000457
Chris Lattner2ce500f2008-07-25 22:25:12 +0000458 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000459 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000460 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
461
John McCall4bb057d2011-08-27 22:06:17 +0000462 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall0562caa2011-08-29 23:55:37 +0000463 // promotion, even on class types, but note:
464 // C++11 [conv.lval]p2:
465 // When an lvalue-to-rvalue conversion occurs in an unevaluated
466 // operand or a subexpression thereof the value contained in the
467 // referenced object is not accessed. Otherwise, if the glvalue
468 // has a class type, the conversion copy-initializes a temporary
469 // of type T from the glvalue and the result of the conversion
470 // is a prvalue for the temporary.
471 // FIXME: add some way to gate this entire thing for correctness in
472 // potentially potentially evaluated contexts.
John McCall4bb057d2011-08-27 22:06:17 +0000473 if (getLangOptions().CPlusPlus && E->isGLValue() &&
474 ExprEvalContexts.back().Context != Unevaluated) {
John McCall29ad95b2011-08-27 01:09:30 +0000475 ExprResult Temp = PerformCopyInitialization(
476 InitializedEntity::InitializeTemporary(E->getType()),
477 E->getExprLoc(),
478 Owned(E));
479 if (Temp.isInvalid())
480 return ExprError();
481 E = Temp.get();
482 }
483
John Wiegley01296292011-04-08 18:41:53 +0000484 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000485}
486
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000487/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
488/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000489/// interfaces passed by value.
490ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000491 FunctionDecl *FDecl) {
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000492 ExprResult ExprRes = CheckPlaceholderExpr(E);
493 if (ExprRes.isInvalid())
494 return ExprError();
495
496 ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000497 if (ExprRes.isInvalid())
498 return ExprError();
499 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000500
Douglas Gregor347e0f22011-05-21 19:26:31 +0000501 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000502 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000503 DiagRuntimeBehavior(E->getLocStart(), 0,
504 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
505 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000506 return ExprError();
John McCall29ad95b2011-08-27 01:09:30 +0000507
John McCall31168b02011-06-15 23:02:42 +0000508 if (!E->getType().isPODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000509 // C++0x [expr.call]p7:
510 // Passing a potentially-evaluated argument of class type (Clause 9)
511 // having a non-trivial copy constructor, a non-trivial move constructor,
512 // or a non-trivial destructor, with no corresponding parameter,
513 // is conditionally-supported with implementation-defined semantics.
514 bool TrivialEnough = false;
515 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
516 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
517 if (Record->hasTrivialCopyConstructor() &&
518 Record->hasTrivialMoveConstructor() &&
519 Record->hasTrivialDestructor())
520 TrivialEnough = true;
521 }
522 }
John McCall31168b02011-06-15 23:02:42 +0000523
524 if (!TrivialEnough &&
525 getLangOptions().ObjCAutoRefCount &&
526 E->getType()->isObjCLifetimeType())
527 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000528
529 if (TrivialEnough) {
530 // Nothing to diagnose. This is okay.
531 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000532 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor253cadf2011-05-21 16:27:21 +0000533 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000534 << CT)) {
535 // Turn this into a trap.
536 CXXScopeSpec SS;
537 UnqualifiedId Name;
538 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
539 E->getLocStart());
540 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
541 if (TrapFn.isInvalid())
542 return ExprError();
543
544 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
545 MultiExprArg(), E->getLocEnd());
546 if (Call.isInvalid())
547 return ExprError();
548
549 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
550 Call.get(), E);
551 if (Comma.isInvalid())
John McCall1cd60a22011-08-26 18:41:18 +0000552 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000553 E = Comma.get();
554 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000555 }
556
John Wiegley01296292011-04-08 18:41:53 +0000557 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000558}
559
Richard Trieu7aa58f12011-09-02 20:58:51 +0000560/// \brief Converts an integer to complex float type. Helper function of
561/// UsualArithmeticConversions()
562///
563/// \return false if the integer expression is an integer type and is
564/// successfully converted to the complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000565static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
566 ExprResult &ComplexExpr,
567 QualType IntTy,
568 QualType ComplexTy,
569 bool SkipCast) {
570 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
571 if (SkipCast) return false;
572 if (IntTy->isIntegerType()) {
573 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
574 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
575 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000576 CK_FloatingRealToComplex);
577 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +0000578 assert(IntTy->isComplexIntegerType());
579 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000580 CK_IntegralComplexToFloatingComplex);
581 }
582 return false;
583}
584
585/// \brief Takes two complex float types and converts them to the same type.
586/// Helper function of UsualArithmeticConversions()
587static QualType
Richard Trieu5065cdd2011-09-06 18:25:09 +0000588handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
589 ExprResult &RHS, QualType LHSType,
590 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000591 bool IsCompAssign) {
Richard Trieu5065cdd2011-09-06 18:25:09 +0000592 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000593
594 if (order < 0) {
595 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000596 if (!IsCompAssign)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000597 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
598 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000599 }
600 if (order > 0)
601 // _Complex float -> _Complex double
Richard Trieu5065cdd2011-09-06 18:25:09 +0000602 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
603 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000604}
605
606/// \brief Converts otherExpr to complex float and promotes complexExpr if
607/// necessary. Helper function of UsualArithmeticConversions()
608static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuba63ce62011-09-09 01:45:06 +0000609 ExprResult &ComplexExpr,
610 ExprResult &OtherExpr,
611 QualType ComplexTy,
612 QualType OtherTy,
613 bool ConvertComplexExpr,
614 bool ConvertOtherExpr) {
615 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000616
617 // If just the complexExpr is complex, the otherExpr needs to be converted,
618 // and the complexExpr might need to be promoted.
619 if (order > 0) { // complexExpr is wider
620 // float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000621 if (ConvertOtherExpr) {
622 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
623 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
624 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000625 CK_FloatingRealToComplex);
626 }
Richard Trieuba63ce62011-09-09 01:45:06 +0000627 return ComplexTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000628 }
629
630 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000631 QualType result = (order == 0 ? ComplexTy :
632 S.Context.getComplexType(OtherTy));
Richard Trieu7aa58f12011-09-02 20:58:51 +0000633
634 // double -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000635 if (ConvertOtherExpr)
636 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000637 CK_FloatingRealToComplex);
638
639 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000640 if (ConvertComplexExpr && order < 0)
641 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000642 CK_FloatingComplexCast);
643
644 return result;
645}
646
647/// \brief Handle arithmetic conversion with complex types. Helper function of
648/// UsualArithmeticConversions()
Richard Trieu5065cdd2011-09-06 18:25:09 +0000649static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
650 ExprResult &RHS, QualType LHSType,
651 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000652 bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000653 // if we have an integer operand, the result is the complex type.
Richard Trieu5065cdd2011-09-06 18:25:09 +0000654 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000655 /*skipCast*/false))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000656 return LHSType;
657 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000658 /*skipCast*/IsCompAssign))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000659 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000660
661 // This handles complex/complex, complex/float, or float/complex.
662 // When both operands are complex, the shorter operand is converted to the
663 // type of the longer, and that is the type of the result. This corresponds
664 // to what is done when combining two real floating-point operands.
665 // The fun begins when size promotion occur across type domains.
666 // From H&S 6.3.4: When one operand is complex and the other is a real
667 // floating-point type, the less precise type is converted, within it's
668 // real or complex domain, to the precision of the other type. For example,
669 // when combining a "long double" with a "double _Complex", the
670 // "double _Complex" is promoted to "long double _Complex".
671
Richard Trieu5065cdd2011-09-06 18:25:09 +0000672 bool LHSComplexFloat = LHSType->isComplexType();
673 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000674
675 // If both are complex, just cast to the more precise type.
676 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000677 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
678 LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000679 IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000680
681 // If only one operand is complex, promote it if necessary and convert the
682 // other operand to complex.
683 if (LHSComplexFloat)
684 return handleOtherComplexFloatConversion(
Richard Trieuba63ce62011-09-09 01:45:06 +0000685 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000686 /*convertOtherExpr*/ true);
687
688 assert(RHSComplexFloat);
689 return handleOtherComplexFloatConversion(
Richard Trieu5065cdd2011-09-06 18:25:09 +0000690 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000691 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000692}
693
694/// \brief Hande arithmetic conversion from integer to float. Helper function
695/// of UsualArithmeticConversions()
Richard Trieuba63ce62011-09-09 01:45:06 +0000696static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
697 ExprResult &IntExpr,
698 QualType FloatTy, QualType IntTy,
699 bool ConvertFloat, bool ConvertInt) {
700 if (IntTy->isIntegerType()) {
701 if (ConvertInt)
Richard Trieu7aa58f12011-09-02 20:58:51 +0000702 // Convert intExpr to the lhs floating point type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000703 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000704 CK_IntegralToFloating);
Richard Trieuba63ce62011-09-09 01:45:06 +0000705 return FloatTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000706 }
707
708 // Convert both sides to the appropriate complex float.
Richard Trieuba63ce62011-09-09 01:45:06 +0000709 assert(IntTy->isComplexIntegerType());
710 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000711
712 // _Complex int -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000713 if (ConvertInt)
714 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000715 CK_IntegralComplexToFloatingComplex);
716
717 // float -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000718 if (ConvertFloat)
719 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000720 CK_FloatingRealToComplex);
721
722 return result;
723}
724
725/// \brief Handle arithmethic conversion with floating point types. Helper
726/// function of UsualArithmeticConversions()
Richard Trieucfe3f212011-09-06 18:38:41 +0000727static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
728 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000729 QualType RHSType, bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000730 bool LHSFloat = LHSType->isRealFloatingType();
731 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000732
733 // If we have two real floating types, convert the smaller operand
734 // to the bigger result.
735 if (LHSFloat && RHSFloat) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000736 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000737 if (order > 0) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000738 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
739 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000740 }
741
742 assert(order < 0 && "illegal float comparison");
Richard Trieuba63ce62011-09-09 01:45:06 +0000743 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000744 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
745 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000746 }
747
748 if (LHSFloat)
Richard Trieucfe3f212011-09-06 18:38:41 +0000749 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000750 /*convertFloat=*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000751 /*convertInt=*/ true);
752 assert(RHSFloat);
Richard Trieucfe3f212011-09-06 18:38:41 +0000753 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000754 /*convertInt=*/ true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000755 /*convertFloat=*/!IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000756}
757
758/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000759/// of UsualArithmeticConversions()
Richard Trieu7aa58f12011-09-02 20:58:51 +0000760// FIXME: if the operands are (int, _Complex long), we currently
761// don't promote the complex. Also, signedness?
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000762static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
763 ExprResult &RHS, QualType LHSType,
764 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000765 bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000766 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
767 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000768
Richard Trieucfe3f212011-09-06 18:38:41 +0000769 if (LHSComplexInt && RHSComplexInt) {
770 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
771 RHSComplexInt->getElementType());
Richard Trieu7aa58f12011-09-02 20:58:51 +0000772 assert(order && "inequal types with equal element ordering");
773 if (order > 0) {
774 // _Complex int -> _Complex long
Richard Trieucfe3f212011-09-06 18:38:41 +0000775 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
776 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000777 }
778
Richard Trieuba63ce62011-09-09 01:45:06 +0000779 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000780 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
781 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000782 }
783
Richard Trieucfe3f212011-09-06 18:38:41 +0000784 if (LHSComplexInt) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000785 // int -> _Complex int
Richard Trieucfe3f212011-09-06 18:38:41 +0000786 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
787 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000788 }
789
Richard Trieucfe3f212011-09-06 18:38:41 +0000790 assert(RHSComplexInt);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000791 // int -> _Complex int
Richard Trieuba63ce62011-09-09 01:45:06 +0000792 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000793 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
794 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000795}
796
797/// \brief Handle integer arithmetic conversions. Helper function of
798/// UsualArithmeticConversions()
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000799static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
800 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000801 QualType RHSType, bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000802 // The rules for this case are in C99 6.3.1.8
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000803 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
804 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
805 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
806 if (LHSSigned == RHSSigned) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000807 // Same signedness; use the higher-ranked type
808 if (order >= 0) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000809 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
810 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000811 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000812 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
813 return RHSType;
814 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000815 // The unsigned type has greater than or equal rank to the
816 // signed type, so use the unsigned type
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000817 if (RHSSigned) {
818 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
819 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000820 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000821 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
822 return RHSType;
823 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000824 // The two types are different widths; if we are here, that
825 // means the signed type is larger than the unsigned type, so
826 // use the signed type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000827 if (LHSSigned) {
828 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
829 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000830 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000831 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
832 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000833 } else {
834 // The signed type is higher-ranked than the unsigned type,
835 // but isn't actually any bigger (like unsigned int and long
836 // on most 32-bit systems). Use the unsigned type corresponding
837 // to the signed type.
838 QualType result =
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000839 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
840 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuba63ce62011-09-09 01:45:06 +0000841 if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000842 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000843 return result;
844 }
845}
846
Chris Lattner513165e2008-07-25 21:10:04 +0000847/// UsualArithmeticConversions - Performs various conversions that are common to
848/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000849/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000850/// responsible for emitting appropriate error diagnostics.
851/// FIXME: verify the conversion rules for "complex int" are consistent with
852/// GCC.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000853QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +0000854 bool IsCompAssign) {
855 if (!IsCompAssign) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000856 LHS = UsualUnaryConversions(LHS.take());
857 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000858 return QualType();
859 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000860
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000861 RHS = UsualUnaryConversions(RHS.take());
862 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000863 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000864
Mike Stump11289f42009-09-09 15:08:12 +0000865 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000866 // For example, "const float" and "float" are equivalent.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000867 QualType LHSType =
868 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
869 QualType RHSType =
870 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000871
872 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000873 if (LHSType == RHSType)
874 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000875
876 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
877 // The caller can deal with this (e.g. pointer + int).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000878 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
879 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000880
John McCalld005ac92010-11-13 08:17:45 +0000881 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000882 QualType LHSUnpromotedType = LHSType;
883 if (LHSType->isPromotableIntegerType())
884 LHSType = Context.getPromotedIntegerType(LHSType);
885 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000886 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000887 LHSType = LHSBitfieldPromoteTy;
Richard Trieuba63ce62011-09-09 01:45:06 +0000888 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000889 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000890
John McCalld005ac92010-11-13 08:17:45 +0000891 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000892 if (LHSType == RHSType)
893 return LHSType;
John McCalld005ac92010-11-13 08:17:45 +0000894
895 // At this point, we have two different arithmetic types.
896
897 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000898 if (LHSType->isComplexType() || RHSType->isComplexType())
899 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000900 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000901
902 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000903 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
904 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000905 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000906
907 // Handle GCC complex int extension.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000908 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000909 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000910 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000911
912 // Finally, we have two differing integer types.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000913 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000914 IsCompAssign);
Douglas Gregora11693b2008-11-12 17:17:38 +0000915}
916
Chris Lattner513165e2008-07-25 21:10:04 +0000917//===----------------------------------------------------------------------===//
918// Semantic Analysis for various Expression Types
919//===----------------------------------------------------------------------===//
920
921
Peter Collingbourne91147592011-04-15 00:35:48 +0000922ExprResult
923Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
924 SourceLocation DefaultLoc,
925 SourceLocation RParenLoc,
926 Expr *ControllingExpr,
Richard Trieuba63ce62011-09-09 01:45:06 +0000927 MultiTypeArg ArgTypes,
928 MultiExprArg ArgExprs) {
929 unsigned NumAssocs = ArgTypes.size();
930 assert(NumAssocs == ArgExprs.size());
Peter Collingbourne91147592011-04-15 00:35:48 +0000931
Richard Trieuba63ce62011-09-09 01:45:06 +0000932 ParsedType *ParsedTypes = ArgTypes.release();
933 Expr **Exprs = ArgExprs.release();
Peter Collingbourne91147592011-04-15 00:35:48 +0000934
935 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
936 for (unsigned i = 0; i < NumAssocs; ++i) {
937 if (ParsedTypes[i])
938 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
939 else
940 Types[i] = 0;
941 }
942
943 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
944 ControllingExpr, Types, Exprs,
945 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000946 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000947 return ER;
948}
949
950ExprResult
951Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
952 SourceLocation DefaultLoc,
953 SourceLocation RParenLoc,
954 Expr *ControllingExpr,
955 TypeSourceInfo **Types,
956 Expr **Exprs,
957 unsigned NumAssocs) {
958 bool TypeErrorFound = false,
959 IsResultDependent = ControllingExpr->isTypeDependent(),
960 ContainsUnexpandedParameterPack
961 = ControllingExpr->containsUnexpandedParameterPack();
962
963 for (unsigned i = 0; i < NumAssocs; ++i) {
964 if (Exprs[i]->containsUnexpandedParameterPack())
965 ContainsUnexpandedParameterPack = true;
966
967 if (Types[i]) {
968 if (Types[i]->getType()->containsUnexpandedParameterPack())
969 ContainsUnexpandedParameterPack = true;
970
971 if (Types[i]->getType()->isDependentType()) {
972 IsResultDependent = true;
973 } else {
974 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
975 // complete object type other than a variably modified type."
976 unsigned D = 0;
977 if (Types[i]->getType()->isIncompleteType())
978 D = diag::err_assoc_type_incomplete;
979 else if (!Types[i]->getType()->isObjectType())
980 D = diag::err_assoc_type_nonobject;
981 else if (Types[i]->getType()->isVariablyModifiedType())
982 D = diag::err_assoc_type_variably_modified;
983
984 if (D != 0) {
985 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
986 << Types[i]->getTypeLoc().getSourceRange()
987 << Types[i]->getType();
988 TypeErrorFound = true;
989 }
990
991 // C1X 6.5.1.1p2 "No two generic associations in the same generic
992 // selection shall specify compatible types."
993 for (unsigned j = i+1; j < NumAssocs; ++j)
994 if (Types[j] && !Types[j]->getType()->isDependentType() &&
995 Context.typesAreCompatible(Types[i]->getType(),
996 Types[j]->getType())) {
997 Diag(Types[j]->getTypeLoc().getBeginLoc(),
998 diag::err_assoc_compatible_types)
999 << Types[j]->getTypeLoc().getSourceRange()
1000 << Types[j]->getType()
1001 << Types[i]->getType();
1002 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1003 diag::note_compat_assoc)
1004 << Types[i]->getTypeLoc().getSourceRange()
1005 << Types[i]->getType();
1006 TypeErrorFound = true;
1007 }
1008 }
1009 }
1010 }
1011 if (TypeErrorFound)
1012 return ExprError();
1013
1014 // If we determined that the generic selection is result-dependent, don't
1015 // try to compute the result expression.
1016 if (IsResultDependent)
1017 return Owned(new (Context) GenericSelectionExpr(
1018 Context, KeyLoc, ControllingExpr,
1019 Types, Exprs, NumAssocs, DefaultLoc,
1020 RParenLoc, ContainsUnexpandedParameterPack));
1021
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001022 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +00001023 unsigned DefaultIndex = -1U;
1024 for (unsigned i = 0; i < NumAssocs; ++i) {
1025 if (!Types[i])
1026 DefaultIndex = i;
1027 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1028 Types[i]->getType()))
1029 CompatIndices.push_back(i);
1030 }
1031
1032 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
1033 // type compatible with at most one of the types named in its generic
1034 // association list."
1035 if (CompatIndices.size() > 1) {
1036 // We strip parens here because the controlling expression is typically
1037 // parenthesized in macro definitions.
1038 ControllingExpr = ControllingExpr->IgnoreParens();
1039 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1040 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1041 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001042 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +00001043 E = CompatIndices.end(); I != E; ++I) {
1044 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1045 diag::note_compat_assoc)
1046 << Types[*I]->getTypeLoc().getSourceRange()
1047 << Types[*I]->getType();
1048 }
1049 return ExprError();
1050 }
1051
1052 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
1053 // its controlling expression shall have type compatible with exactly one of
1054 // the types named in its generic association list."
1055 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1056 // We strip parens here because the controlling expression is typically
1057 // parenthesized in macro definitions.
1058 ControllingExpr = ControllingExpr->IgnoreParens();
1059 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1060 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1061 return ExprError();
1062 }
1063
1064 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
1065 // type name that is compatible with the type of the controlling expression,
1066 // then the result expression of the generic selection is the expression
1067 // in that generic association. Otherwise, the result expression of the
1068 // generic selection is the expression in the default generic association."
1069 unsigned ResultIndex =
1070 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1071
1072 return Owned(new (Context) GenericSelectionExpr(
1073 Context, KeyLoc, ControllingExpr,
1074 Types, Exprs, NumAssocs, DefaultLoc,
1075 RParenLoc, ContainsUnexpandedParameterPack,
1076 ResultIndex));
1077}
1078
Steve Naroff83895f72007-09-16 03:34:24 +00001079/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001080/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1081/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1082/// multiple tokens. However, the common case is that StringToks points to one
1083/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001084///
John McCalldadc5752010-08-24 06:29:42 +00001085ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +00001086Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001087 assert(NumStringToks && "Must have at least one string!");
1088
Chris Lattner8a24e582009-01-16 18:51:42 +00001089 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001090 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001091 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001092
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001093 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001094 for (unsigned i = 0; i != NumStringToks; ++i)
1095 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001096
Chris Lattner36fc8792008-02-11 00:02:17 +00001097 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001098 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001099 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001100 else if (Literal.isUTF16())
1101 StrTy = Context.Char16Ty;
1102 else if (Literal.isUTF32())
1103 StrTy = Context.Char32Ty;
Anders Carlsson6b06e182011-04-06 18:42:48 +00001104 else if (Literal.Pascal)
1105 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001106
Douglas Gregorfb65e592011-07-27 05:40:30 +00001107 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1108 if (Literal.isWide())
1109 Kind = StringLiteral::Wide;
1110 else if (Literal.isUTF8())
1111 Kind = StringLiteral::UTF8;
1112 else if (Literal.isUTF16())
1113 Kind = StringLiteral::UTF16;
1114 else if (Literal.isUTF32())
1115 Kind = StringLiteral::UTF32;
1116
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001117 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +00001118 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001119 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001120
Chris Lattner36fc8792008-02-11 00:02:17 +00001121 // Get an array type for the string, according to C99 6.4.5. This includes
1122 // the nul terminator character as well as the string length for pascal
1123 // strings.
1124 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001125 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001126 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001127
Chris Lattner5b183d82006-11-10 05:03:26 +00001128 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +00001129 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00001130 Kind, Literal.Pascal, StrTy,
Alexis Hunt3b791862010-08-30 17:47:05 +00001131 &StringTokLocs[0],
1132 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +00001133}
1134
John McCallc63de662011-02-02 13:00:07 +00001135enum CaptureResult {
1136 /// No capture is required.
1137 CR_NoCapture,
1138
1139 /// A capture is required.
1140 CR_Capture,
1141
John McCall351762c2011-02-07 10:33:21 +00001142 /// A by-ref capture is required.
1143 CR_CaptureByRef,
1144
John McCallc63de662011-02-02 13:00:07 +00001145 /// An error occurred when trying to capture the given variable.
1146 CR_Error
1147};
1148
1149/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +00001150///
John McCallc63de662011-02-02 13:00:07 +00001151/// \param var - the variable referenced
1152/// \param DC - the context which we couldn't capture through
1153static CaptureResult
John McCall351762c2011-02-07 10:33:21 +00001154diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001155 VarDecl *var, DeclContext *DC) {
1156 switch (S.ExprEvalContexts.back().Context) {
1157 case Sema::Unevaluated:
1158 // The argument will never be evaluated, so don't complain.
1159 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +00001160
John McCallc63de662011-02-02 13:00:07 +00001161 case Sema::PotentiallyEvaluated:
1162 case Sema::PotentiallyEvaluatedIfUsed:
1163 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +00001164
John McCallc63de662011-02-02 13:00:07 +00001165 case Sema::PotentiallyPotentiallyEvaluated:
1166 // FIXME: delay these!
1167 break;
Chris Lattner497d7b02009-04-21 22:26:47 +00001168 }
Mike Stump11289f42009-09-09 15:08:12 +00001169
John McCallc63de662011-02-02 13:00:07 +00001170 // Don't diagnose about capture if we're not actually in code right
1171 // now; in general, there are more appropriate places that will
1172 // diagnose this.
1173 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1174
John McCall92d627e2011-03-22 23:15:50 +00001175 // Certain madnesses can happen with parameter declarations, which
1176 // we want to ignore.
1177 if (isa<ParmVarDecl>(var)) {
1178 // - If the parameter still belongs to the translation unit, then
1179 // we're actually just using one parameter in the declaration of
1180 // the next. This is useful in e.g. VLAs.
1181 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1182 return CR_NoCapture;
1183
1184 // - This particular madness can happen in ill-formed default
1185 // arguments; claim it's okay and let downstream code handle it.
1186 if (S.CurContext == var->getDeclContext()->getParent())
1187 return CR_NoCapture;
1188 }
John McCallc63de662011-02-02 13:00:07 +00001189
1190 DeclarationName functionName;
1191 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1192 functionName = fn->getDeclName();
1193 // FIXME: variable from enclosing block that we couldn't capture from!
1194
1195 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1196 << var->getIdentifier() << functionName;
1197 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1198 << var->getIdentifier();
1199
1200 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +00001201}
1202
John McCall351762c2011-02-07 10:33:21 +00001203/// There is a well-formed capture at a particular scope level;
1204/// propagate it through all the nested blocks.
Richard Trieuba63ce62011-09-09 01:45:06 +00001205static CaptureResult propagateCapture(Sema &S, unsigned ValidScopeIndex,
1206 const BlockDecl::Capture &Capture) {
1207 VarDecl *var = Capture.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001208
1209 // Update all the inner blocks with the capture information.
Richard Trieuba63ce62011-09-09 01:45:06 +00001210 for (unsigned i = ValidScopeIndex + 1, e = S.FunctionScopes.size();
John McCall351762c2011-02-07 10:33:21 +00001211 i != e; ++i) {
1212 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1213 innerBlock->Captures.push_back(
Richard Trieuba63ce62011-09-09 01:45:06 +00001214 BlockDecl::Capture(Capture.getVariable(), Capture.isByRef(),
1215 /*nested*/ true, Capture.getCopyExpr()));
John McCall351762c2011-02-07 10:33:21 +00001216 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1217 }
1218
Richard Trieuba63ce62011-09-09 01:45:06 +00001219 return Capture.isByRef() ? CR_CaptureByRef : CR_Capture;
John McCall351762c2011-02-07 10:33:21 +00001220}
1221
1222/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +00001223/// given value in the current context requires a variable capture.
1224///
1225/// This also keeps the captures set in the BlockScopeInfo records
1226/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +00001227static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00001228 ValueDecl *Value) {
John McCallc63de662011-02-02 13:00:07 +00001229 // Only variables ever require capture.
Richard Trieuba63ce62011-09-09 01:45:06 +00001230 VarDecl *var = dyn_cast<VarDecl>(Value);
John McCallf4cd4f92011-02-09 01:13:10 +00001231 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +00001232
1233 // Fast path: variables from the current context never require capture.
1234 DeclContext *DC = S.CurContext;
1235 if (var->getDeclContext() == DC) return CR_NoCapture;
1236
1237 // Only variables with local storage require capture.
1238 // FIXME: What about 'const' variables in C++?
1239 if (!var->hasLocalStorage()) return CR_NoCapture;
1240
1241 // Otherwise, we need to capture.
1242
1243 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +00001244 do {
1245 // Only blocks (and eventually C++0x closures) can capture; other
1246 // scopes don't work.
1247 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +00001248 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +00001249
1250 BlockScopeInfo *blockScope =
1251 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1252 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1253
John McCall351762c2011-02-07 10:33:21 +00001254 // Check whether we've already captured it in this block. If so,
1255 // we're done.
1256 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1257 return propagateCapture(S, functionScopesIndex,
1258 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +00001259
1260 functionScopesIndex--;
1261 DC = cast<BlockDecl>(DC)->getDeclContext();
1262 } while (var->getDeclContext() != DC);
1263
John McCall351762c2011-02-07 10:33:21 +00001264 // Okay, we descended all the way to the block that defines the variable.
1265 // Actually try to capture it.
1266 QualType type = var->getType();
1267
1268 // Prohibit variably-modified types.
1269 if (type->isVariablyModifiedType()) {
1270 S.Diag(loc, diag::err_ref_vm_type);
1271 S.Diag(var->getLocation(), diag::note_declared_at);
1272 return CR_Error;
1273 }
1274
1275 // Prohibit arrays, even in __block variables, but not references to
1276 // them.
1277 if (type->isArrayType()) {
1278 S.Diag(loc, diag::err_ref_array_type);
1279 S.Diag(var->getLocation(), diag::note_declared_at);
1280 return CR_Error;
1281 }
1282
1283 S.MarkDeclarationReferenced(loc, var);
1284
1285 // The BlocksAttr indicates the variable is bound by-reference.
1286 bool byRef = var->hasAttr<BlocksAttr>();
1287
1288 // Build a copy expression.
1289 Expr *copyExpr = 0;
John McCalla85af562011-04-28 02:15:35 +00001290 const RecordType *rtype;
1291 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1292 (rtype = type->getAs<RecordType>())) {
1293
1294 // The capture logic needs the destructor, so make sure we mark it.
1295 // Usually this is unnecessary because most local variables have
1296 // their destructors marked at declaration time, but parameters are
1297 // an exception because it's technically only the call site that
1298 // actually requires the destructor.
1299 if (isa<ParmVarDecl>(var))
1300 S.FinalizeVarWithDestructor(var, rtype);
1301
John McCall351762c2011-02-07 10:33:21 +00001302 // According to the blocks spec, the capture of a variable from
1303 // the stack requires a const copy constructor. This is not true
1304 // of the copy/move done to move a __block variable to the heap.
1305 type.addConst();
1306
1307 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1308 ExprResult result =
1309 S.PerformCopyInitialization(
1310 InitializedEntity::InitializeBlock(var->getLocation(),
1311 type, false),
1312 loc, S.Owned(declRef));
1313
1314 // Build a full-expression copy expression if initialization
1315 // succeeded and used a non-trivial constructor. Recover from
1316 // errors by pretending that the copy isn't necessary.
1317 if (!result.isInvalid() &&
1318 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1319 result = S.MaybeCreateExprWithCleanups(result);
1320 copyExpr = result.take();
1321 }
1322 }
1323
1324 // We're currently at the declarer; go back to the closure.
1325 functionScopesIndex++;
1326 BlockScopeInfo *blockScope =
1327 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1328
1329 // Build a valid capture in this scope.
1330 blockScope->Captures.push_back(
1331 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1332 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1333
1334 // Propagate that to inner captures if necessary.
1335 return propagateCapture(S, functionScopesIndex,
1336 blockScope->Captures.back());
1337}
1338
Richard Trieuba63ce62011-09-09 01:45:06 +00001339static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *VD,
John McCall351762c2011-02-07 10:33:21 +00001340 const DeclarationNameInfo &NameInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00001341 bool ByRef) {
1342 assert(isa<VarDecl>(VD) && "capturing non-variable");
John McCall351762c2011-02-07 10:33:21 +00001343
Richard Trieuba63ce62011-09-09 01:45:06 +00001344 VarDecl *var = cast<VarDecl>(VD);
John McCall351762c2011-02-07 10:33:21 +00001345 assert(var->hasLocalStorage() && "capturing non-local");
Richard Trieuba63ce62011-09-09 01:45:06 +00001346 assert(ByRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
John McCall351762c2011-02-07 10:33:21 +00001347
1348 QualType exprType = var->getType().getNonReferenceType();
1349
1350 BlockDeclRefExpr *BDRE;
Richard Trieuba63ce62011-09-09 01:45:06 +00001351 if (!ByRef) {
John McCall351762c2011-02-07 10:33:21 +00001352 // The variable will be bound by copy; make it const within the
1353 // closure, but record that this was done in the expression.
1354 bool constAdded = !exprType.isConstQualified();
1355 exprType.addConst();
1356
1357 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1358 NameInfo.getLoc(), false,
1359 constAdded);
1360 } else {
1361 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1362 NameInfo.getLoc(), true);
1363 }
1364
1365 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001366}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001367
John McCalldadc5752010-08-24 06:29:42 +00001368ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001369Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001370 SourceLocation Loc,
1371 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001372 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001373 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001374}
1375
John McCallf4cd4f92011-02-09 01:13:10 +00001376/// BuildDeclRefExpr - Build an expression that references a
1377/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001378ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001379Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001380 const DeclarationNameInfo &NameInfo,
1381 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001382 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001383
John McCall086a4642010-11-24 05:12:34 +00001384 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001385 SS? SS->getWithLocInContext(Context)
1386 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001387 D, NameInfo, Ty, VK);
1388
1389 // Just in case we're building an illegal pointer-to-member.
1390 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1391 E->setObjectKind(OK_BitField);
1392
1393 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001394}
1395
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001396/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001397/// possibly a list of template arguments.
1398///
1399/// If this produces template arguments, it is permitted to call
1400/// DecomposeTemplateName.
1401///
1402/// This actually loses a lot of source location information for
1403/// non-standard name kinds; we should consider preserving that in
1404/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001405void
1406Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1407 TemplateArgumentListInfo &Buffer,
1408 DeclarationNameInfo &NameInfo,
1409 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001410 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1411 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1412 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1413
Douglas Gregor5476205b2011-06-23 00:49:38 +00001414 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001415 Id.TemplateId->getTemplateArgs(),
1416 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001417 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001418 TemplateArgsPtr.release();
1419
John McCall3e56fd42010-08-23 07:28:44 +00001420 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001421 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001422 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001423 TemplateArgs = &Buffer;
1424 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001425 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001426 TemplateArgs = 0;
1427 }
1428}
1429
John McCalld681c392009-12-16 08:11:27 +00001430/// Diagnose an empty lookup.
1431///
1432/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001433bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001434 CorrectTypoContext CTC,
1435 TemplateArgumentListInfo *ExplicitTemplateArgs,
1436 Expr **Args, unsigned NumArgs) {
John McCalld681c392009-12-16 08:11:27 +00001437 DeclarationName Name = R.getLookupName();
1438
John McCalld681c392009-12-16 08:11:27 +00001439 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001440 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001441 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1442 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001443 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001444 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001445 diagnostic_suggest = diag::err_undeclared_use_suggest;
1446 }
John McCalld681c392009-12-16 08:11:27 +00001447
Douglas Gregor598b08f2009-12-31 05:20:13 +00001448 // If the original lookup was an unqualified lookup, fake an
1449 // unqualified lookup. This is useful when (for example) the
1450 // original lookup would not have found something because it was a
1451 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001452 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001453 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001454 if (isa<CXXRecordDecl>(DC)) {
1455 LookupQualifiedName(R, DC);
1456
1457 if (!R.empty()) {
1458 // Don't give errors about ambiguities in this lookup.
1459 R.suppressDiagnostics();
1460
1461 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1462 bool isInstance = CurMethod &&
1463 CurMethod->isInstance() &&
1464 DC == CurMethod->getParent();
1465
1466 // Give a code modification hint to insert 'this->'.
1467 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1468 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001469 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001470 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1471 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001472 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001473 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001474 if (DepMethod) {
Francois Pichet0706d202011-09-17 17:15:52 +00001475 if (getLangOptions().MicrosoftExt)
Francois Pichetbcf64712011-09-07 00:14:57 +00001476 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyfe712382010-08-20 20:54:15 +00001477 Diag(R.getNameLoc(), diagnostic) << Name
1478 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1479 QualType DepThisType = DepMethod->getThisType(Context);
1480 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1481 R.getNameLoc(), DepThisType, false);
1482 TemplateArgumentListInfo TList;
1483 if (ULE->hasExplicitTemplateArgs())
1484 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001485
Douglas Gregore16af532011-02-28 18:50:33 +00001486 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001487 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001488 CXXDependentScopeMemberExpr *DepExpr =
1489 CXXDependentScopeMemberExpr::Create(
1490 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001491 SS.getWithLocInContext(Context), NULL,
Francois Pichet4391c752011-09-04 23:00:48 +00001492 R.getLookupNameInfo(),
1493 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyfe712382010-08-20 20:54:15 +00001494 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001495 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001496 // FIXME: we should be able to handle this case too. It is correct
1497 // to add this-> here. This is a workaround for PR7947.
1498 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001499 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001500 } else {
John McCalld681c392009-12-16 08:11:27 +00001501 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001502 }
John McCalld681c392009-12-16 08:11:27 +00001503
1504 // Do we really want to note all of these?
1505 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1506 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1507
1508 // Tell the callee to try to recover.
1509 return false;
1510 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001511
1512 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001513 }
1514 }
1515
Douglas Gregor598b08f2009-12-31 05:20:13 +00001516 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001517 TypoCorrection Corrected;
1518 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1519 S, &SS, NULL, false, CTC))) {
1520 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1521 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1522 R.setLookupName(Corrected.getCorrection());
1523
Hans Wennborg38198de2011-07-12 08:45:31 +00001524 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001525 if (Corrected.isOverloaded()) {
1526 OverloadCandidateSet OCS(R.getNameLoc());
1527 OverloadCandidateSet::iterator Best;
1528 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1529 CDEnd = Corrected.end();
1530 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001531 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001532 dyn_cast<FunctionTemplateDecl>(*CD))
1533 AddTemplateOverloadCandidate(
1534 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1535 Args, NumArgs, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001536 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1537 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1538 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1539 Args, NumArgs, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001540 }
1541 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1542 case OR_Success:
1543 ND = Best->Function;
1544 break;
1545 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001546 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001547 }
1548 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001549 R.addDecl(ND);
1550 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001551 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001552 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1553 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001554 else
1555 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001556 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001557 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001558 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1559 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001560 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001561 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001562
1563 // Tell the callee to try to recover.
1564 return false;
1565 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001566
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001567 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001568 // FIXME: If we ended up with a typo for a type name or
1569 // Objective-C class name, we're in trouble because the parser
1570 // is in the wrong place to recover. Suggest the typo
1571 // correction, but don't make it a fix-it since we're not going
1572 // to recover well anyway.
1573 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001574 Diag(R.getNameLoc(), diagnostic_suggest)
1575 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001576 else
1577 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001578 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001579 << SS.getRange();
1580
1581 // Don't try to recover; it won't work.
1582 return true;
1583 }
1584 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001585 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001586 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001587 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001588 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001589 else
Douglas Gregor25363982010-01-01 00:15:04 +00001590 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001591 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001592 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001593 return true;
1594 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001595 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001596 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001597
1598 // Emit a special diagnostic for failed member lookups.
1599 // FIXME: computing the declaration context might fail here (?)
1600 if (!SS.isEmpty()) {
1601 Diag(R.getNameLoc(), diag::err_no_member)
1602 << Name << computeDeclContext(SS, false)
1603 << SS.getRange();
1604 return true;
1605 }
1606
John McCalld681c392009-12-16 08:11:27 +00001607 // Give up, we can't recover.
1608 Diag(R.getNameLoc(), diagnostic) << Name;
1609 return true;
1610}
1611
John McCalldadc5752010-08-24 06:29:42 +00001612ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001613 CXXScopeSpec &SS,
1614 UnqualifiedId &Id,
1615 bool HasTrailingLParen,
Richard Trieuba63ce62011-09-09 01:45:06 +00001616 bool IsAddressOfOperand) {
1617 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00001618 "cannot be direct & operand and have a trailing lparen");
1619
1620 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001621 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001622
John McCall10eae182009-11-30 22:42:35 +00001623 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001624
1625 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001626 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001627 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001628 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001629
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001630 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001631 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001632 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001633
John McCalle66edc12009-11-24 19:00:30 +00001634 // C++ [temp.dep.expr]p3:
1635 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001636 // -- an identifier that was declared with a dependent type,
1637 // (note: handled after lookup)
1638 // -- a template-id that is dependent,
1639 // (note: handled in BuildTemplateIdExpr)
1640 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001641 // -- a nested-name-specifier that contains a class-name that
1642 // names a dependent type.
1643 // Determine whether this is a member of an unknown specialization;
1644 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001645 bool DependentID = false;
1646 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1647 Name.getCXXNameType()->isDependentType()) {
1648 DependentID = true;
1649 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001650 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001651 if (RequireCompleteDeclContext(SS, DC))
1652 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001653 } else {
1654 DependentID = true;
1655 }
1656 }
1657
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001658 if (DependentID)
Richard Trieuba63ce62011-09-09 01:45:06 +00001659 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001660 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001661
Fariborz Jahanian86151342010-07-22 23:33:21 +00001662 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001663 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001664 LookupResult R(*this, NameInfo,
1665 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1666 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001667 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001668 // Lookup the template name again to correctly establish the context in
1669 // which it was found. This is really unfortunate as we already did the
1670 // lookup to determine that it was a template name in the first place. If
1671 // this becomes a performance hit, we can work harder to preserve those
1672 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001673 bool MemberOfUnknownSpecialization;
1674 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1675 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001676
1677 if (MemberOfUnknownSpecialization ||
1678 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Richard Trieuba63ce62011-09-09 01:45:06 +00001679 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregora5226932011-02-04 13:35:07 +00001680 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001681 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001682 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001683 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001684
Douglas Gregora5226932011-02-04 13:35:07 +00001685 // If the result might be in a dependent base class, this is a dependent
1686 // id-expression.
1687 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Richard Trieuba63ce62011-09-09 01:45:06 +00001688 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
Douglas Gregora5226932011-02-04 13:35:07 +00001689 TemplateArgs);
1690
John McCalle66edc12009-11-24 19:00:30 +00001691 // If this reference is in an Objective-C method, then we need to do
1692 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001693 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001694 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001695 if (E.isInvalid())
1696 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001697
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001698 if (Expr *Ex = E.takeAs<Expr>())
1699 return Owned(Ex);
1700
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001701 // for further use, this must be set to false if in class method.
1702 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001703 }
Chris Lattner59a25942008-03-31 00:36:02 +00001704 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001705
John McCalle66edc12009-11-24 19:00:30 +00001706 if (R.isAmbiguous())
1707 return ExprError();
1708
Douglas Gregor171c45a2009-02-18 21:56:37 +00001709 // Determine whether this name might be a candidate for
1710 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001711 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001712
John McCalle66edc12009-11-24 19:00:30 +00001713 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001714 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001715 // in C90, extension in C99, forbidden in C++).
1716 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1717 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1718 if (D) R.addDecl(D);
1719 }
1720
1721 // If this name wasn't predeclared and if this is not a function
1722 // call, diagnose the problem.
1723 if (R.empty()) {
Francois Pichetd8e4e412011-09-24 10:38:05 +00001724
1725 // In Microsoft mode, if we are inside a template class member function
1726 // and we can't resolve an identifier then assume the identifier is type
1727 // dependent. The goal is to postpone name lookup to instantiation time
1728 // to be able to search into type dependent base classes.
1729 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
1730 isa<CXXMethodDecl>(CurContext))
1731 return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
1732 TemplateArgs);
1733
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001734 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001735 return ExprError();
1736
1737 assert(!R.empty() &&
1738 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001739
1740 // If we found an Objective-C instance variable, let
1741 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001742 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001743 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1744 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001745 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanian44653702011-09-23 23:11:38 +00001746 // In a hopelessly buggy code, Objective-C instance variable
1747 // lookup fails and no expression will be built to reference it.
1748 if (!E.isInvalid() && !E.get())
1749 return ExprError();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001750 return move(E);
1751 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001752 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001753 }
Mike Stump11289f42009-09-09 15:08:12 +00001754
John McCalle66edc12009-11-24 19:00:30 +00001755 // This is guaranteed from this point on.
1756 assert(!R.empty() || ADL);
1757
John McCall2d74de92009-12-01 22:10:20 +00001758 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001759 // C++ [class.mfct.non-static]p3:
1760 // When an id-expression that is not part of a class member access
1761 // syntax and not used to form a pointer to member is used in the
1762 // body of a non-static member function of class X, if name lookup
1763 // resolves the name in the id-expression to a non-static non-type
1764 // member of some class C, the id-expression is transformed into a
1765 // class member access expression using (*this) as the
1766 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001767 //
1768 // But we don't actually need to do this for '&' operands if R
1769 // resolved to a function or overloaded function set, because the
1770 // expression is ill-formed if it actually works out to be a
1771 // non-static member function:
1772 //
1773 // C++ [expr.ref]p4:
1774 // Otherwise, if E1.E2 refers to a non-static member function. . .
1775 // [t]he expression can be used only as the left-hand operand of a
1776 // member function call.
1777 //
1778 // There are other safeguards against such uses, but it's important
1779 // to get this right here so that we don't end up making a
1780 // spuriously dependent expression if we're inside a dependent
1781 // instance method.
John McCall57500772009-12-16 12:17:52 +00001782 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001783 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00001784 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00001785 MightBeImplicitMember = true;
1786 else if (!SS.isEmpty())
1787 MightBeImplicitMember = false;
1788 else if (R.isOverloadedResult())
1789 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001790 else if (R.isUnresolvableResult())
1791 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001792 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001793 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1794 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001795
1796 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001797 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001798 }
1799
John McCalle66edc12009-11-24 19:00:30 +00001800 if (TemplateArgs)
1801 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001802
John McCalle66edc12009-11-24 19:00:30 +00001803 return BuildDeclarationNameExpr(SS, R, ADL);
1804}
1805
John McCall10eae182009-11-30 22:42:35 +00001806/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1807/// declaration name, generally during template instantiation.
1808/// There's a large number of things which don't need to be done along
1809/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001810ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001811Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001812 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001813 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001814 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001815 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00001816
John McCall0b66eb32010-05-01 00:40:08 +00001817 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001818 return ExprError();
1819
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001820 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001821 LookupQualifiedName(R, DC);
1822
1823 if (R.isAmbiguous())
1824 return ExprError();
1825
1826 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001827 Diag(NameInfo.getLoc(), diag::err_no_member)
1828 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001829 return ExprError();
1830 }
1831
1832 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1833}
1834
1835/// LookupInObjCMethod - The parser has read a name in, and Sema has
1836/// detected that we're currently inside an ObjC method. Perform some
1837/// additional lookup.
1838///
1839/// Ideally, most of this would be done by lookup, but there's
1840/// actually quite a lot of extra work involved.
1841///
1842/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001843ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001844Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001845 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001846 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001847 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001848
John McCalle66edc12009-11-24 19:00:30 +00001849 // There are two cases to handle here. 1) scoped lookup could have failed,
1850 // in which case we should look for an ivar. 2) scoped lookup could have
1851 // found a decl, but that decl is outside the current instance method (i.e.
1852 // a global variable). In these two cases, we do a lookup for an ivar with
1853 // this name, if the lookup sucedes, we replace it our current decl.
1854
1855 // If we're in a class method, we don't normally want to look for
1856 // ivars. But if we don't find anything else, and there's an
1857 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001858 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001859
1860 bool LookForIvars;
1861 if (Lookup.empty())
1862 LookForIvars = true;
1863 else if (IsClassMethod)
1864 LookForIvars = false;
1865 else
1866 LookForIvars = (Lookup.isSingleResult() &&
1867 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001868 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001869 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001870 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001871 ObjCInterfaceDecl *ClassDeclared;
1872 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1873 // Diagnose using an ivar in a class method.
1874 if (IsClassMethod)
1875 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1876 << IV->getDeclName());
1877
1878 // If we're referencing an invalid decl, just return this as a silent
1879 // error node. The error diagnostic was already emitted on the decl.
1880 if (IV->isInvalidDecl())
1881 return ExprError();
1882
1883 // Check if referencing a field with __attribute__((deprecated)).
1884 if (DiagnoseUseOfDecl(IV, Loc))
1885 return ExprError();
1886
1887 // Diagnose the use of an ivar outside of the declaring class.
1888 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1889 ClassDeclared != IFace)
1890 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1891
1892 // FIXME: This should use a new expr for a direct reference, don't
1893 // turn this into Self->ivar, just return a BareIVarExpr or something.
1894 IdentifierInfo &II = Context.Idents.get("self");
1895 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001896 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001897 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001898 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00001899 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001900 SelfName, false, false);
1901 if (SelfExpr.isInvalid())
1902 return ExprError();
1903
John Wiegley01296292011-04-08 18:41:53 +00001904 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1905 if (SelfExpr.isInvalid())
1906 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001907
John McCalle66edc12009-11-24 19:00:30 +00001908 MarkDeclarationReferenced(Loc, IV);
1909 return Owned(new (Context)
1910 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001911 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001912 }
Chris Lattner87313662010-04-12 05:10:17 +00001913 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001914 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00001915 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001916 ObjCInterfaceDecl *ClassDeclared;
1917 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1918 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1919 IFace == ClassDeclared)
1920 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1921 }
1922 }
1923
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001924 if (Lookup.empty() && II && AllowBuiltinCreation) {
1925 // FIXME. Consolidate this with similar code in LookupName.
1926 if (unsigned BuiltinID = II->getBuiltinID()) {
1927 if (!(getLangOptions().CPlusPlus &&
1928 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1929 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1930 S, Lookup.isForRedeclaration(),
1931 Lookup.getNameLoc());
1932 if (D) Lookup.addDecl(D);
1933 }
1934 }
1935 }
John McCalle66edc12009-11-24 19:00:30 +00001936 // Sentinel value saying that we didn't do anything special.
1937 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001938}
John McCalld14a8642009-11-21 08:51:07 +00001939
John McCall16df1e52010-03-30 21:47:33 +00001940/// \brief Cast a base object to a member's actual type.
1941///
1942/// Logically this happens in three phases:
1943///
1944/// * First we cast from the base type to the naming class.
1945/// The naming class is the class into which we were looking
1946/// when we found the member; it's the qualifier type if a
1947/// qualifier was provided, and otherwise it's the base type.
1948///
1949/// * Next we cast from the naming class to the declaring class.
1950/// If the member we found was brought into a class's scope by
1951/// a using declaration, this is that class; otherwise it's
1952/// the class declaring the member.
1953///
1954/// * Finally we cast from the declaring class to the "true"
1955/// declaring class of the member. This conversion does not
1956/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001957ExprResult
1958Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001959 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001960 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001961 NamedDecl *Member) {
1962 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1963 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001964 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001965
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001966 QualType DestRecordType;
1967 QualType DestType;
1968 QualType FromRecordType;
1969 QualType FromType = From->getType();
1970 bool PointerConversions = false;
1971 if (isa<FieldDecl>(Member)) {
1972 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001973
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001974 if (FromType->getAs<PointerType>()) {
1975 DestType = Context.getPointerType(DestRecordType);
1976 FromRecordType = FromType->getPointeeType();
1977 PointerConversions = true;
1978 } else {
1979 DestType = DestRecordType;
1980 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001981 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001982 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1983 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00001984 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001985
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001986 DestType = Method->getThisType(Context);
1987 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001988
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001989 if (FromType->getAs<PointerType>()) {
1990 FromRecordType = FromType->getPointeeType();
1991 PointerConversions = true;
1992 } else {
1993 FromRecordType = FromType;
1994 DestType = DestRecordType;
1995 }
1996 } else {
1997 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00001998 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001999 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002000
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002001 if (DestType->isDependentType() || FromType->isDependentType())
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 // If the unqualified types are the same, no conversion is necessary.
2005 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002006 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002007
John McCall16df1e52010-03-30 21:47:33 +00002008 SourceRange FromRange = From->getSourceRange();
2009 SourceLocation FromLoc = FromRange.getBegin();
2010
Eli Friedmanbe4b3632011-09-27 21:58:52 +00002011 ExprValueKind VK = From->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002012
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002013 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002014 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002015 // class name.
2016 //
2017 // If the member was a qualified name and the qualified referred to a
2018 // specific base subobject type, we'll cast to that intermediate type
2019 // first and then to the object in which the member is declared. That allows
2020 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2021 //
2022 // class Base { public: int x; };
2023 // class Derived1 : public Base { };
2024 // class Derived2 : public Base { };
2025 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2026 //
2027 // void VeryDerived::f() {
2028 // x = 17; // error: ambiguous base subobjects
2029 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2030 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002031 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002032 QualType QType = QualType(Qualifier->getAsType(), 0);
2033 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2034 assert(QType->isRecordType() && "lookup done with non-record type");
2035
2036 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2037
2038 // In C++98, the qualifier type doesn't actually have to be a base
2039 // type of the object type, in which case we just ignore it.
2040 // Otherwise build the appropriate casts.
2041 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002042 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002043 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002044 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002045 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002046
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002047 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002048 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002049 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2050 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002051
2052 FromType = QType;
2053 FromRecordType = QRecordType;
2054
2055 // If the qualifier type was the same as the destination type,
2056 // we're done.
2057 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002058 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002059 }
2060 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002061
John McCall16df1e52010-03-30 21:47:33 +00002062 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002063
John McCall16df1e52010-03-30 21:47:33 +00002064 // If we actually found the member through a using declaration, cast
2065 // down to the using declaration's type.
2066 //
2067 // Pointer equality is fine here because only one declaration of a
2068 // class ever has member declarations.
2069 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2070 assert(isa<UsingShadowDecl>(FoundDecl));
2071 QualType URecordType = Context.getTypeDeclType(
2072 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2073
2074 // We only need to do this if the naming-class to declaring-class
2075 // conversion is non-trivial.
2076 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2077 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002078 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002079 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002080 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002081 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002082
John McCall16df1e52010-03-30 21:47:33 +00002083 QualType UType = URecordType;
2084 if (PointerConversions)
2085 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002086 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2087 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002088 FromType = UType;
2089 FromRecordType = URecordType;
2090 }
2091
2092 // We don't do access control for the conversion from the
2093 // declaring class to the true declaring class.
2094 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002095 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002096
John McCallcf142162010-08-07 06:22:56 +00002097 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002098 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2099 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002100 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002101 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002102
John Wiegley01296292011-04-08 18:41:53 +00002103 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2104 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002105}
Douglas Gregor3256d042009-06-30 15:47:41 +00002106
John McCalle66edc12009-11-24 19:00:30 +00002107bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002108 const LookupResult &R,
2109 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002110 // Only when used directly as the postfix-expression of a call.
2111 if (!HasTrailingLParen)
2112 return false;
2113
2114 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002115 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002116 return false;
2117
2118 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002119 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002120 return false;
2121
2122 // Turn off ADL when we find certain kinds of declarations during
2123 // normal lookup:
2124 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2125 NamedDecl *D = *I;
2126
2127 // C++0x [basic.lookup.argdep]p3:
2128 // -- a declaration of a class member
2129 // Since using decls preserve this property, we check this on the
2130 // original decl.
John McCall57500772009-12-16 12:17:52 +00002131 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002132 return false;
2133
2134 // C++0x [basic.lookup.argdep]p3:
2135 // -- a block-scope function declaration that is not a
2136 // using-declaration
2137 // NOTE: we also trigger this for function templates (in fact, we
2138 // don't check the decl type at all, since all other decl types
2139 // turn off ADL anyway).
2140 if (isa<UsingShadowDecl>(D))
2141 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2142 else if (D->getDeclContext()->isFunctionOrMethod())
2143 return false;
2144
2145 // C++0x [basic.lookup.argdep]p3:
2146 // -- a declaration that is neither a function or a function
2147 // template
2148 // And also for builtin functions.
2149 if (isa<FunctionDecl>(D)) {
2150 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2151
2152 // But also builtin functions.
2153 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2154 return false;
2155 } else if (!isa<FunctionTemplateDecl>(D))
2156 return false;
2157 }
2158
2159 return true;
2160}
2161
2162
John McCalld14a8642009-11-21 08:51:07 +00002163/// Diagnoses obvious problems with the use of the given declaration
2164/// as an expression. This is only actually called for lookups that
2165/// were not overloaded, and it doesn't promise that the declaration
2166/// will in fact be used.
2167static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002168 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002169 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2170 return true;
2171 }
2172
2173 if (isa<ObjCInterfaceDecl>(D)) {
2174 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2175 return true;
2176 }
2177
2178 if (isa<NamespaceDecl>(D)) {
2179 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2180 return true;
2181 }
2182
2183 return false;
2184}
2185
John McCalldadc5752010-08-24 06:29:42 +00002186ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002187Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002188 LookupResult &R,
2189 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002190 // If this is a single, fully-resolved result and we don't need ADL,
2191 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002192 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002193 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2194 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002195
2196 // We only need to check the declaration if there's exactly one
2197 // result, because in the overloaded case the results can only be
2198 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002199 if (R.isSingleResult() &&
2200 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002201 return ExprError();
2202
John McCall58cc69d2010-01-27 01:50:18 +00002203 // Otherwise, just build an unresolved lookup expression. Suppress
2204 // any lookup-related diagnostics; we'll hash these out later, when
2205 // we've picked a target.
2206 R.suppressDiagnostics();
2207
John McCalld14a8642009-11-21 08:51:07 +00002208 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002209 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002210 SS.getWithLocInContext(Context),
2211 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002212 NeedsADL, R.isOverloadedResult(),
2213 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002214
2215 return Owned(ULE);
2216}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002217
John McCalld14a8642009-11-21 08:51:07 +00002218/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002219ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002220Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002221 const DeclarationNameInfo &NameInfo,
2222 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002223 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002224 assert(!isa<FunctionTemplateDecl>(D) &&
2225 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002226
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002227 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002228 if (CheckDeclInExpr(*this, Loc, D))
2229 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002230
Douglas Gregore7488b92009-12-01 16:58:18 +00002231 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2232 // Specifically diagnose references to class templates that are missing
2233 // a template argument list.
2234 Diag(Loc, diag::err_template_decl_ref)
2235 << Template << SS.getRange();
2236 Diag(Template->getLocation(), diag::note_template_decl_here);
2237 return ExprError();
2238 }
2239
2240 // Make sure that we're referring to a value.
2241 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2242 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002243 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002244 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002245 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002246 return ExprError();
2247 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002248
Douglas Gregor171c45a2009-02-18 21:56:37 +00002249 // Check whether this declaration can be used. Note that we suppress
2250 // this check when we're going to perform argument-dependent lookup
2251 // on this function name, because this might not be the function
2252 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002253 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002254 return ExprError();
2255
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002256 // Only create DeclRefExpr's for valid Decl's.
2257 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002258 return ExprError();
2259
John McCallf3a88602011-02-03 08:15:49 +00002260 // Handle members of anonymous structs and unions. If we got here,
2261 // and the reference is to a class member indirect field, then this
2262 // must be the subject of a pointer-to-member expression.
2263 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2264 if (!indirectField->isCXXClassMember())
2265 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2266 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002267
Chris Lattner2a9d9892008-10-20 05:16:36 +00002268 // If the identifier reference is inside a block, and it refers to a value
2269 // that is outside the block, create a BlockDeclRefExpr instead of a
2270 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2271 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002272 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002273 // We do not do this for things like enum constants, global variables, etc,
2274 // as they do not get snapshotted.
2275 //
John McCall351762c2011-02-07 10:33:21 +00002276 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002277 case CR_Error:
2278 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002279
John McCallc63de662011-02-02 13:00:07 +00002280 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002281 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2282 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2283
2284 case CR_CaptureByRef:
2285 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2286 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002287
2288 case CR_NoCapture: {
2289 // If this reference is not in a block or if the referenced
2290 // variable is within the block, create a normal DeclRefExpr.
2291
2292 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002293 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002294
2295 switch (D->getKind()) {
2296 // Ignore all the non-ValueDecl kinds.
2297#define ABSTRACT_DECL(kind)
2298#define VALUE(type, base)
2299#define DECL(type, base) \
2300 case Decl::type:
2301#include "clang/AST/DeclNodes.inc"
2302 llvm_unreachable("invalid value decl kind");
2303 return ExprError();
2304
2305 // These shouldn't make it here.
2306 case Decl::ObjCAtDefsField:
2307 case Decl::ObjCIvar:
2308 llvm_unreachable("forming non-member reference to ivar?");
2309 return ExprError();
2310
2311 // Enum constants are always r-values and never references.
2312 // Unresolved using declarations are dependent.
2313 case Decl::EnumConstant:
2314 case Decl::UnresolvedUsingValue:
2315 valueKind = VK_RValue;
2316 break;
2317
2318 // Fields and indirect fields that got here must be for
2319 // pointer-to-member expressions; we just call them l-values for
2320 // internal consistency, because this subexpression doesn't really
2321 // exist in the high-level semantics.
2322 case Decl::Field:
2323 case Decl::IndirectField:
2324 assert(getLangOptions().CPlusPlus &&
2325 "building reference to field in C?");
2326
2327 // These can't have reference type in well-formed programs, but
2328 // for internal consistency we do this anyway.
2329 type = type.getNonReferenceType();
2330 valueKind = VK_LValue;
2331 break;
2332
2333 // Non-type template parameters are either l-values or r-values
2334 // depending on the type.
2335 case Decl::NonTypeTemplateParm: {
2336 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2337 type = reftype->getPointeeType();
2338 valueKind = VK_LValue; // even if the parameter is an r-value reference
2339 break;
2340 }
2341
2342 // For non-references, we need to strip qualifiers just in case
2343 // the template parameter was declared as 'const int' or whatever.
2344 valueKind = VK_RValue;
2345 type = type.getUnqualifiedType();
2346 break;
2347 }
2348
2349 case Decl::Var:
2350 // In C, "extern void blah;" is valid and is an r-value.
2351 if (!getLangOptions().CPlusPlus &&
2352 !type.hasQualifiers() &&
2353 type->isVoidType()) {
2354 valueKind = VK_RValue;
2355 break;
2356 }
2357 // fallthrough
2358
2359 case Decl::ImplicitParam:
2360 case Decl::ParmVar:
2361 // These are always l-values.
2362 valueKind = VK_LValue;
2363 type = type.getNonReferenceType();
2364 break;
2365
2366 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002367 const FunctionType *fty = type->castAs<FunctionType>();
2368
2369 // If we're referring to a function with an __unknown_anytype
2370 // result type, make the entire expression __unknown_anytype.
2371 if (fty->getResultType() == Context.UnknownAnyTy) {
2372 type = Context.UnknownAnyTy;
2373 valueKind = VK_RValue;
2374 break;
2375 }
2376
John McCallf4cd4f92011-02-09 01:13:10 +00002377 // Functions are l-values in C++.
2378 if (getLangOptions().CPlusPlus) {
2379 valueKind = VK_LValue;
2380 break;
2381 }
2382
2383 // C99 DR 316 says that, if a function type comes from a
2384 // function definition (without a prototype), that type is only
2385 // used for checking compatibility. Therefore, when referencing
2386 // the function, we pretend that we don't have the full function
2387 // type.
John McCall2979fe02011-04-12 00:42:48 +00002388 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2389 isa<FunctionProtoType>(fty))
2390 type = Context.getFunctionNoProtoType(fty->getResultType(),
2391 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002392
2393 // Functions are r-values in C.
2394 valueKind = VK_RValue;
2395 break;
2396 }
2397
2398 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002399 // If we're referring to a method with an __unknown_anytype
2400 // result type, make the entire expression __unknown_anytype.
2401 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002402 if (const FunctionProtoType *proto
2403 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002404 if (proto->getResultType() == Context.UnknownAnyTy) {
2405 type = Context.UnknownAnyTy;
2406 valueKind = VK_RValue;
2407 break;
2408 }
2409
John McCallf4cd4f92011-02-09 01:13:10 +00002410 // C++ methods are l-values if static, r-values if non-static.
2411 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2412 valueKind = VK_LValue;
2413 break;
2414 }
2415 // fallthrough
2416
2417 case Decl::CXXConversion:
2418 case Decl::CXXDestructor:
2419 case Decl::CXXConstructor:
2420 valueKind = VK_RValue;
2421 break;
2422 }
2423
2424 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2425 }
2426
John McCallc63de662011-02-02 13:00:07 +00002427 }
John McCall7decc9e2010-11-18 06:31:45 +00002428
John McCall351762c2011-02-07 10:33:21 +00002429 llvm_unreachable("unknown capture result");
2430 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002431}
Chris Lattnere168f762006-11-10 05:29:30 +00002432
John McCall2979fe02011-04-12 00:42:48 +00002433ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002434 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002435
Chris Lattnere168f762006-11-10 05:29:30 +00002436 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002437 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002438 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2439 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2440 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002441 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002442
Chris Lattnera81a0272008-01-12 08:14:25 +00002443 // Pre-defined identifiers are of type char[x], where x is the length of the
2444 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002445
Anders Carlsson2fb08242009-09-08 18:24:21 +00002446 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002447 if (!currentDecl && getCurBlock())
2448 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002449 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002450 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002451 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002452 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002453
Anders Carlsson0b209a82009-09-11 01:22:35 +00002454 QualType ResTy;
2455 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2456 ResTy = Context.DependentTy;
2457 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002458 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002459
Anders Carlsson0b209a82009-09-11 01:22:35 +00002460 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002461 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002462 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2463 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002464 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002465}
2466
John McCalldadc5752010-08-24 06:29:42 +00002467ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002468 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002469 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002470 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002471 if (Invalid)
2472 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002473
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002474 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002475 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002476 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002477 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002478
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002479 QualType Ty;
2480 if (!getLangOptions().CPlusPlus)
2481 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2482 else if (Literal.isWide())
2483 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002484 else if (Literal.isUTF16())
2485 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2486 else if (Literal.isUTF32())
2487 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002488 else if (Literal.isMultiChar())
2489 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002490 else
2491 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002492
Douglas Gregorfb65e592011-07-27 05:40:30 +00002493 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2494 if (Literal.isWide())
2495 Kind = CharacterLiteral::Wide;
2496 else if (Literal.isUTF16())
2497 Kind = CharacterLiteral::UTF16;
2498 else if (Literal.isUTF32())
2499 Kind = CharacterLiteral::UTF32;
2500
2501 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2502 Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002503}
2504
John McCalldadc5752010-08-24 06:29:42 +00002505ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002506 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002507 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2508 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002509 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Douglas Gregore8bbc122011-09-02 00:18:52 +00002510 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002511 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002512 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002513 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002514
Chris Lattner23b7eb62007-06-15 23:05:46 +00002515 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002516 // Add padding so that NumericLiteralParser can overread by one character.
2517 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002518 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002519
Chris Lattner67ca9252007-05-21 01:08:44 +00002520 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002521 bool Invalid = false;
2522 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2523 if (Invalid)
2524 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002525
Mike Stump11289f42009-09-09 15:08:12 +00002526 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002527 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002528 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002529 return ExprError();
2530
Chris Lattner1c20a172007-08-26 03:42:43 +00002531 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002532
Chris Lattner1c20a172007-08-26 03:42:43 +00002533 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002534 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002535 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002536 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002537 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002538 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002539 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002540 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002541
2542 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2543
John McCall53b93a02009-12-24 09:08:04 +00002544 using llvm::APFloat;
2545 APFloat Val(Format);
2546
2547 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002548
2549 // Overflow is always an error, but underflow is only an error if
2550 // we underflowed to zero (APFloat reports denormals as underflow).
2551 if ((result & APFloat::opOverflow) ||
2552 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002553 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002554 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002555 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002556 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002557 APFloat::getLargest(Format).toString(buffer);
2558 } else {
John McCall62abc942010-02-26 23:35:57 +00002559 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002560 APFloat::getSmallest(Format).toString(buffer);
2561 }
2562
2563 Diag(Tok.getLocation(), diagnostic)
2564 << Ty
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002565 << StringRef(buffer.data(), buffer.size());
John McCall53b93a02009-12-24 09:08:04 +00002566 }
2567
2568 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002569 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002570
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002571 if (Ty == Context.DoubleTy) {
2572 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002573 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002574 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2575 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002576 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002577 }
2578 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002579 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002580 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002581 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002582 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002583
Neil Boothac582c52007-08-29 22:00:19 +00002584 // long long is a C99 feature.
2585 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002586 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002587 Diag(Tok.getLocation(), diag::ext_longlong);
2588
Chris Lattner67ca9252007-05-21 01:08:44 +00002589 // Get the value in the widest-possible width.
Douglas Gregore8bbc122011-09-02 00:18:52 +00002590 llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002591
Chris Lattner67ca9252007-05-21 01:08:44 +00002592 if (Literal.GetIntegerValue(ResultVal)) {
2593 // If this value didn't fit into uintmax_t, warn and force to ull.
2594 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002595 Ty = Context.UnsignedLongLongTy;
2596 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002597 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002598 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002599 // If this value fits into a ULL, try to figure out what else it fits into
2600 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002601
Chris Lattner67ca9252007-05-21 01:08:44 +00002602 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2603 // be an unsigned int.
2604 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2605
2606 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002607 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002608 if (!Literal.isLong && !Literal.isLongLong) {
2609 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00002610 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002611
Chris Lattner67ca9252007-05-21 01:08:44 +00002612 // Does it fit in a unsigned int?
2613 if (ResultVal.isIntN(IntSize)) {
2614 // Does it fit in a signed int?
2615 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002616 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002617 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002618 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002619 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002620 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002621 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002622
Chris Lattner67ca9252007-05-21 01:08:44 +00002623 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002624 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002625 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002626
Chris Lattner67ca9252007-05-21 01:08:44 +00002627 // Does it fit in a unsigned long?
2628 if (ResultVal.isIntN(LongSize)) {
2629 // Does it fit in a signed long?
2630 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002631 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002632 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002633 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002634 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002635 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002636 }
2637
Chris Lattner67ca9252007-05-21 01:08:44 +00002638 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002639 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002640 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002641
Chris Lattner67ca9252007-05-21 01:08:44 +00002642 // Does it fit in a unsigned long long?
2643 if (ResultVal.isIntN(LongLongSize)) {
2644 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002645 // To be compatible with MSVC, hex integer literals ending with the
2646 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002647 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
Francois Pichet0706d202011-09-17 17:15:52 +00002648 (getLangOptions().MicrosoftExt && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002649 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002650 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002651 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002652 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002653 }
2654 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002655
Chris Lattner67ca9252007-05-21 01:08:44 +00002656 // If we still couldn't decide a type, we probably have something that
2657 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002658 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002659 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002660 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00002661 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002662 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002663
Chris Lattner55258cf2008-05-09 05:59:00 +00002664 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002665 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002666 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002667 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002668 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002669
Chris Lattner1c20a172007-08-26 03:42:43 +00002670 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2671 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002672 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002673 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002674
2675 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002676}
2677
Richard Trieuba63ce62011-09-09 01:45:06 +00002678ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002679 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002680 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002681}
2682
Chandler Carruth62da79c2011-05-26 08:53:12 +00002683static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2684 SourceLocation Loc,
2685 SourceRange ArgRange) {
2686 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2687 // scalar or vector data type argument..."
2688 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2689 // type (C99 6.2.5p18) or void.
2690 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2691 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2692 << T << ArgRange;
2693 return true;
2694 }
2695
2696 assert((T->isVoidType() || !T->isIncompleteType()) &&
2697 "Scalar types should always be complete");
2698 return false;
2699}
2700
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002701static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2702 SourceLocation Loc,
2703 SourceRange ArgRange,
2704 UnaryExprOrTypeTrait TraitKind) {
2705 // C99 6.5.3.4p1:
2706 if (T->isFunctionType()) {
2707 // alignof(function) is allowed as an extension.
2708 if (TraitKind == UETT_SizeOf)
2709 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2710 return false;
2711 }
2712
2713 // Allow sizeof(void)/alignof(void) as an extension.
2714 if (T->isVoidType()) {
2715 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2716 return false;
2717 }
2718
2719 return true;
2720}
2721
2722static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2723 SourceLocation Loc,
2724 SourceRange ArgRange,
2725 UnaryExprOrTypeTrait TraitKind) {
2726 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2727 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2728 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2729 << T << (TraitKind == UETT_SizeOf)
2730 << ArgRange;
2731 return true;
2732 }
2733
2734 return false;
2735}
2736
Chandler Carruth14502c22011-05-26 08:53:10 +00002737/// \brief Check the constrains on expression operands to unary type expression
2738/// and type traits.
2739///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002740/// Completes any types necessary and validates the constraints on the operand
2741/// expression. The logic mostly mirrors the type-based overload, but may modify
2742/// the expression as it completes the type for that expression through template
2743/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00002744bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00002745 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002746 QualType ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002747
2748 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2749 // the result is the size of the referenced type."
2750 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2751 // result shall be the alignment of the referenced type."
2752 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2753 ExprTy = Ref->getPointeeType();
2754
2755 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002756 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2757 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00002758
2759 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002760 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2761 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002762 return false;
2763
Richard Trieuba63ce62011-09-09 01:45:06 +00002764 if (RequireCompleteExprType(E,
Chandler Carruth7c430c02011-05-27 01:33:31 +00002765 PDiag(diag::err_sizeof_alignof_incomplete_type)
Richard Trieuba63ce62011-09-09 01:45:06 +00002766 << ExprKind << E->getSourceRange(),
Chandler Carruth7c430c02011-05-27 01:33:31 +00002767 std::make_pair(SourceLocation(), PDiag(0))))
2768 return true;
2769
2770 // Completeing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00002771 ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002772 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2773 ExprTy = Ref->getPointeeType();
2774
Richard Trieuba63ce62011-09-09 01:45:06 +00002775 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2776 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002777 return true;
2778
Nico Weber0870deb2011-06-15 02:47:03 +00002779 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002780 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00002781 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2782 QualType OType = PVD->getOriginalType();
2783 QualType Type = PVD->getType();
2784 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002785 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00002786 << Type << OType;
2787 Diag(PVD->getLocation(), diag::note_declared_at);
2788 }
2789 }
2790 }
2791 }
2792
Chandler Carruth7c430c02011-05-27 01:33:31 +00002793 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002794}
2795
2796/// \brief Check the constraints on operands to unary expression and type
2797/// traits.
2798///
2799/// This will complete any types necessary, and validate the various constraints
2800/// on those operands.
2801///
Steve Naroff71b59a92007-06-04 22:22:31 +00002802/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002803/// C99 6.3.2.1p[2-4] all state:
2804/// Except when it is the operand of the sizeof operator ...
2805///
2806/// C++ [expr.sizeof]p4
2807/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2808/// standard conversions are not applied to the operand of sizeof.
2809///
2810/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00002811bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00002812 SourceLocation OpLoc,
2813 SourceRange ExprRange,
2814 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002815 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002816 return false;
2817
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002818 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2819 // the result is the size of the referenced type."
2820 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2821 // result shall be the alignment of the referenced type."
Richard Trieuba63ce62011-09-09 01:45:06 +00002822 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
2823 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002824
Chandler Carruth62da79c2011-05-26 08:53:12 +00002825 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002826 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002827
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002828 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002829 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002830 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00002831 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002832
Richard Trieuba63ce62011-09-09 01:45:06 +00002833 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002834 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002835 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002836 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002837
Richard Trieuba63ce62011-09-09 01:45:06 +00002838 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002839 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002840 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002841
Chris Lattner62975a72009-04-24 00:30:45 +00002842 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002843}
2844
Chandler Carruth14502c22011-05-26 08:53:10 +00002845static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002846 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002847
Mike Stump11289f42009-09-09 15:08:12 +00002848 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002849 if (isa<DeclRefExpr>(E))
2850 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002851
2852 // Cannot know anything else if the expression is dependent.
2853 if (E->isTypeDependent())
2854 return false;
2855
Douglas Gregor71235ec2009-05-02 02:18:30 +00002856 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002857 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2858 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00002859 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002860 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002861
2862 // Alignment of a field access is always okay, so long as it isn't a
2863 // bit-field.
2864 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002865 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002866 return false;
2867
Chandler Carruth14502c22011-05-26 08:53:10 +00002868 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002869}
2870
Chandler Carruth14502c22011-05-26 08:53:10 +00002871bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002872 E = E->IgnoreParens();
2873
2874 // Cannot know anything else if the expression is dependent.
2875 if (E->isTypeDependent())
2876 return false;
2877
Chandler Carruth14502c22011-05-26 08:53:10 +00002878 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002879}
2880
Douglas Gregor0950e412009-03-13 21:01:28 +00002881/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002882ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002883Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2884 SourceLocation OpLoc,
2885 UnaryExprOrTypeTrait ExprKind,
2886 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002887 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002888 return ExprError();
2889
John McCallbcd03502009-12-07 02:54:59 +00002890 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002891
Douglas Gregor0950e412009-03-13 21:01:28 +00002892 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002893 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002894 return ExprError();
2895
2896 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002897 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2898 Context.getSizeType(),
2899 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002900}
2901
2902/// \brief Build a sizeof or alignof expression given an expression
2903/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002904ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00002905Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2906 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00002907 ExprResult PE = CheckPlaceholderExpr(E);
2908 if (PE.isInvalid())
2909 return ExprError();
2910
2911 E = PE.get();
2912
Douglas Gregor0950e412009-03-13 21:01:28 +00002913 // Verify that the operand is valid.
2914 bool isInvalid = false;
2915 if (E->isTypeDependent()) {
2916 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002917 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002918 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002919 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002920 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002921 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00002922 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00002923 isInvalid = true;
2924 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00002925 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002926 }
2927
2928 if (isInvalid)
2929 return ExprError();
2930
2931 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00002932 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00002933 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00002934 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002935}
2936
Peter Collingbournee190dee2011-03-11 19:24:49 +00002937/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2938/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00002939/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002940ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002941Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00002942 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00002943 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002944 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002945 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002946
Richard Trieuba63ce62011-09-09 01:45:06 +00002947 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00002948 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002949 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002950 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002951 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002952
Douglas Gregor0950e412009-03-13 21:01:28 +00002953 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00002954 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00002955 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002956}
2957
John Wiegley01296292011-04-08 18:41:53 +00002958static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00002959 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00002960 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002961 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002962
John McCall34376a62010-12-04 03:47:34 +00002963 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00002964 if (V.get()->getObjectKind() != OK_Ordinary) {
2965 V = S.DefaultLvalueConversion(V.take());
2966 if (V.isInvalid())
2967 return QualType();
2968 }
John McCall34376a62010-12-04 03:47:34 +00002969
Chris Lattnere267f5d2007-08-26 05:39:26 +00002970 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00002971 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002972 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002973
Chris Lattnere267f5d2007-08-26 05:39:26 +00002974 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00002975 if (V.get()->getType()->isArithmeticType())
2976 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002977
John McCall36226622010-10-12 02:09:17 +00002978 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00002979 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00002980 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00002981 if (PR.get() != V.get()) {
2982 V = move(PR);
Richard Trieuba63ce62011-09-09 01:45:06 +00002983 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00002984 }
2985
Chris Lattnere267f5d2007-08-26 05:39:26 +00002986 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00002987 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00002988 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002989 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002990}
2991
2992
Chris Lattnere168f762006-11-10 05:29:30 +00002993
John McCalldadc5752010-08-24 06:29:42 +00002994ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002995Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002996 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002997 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002998 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002999 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003000 case tok::plusplus: Opc = UO_PostInc; break;
3001 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003002 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003003
John McCallb268a282010-08-23 23:25:46 +00003004 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003005}
3006
John McCalldadc5752010-08-24 06:29:42 +00003007ExprResult
John McCallb268a282010-08-23 23:25:46 +00003008Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3009 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003010 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003011 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003012 if (Result.isInvalid()) return ExprError();
3013 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003014
John McCallb268a282010-08-23 23:25:46 +00003015 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003016
Douglas Gregor40412ac2008-11-19 17:17:41 +00003017 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003018 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003019 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003020 Context.DependentTy,
3021 VK_LValue, OK_Ordinary,
3022 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003023 }
3024
Mike Stump11289f42009-09-09 15:08:12 +00003025 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003026 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003027 LHSExp->getType()->isEnumeralType() ||
3028 RHSExp->getType()->isRecordType() ||
3029 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00003030 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003031 }
3032
John McCallb268a282010-08-23 23:25:46 +00003033 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003034}
3035
3036
John McCalldadc5752010-08-24 06:29:42 +00003037ExprResult
John McCallb268a282010-08-23 23:25:46 +00003038Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003039 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00003040 Expr *LHSExp = Base;
3041 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003042
Chris Lattner36d572b2007-07-16 00:14:47 +00003043 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003044 if (!LHSExp->getType()->getAs<VectorType>()) {
3045 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3046 if (Result.isInvalid())
3047 return ExprError();
3048 LHSExp = Result.take();
3049 }
3050 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3051 if (Result.isInvalid())
3052 return ExprError();
3053 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003054
Chris Lattner36d572b2007-07-16 00:14:47 +00003055 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003056 ExprValueKind VK = VK_LValue;
3057 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003058
Steve Naroffc1aadb12007-03-28 21:49:40 +00003059 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003060 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003061 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003062 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003063 Expr *BaseExpr, *IndexExpr;
3064 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003065 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3066 BaseExpr = LHSExp;
3067 IndexExpr = RHSExp;
3068 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003069 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003070 BaseExpr = LHSExp;
3071 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003072 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003073 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003074 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003075 BaseExpr = RHSExp;
3076 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003077 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003078 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003079 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003080 BaseExpr = LHSExp;
3081 IndexExpr = RHSExp;
3082 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003083 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003084 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003085 // Handle the uncommon case of "123[Ptr]".
3086 BaseExpr = RHSExp;
3087 IndexExpr = LHSExp;
3088 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003089 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003090 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003091 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003092 VK = LHSExp->getValueKind();
3093 if (VK != VK_RValue)
3094 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003095
Chris Lattner36d572b2007-07-16 00:14:47 +00003096 // FIXME: need to deal with const...
3097 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003098 } else if (LHSTy->isArrayType()) {
3099 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003100 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003101 // wasn't promoted because of the C90 rule that doesn't
3102 // allow promoting non-lvalue arrays. Warn, then
3103 // force the promotion here.
3104 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3105 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003106 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3107 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003108 LHSTy = LHSExp->getType();
3109
3110 BaseExpr = LHSExp;
3111 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003112 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003113 } else if (RHSTy->isArrayType()) {
3114 // Same as previous, except for 123[f().a] case
3115 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3116 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003117 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3118 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003119 RHSTy = RHSExp->getType();
3120
3121 BaseExpr = RHSExp;
3122 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003123 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003124 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003125 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3126 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003127 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003128 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003129 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003130 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3131 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003132
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003133 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003134 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3135 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003136 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3137
Douglas Gregorac1fb652009-03-24 19:52:54 +00003138 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003139 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3140 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003141 // incomplete types are not object types.
3142 if (ResultType->isFunctionType()) {
3143 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3144 << ResultType << BaseExpr->getSourceRange();
3145 return ExprError();
3146 }
Mike Stump11289f42009-09-09 15:08:12 +00003147
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003148 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3149 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003150 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3151 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003152
3153 // C forbids expressions of unqualified void type from being l-values.
3154 // See IsCForbiddenLValueType.
3155 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003156 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003157 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003158 PDiag(diag::err_subscript_incomplete_type)
3159 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003160 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003161
Chris Lattner62975a72009-04-24 00:30:45 +00003162 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003163 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003164 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3165 << ResultType << BaseExpr->getSourceRange();
3166 return ExprError();
3167 }
Mike Stump11289f42009-09-09 15:08:12 +00003168
John McCall4bc41ae2010-11-18 19:01:18 +00003169 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003170 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003171
Mike Stump4e1f26a2009-02-19 03:04:26 +00003172 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003173 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003174}
3175
John McCalldadc5752010-08-24 06:29:42 +00003176ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003177 FunctionDecl *FD,
3178 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003179 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003180 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003181 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003182 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003183 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003184 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003185 return ExprError();
3186 }
3187
3188 if (Param->hasUninstantiatedDefaultArg()) {
3189 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003190
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003191 // Instantiate the expression.
3192 MultiLevelTemplateArgumentList ArgList
3193 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003194
Nico Weber44887f62010-11-29 18:19:25 +00003195 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003196 = ArgList.getInnermost();
3197 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3198 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003199
Nico Weber44887f62010-11-29 18:19:25 +00003200 ExprResult Result;
3201 {
3202 // C++ [dcl.fct.default]p5:
3203 // The names in the [default argument] expression are bound, and
3204 // the semantic constraints are checked, at the point where the
3205 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003206 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00003207 Result = SubstExpr(UninstExpr, ArgList);
3208 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003209 if (Result.isInvalid())
3210 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003211
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003212 // Check the expression as an initializer for the parameter.
3213 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003214 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003215 InitializationKind Kind
3216 = InitializationKind::CreateCopy(Param->getLocation(),
3217 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3218 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003219
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003220 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3221 Result = InitSeq.Perform(*this, Entity, Kind,
3222 MultiExprArg(*this, &ResultE, 1));
3223 if (Result.isInvalid())
3224 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003225
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003226 // Build the default argument expression.
3227 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3228 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003229 }
3230
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003231 // If the default expression creates temporaries, we need to
3232 // push them to the current stack of expression temporaries so they'll
3233 // be properly destroyed.
3234 // FIXME: We should really be rebuilding the default argument with new
3235 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003236 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3237 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3238 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3239 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3240 ExprTemporaries.push_back(Temporary);
John McCall31168b02011-06-15 23:02:42 +00003241 ExprNeedsCleanups = true;
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003242 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003243
3244 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003245 // Just mark all of the declarations in this potentially-evaluated expression
3246 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003247 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00003248 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003249}
3250
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003251/// ConvertArgumentsForCall - Converts the arguments specified in
3252/// Args/NumArgs to the parameter types of the function FDecl with
3253/// function prototype Proto. Call is the call expression itself, and
3254/// Fn is the function expression. For a C++ member function, this
3255/// routine does not attempt to convert the object argument. Returns
3256/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003257bool
3258Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003259 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003260 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003261 Expr **Args, unsigned NumArgs,
3262 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00003263 // Bail out early if calling a builtin with custom typechecking.
3264 // We don't need to do this in the
3265 if (FDecl)
3266 if (unsigned ID = FDecl->getBuiltinID())
3267 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3268 return false;
3269
Mike Stump4e1f26a2009-02-19 03:04:26 +00003270 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003271 // assignment, to the types of the corresponding parameter, ...
3272 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003273 bool Invalid = false;
Peter Collingbourne740afe22011-10-02 23:49:20 +00003274 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003275
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003276 // If too few arguments are available (and we don't have default
3277 // arguments for the remaining parameters), don't make the call.
3278 if (NumArgs < NumArgsInProto) {
Peter Collingbourne740afe22011-10-02 23:49:20 +00003279 if (NumArgs < MinArgs) {
3280 Diag(RParenLoc, MinArgs == NumArgsInProto
3281 ? diag::err_typecheck_call_too_few_args
3282 : diag::err_typecheck_call_too_few_args_at_least)
Alexis Huntc46382e2010-04-28 23:02:27 +00003283 << Fn->getType()->isBlockPointerType()
Peter Collingbourne740afe22011-10-02 23:49:20 +00003284 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003285
3286 // Emit the location of the prototype.
3287 if (FDecl && !FDecl->getBuiltinID())
3288 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3289 << FDecl;
3290
3291 return true;
3292 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003293 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003294 }
3295
3296 // If too many are passed and not variadic, error on the extras and drop
3297 // them.
3298 if (NumArgs > NumArgsInProto) {
3299 if (!Proto->isVariadic()) {
3300 Diag(Args[NumArgsInProto]->getLocStart(),
Peter Collingbourne740afe22011-10-02 23:49:20 +00003301 MinArgs == NumArgsInProto
3302 ? diag::err_typecheck_call_too_many_args
3303 : diag::err_typecheck_call_too_many_args_at_most)
Alexis Huntc46382e2010-04-28 23:02:27 +00003304 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003305 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003306 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3307 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003308
3309 // Emit the location of the prototype.
3310 if (FDecl && !FDecl->getBuiltinID())
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003311 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3312 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003313
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003314 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003315 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003316 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003317 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003318 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003319 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003320 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003321 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3322 if (Fn->getType()->isBlockPointerType())
3323 CallType = VariadicBlock; // Block
3324 else if (isa<MemberExpr>(Fn))
3325 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003326 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003327 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003328 if (Invalid)
3329 return true;
3330 unsigned TotalNumArgs = AllArgs.size();
3331 for (unsigned i = 0; i < TotalNumArgs; ++i)
3332 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003333
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003334 return false;
3335}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003336
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003337bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3338 FunctionDecl *FDecl,
3339 const FunctionProtoType *Proto,
3340 unsigned FirstProtoArg,
3341 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003342 SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003343 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003344 unsigned NumArgsInProto = Proto->getNumArgs();
3345 unsigned NumArgsToCheck = NumArgs;
3346 bool Invalid = false;
3347 if (NumArgs != NumArgsInProto)
3348 // Use default arguments for missing arguments
3349 NumArgsToCheck = NumArgsInProto;
3350 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003351 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003352 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003353 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003354
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003355 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003356 if (ArgIx < NumArgs) {
3357 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003358
Eli Friedman3164fb12009-03-22 22:00:50 +00003359 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3360 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003361 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003362 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003363 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003364
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003365 // Pass the argument
3366 ParmVarDecl *Param = 0;
3367 if (FDecl && i < FDecl->getNumParams())
3368 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003369
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003370 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003371 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003372 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3373 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003374 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003375 SourceLocation(),
3376 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003377 if (ArgE.isInvalid())
3378 return true;
3379
3380 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003381 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003382 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003383
John McCalldadc5752010-08-24 06:29:42 +00003384 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003385 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003386 if (ArgExpr.isInvalid())
3387 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003388
Anders Carlsson355933d2009-08-25 03:49:14 +00003389 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003390 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003391
3392 // Check for array bounds violations for each argument to the call. This
3393 // check only triggers warnings when the argument isn't a more complex Expr
3394 // with its own checking, such as a BinaryOperator.
3395 CheckArrayAccess(Arg);
3396
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003397 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003398 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003399
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003400 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003401 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003402
3403 // Assume that extern "C" functions with variadic arguments that
3404 // return __unknown_anytype aren't *really* variadic.
3405 if (Proto->getResultType() == Context.UnknownAnyTy &&
3406 FDecl && FDecl->isExternC()) {
3407 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3408 ExprResult arg;
3409 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3410 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3411 else
3412 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3413 Invalid |= arg.isInvalid();
3414 AllArgs.push_back(arg.take());
3415 }
3416
3417 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3418 } else {
3419 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003420 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3421 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003422 Invalid |= Arg.isInvalid();
3423 AllArgs.push_back(Arg.take());
3424 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003425 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00003426
3427 // Check for array bounds violations.
3428 for (unsigned i = ArgIx; i != NumArgs; ++i)
3429 CheckArrayAccess(Args[i]);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003430 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003431 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003432}
3433
John McCall2979fe02011-04-12 00:42:48 +00003434/// Given a function expression of unknown-any type, try to rebuild it
3435/// to have a function type.
3436static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3437
Steve Naroff83895f72007-09-16 03:34:24 +00003438/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003439/// This provides the location of the left/right parens and a list of comma
3440/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003441ExprResult
John McCallb268a282010-08-23 23:25:46 +00003442Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003443 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003444 Expr *ExecConfig) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003445 unsigned NumArgs = ArgExprs.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003446
3447 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003448 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003449 if (Result.isInvalid()) return ExprError();
3450 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003451
Richard Trieuba63ce62011-09-09 01:45:06 +00003452 Expr **Args = ArgExprs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003453
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003454 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003455 // If this is a pseudo-destructor expression, build the call immediately.
3456 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3457 if (NumArgs > 0) {
3458 // Pseudo-destructor calls should not have any arguments.
3459 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003460 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003461 SourceRange(Args[0]->getLocStart(),
3462 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003463
Douglas Gregorad8a3362009-09-04 17:36:40 +00003464 NumArgs = 0;
3465 }
Mike Stump11289f42009-09-09 15:08:12 +00003466
Douglas Gregorad8a3362009-09-04 17:36:40 +00003467 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003468 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003469 }
Mike Stump11289f42009-09-09 15:08:12 +00003470
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003471 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003472 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003473 // FIXME: Will need to cache the results of name lookup (including ADL) in
3474 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003475 bool Dependent = false;
3476 if (Fn->isTypeDependent())
3477 Dependent = true;
3478 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3479 Dependent = true;
3480
Peter Collingbourne41f85462011-02-09 21:07:24 +00003481 if (Dependent) {
3482 if (ExecConfig) {
3483 return Owned(new (Context) CUDAKernelCallExpr(
3484 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3485 Context.DependentTy, VK_RValue, RParenLoc));
3486 } else {
3487 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3488 Context.DependentTy, VK_RValue,
3489 RParenLoc));
3490 }
3491 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003492
3493 // Determine whether this is a call to an object (C++ [over.call.object]).
3494 if (Fn->getType()->isRecordType())
3495 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003496 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003497
John McCall2979fe02011-04-12 00:42:48 +00003498 if (Fn->getType() == Context.UnknownAnyTy) {
3499 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3500 if (result.isInvalid()) return ExprError();
3501 Fn = result.take();
3502 }
3503
John McCall0009fcc2011-04-26 20:42:42 +00003504 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003505 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003506 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003507 }
John McCall0009fcc2011-04-26 20:42:42 +00003508 }
John McCall10eae182009-11-30 22:42:35 +00003509
John McCall0009fcc2011-04-26 20:42:42 +00003510 // Check for overloaded calls. This can happen even in C due to extensions.
3511 if (Fn->getType() == Context.OverloadTy) {
3512 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3513
3514 // We aren't supposed to apply this logic if there's an '&' involved.
3515 if (!find.IsAddressOfOperand) {
3516 OverloadExpr *ovl = find.Expression;
3517 if (isa<UnresolvedLookupExpr>(ovl)) {
3518 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3519 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3520 RParenLoc, ExecConfig);
3521 } else {
John McCall2d74de92009-12-01 22:10:20 +00003522 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003523 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003524 }
3525 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003526 }
3527
Douglas Gregore254f902009-02-04 00:32:51 +00003528 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003529
Eli Friedmane14b1992009-12-26 03:35:45 +00003530 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003531
John McCall57500772009-12-16 12:17:52 +00003532 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003533 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3534 if (UnOp->getOpcode() == UO_AddrOf)
3535 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3536
John McCall57500772009-12-16 12:17:52 +00003537 if (isa<DeclRefExpr>(NakedFn))
3538 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003539 else if (isa<MemberExpr>(NakedFn))
3540 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003541
Peter Collingbourne41f85462011-02-09 21:07:24 +00003542 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3543 ExecConfig);
3544}
3545
3546ExprResult
3547Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003548 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbourne41f85462011-02-09 21:07:24 +00003549 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3550 if (!ConfigDecl)
3551 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3552 << "cudaConfigureCall");
3553 QualType ConfigQTy = ConfigDecl->getType();
3554
3555 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3556 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3557
Richard Trieuba63ce62011-09-09 01:45:06 +00003558 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00003559}
3560
Tanya Lattner55808c12011-06-04 00:47:47 +00003561/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3562///
3563/// __builtin_astype( value, dst type )
3564///
Richard Trieuba63ce62011-09-09 01:45:06 +00003565ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00003566 SourceLocation BuiltinLoc,
3567 SourceLocation RParenLoc) {
3568 ExprValueKind VK = VK_RValue;
3569 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00003570 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3571 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00003572 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3573 return ExprError(Diag(BuiltinLoc,
3574 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003575 << DstTy
3576 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00003577 << E->getSourceRange());
3578 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieucfc491d2011-08-02 04:35:43 +00003579 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003580}
3581
John McCall57500772009-12-16 12:17:52 +00003582/// BuildResolvedCallExpr - Build a call to a resolved expression,
3583/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003584/// unary-convert to an expression of function-pointer or
3585/// block-pointer type.
3586///
3587/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003588ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003589Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3590 SourceLocation LParenLoc,
3591 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003592 SourceLocation RParenLoc,
3593 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00003594 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3595
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003596 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003597 ExprResult Result = UsualUnaryConversions(Fn);
3598 if (Result.isInvalid())
3599 return ExprError();
3600 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003601
Chris Lattner08464942007-12-28 05:29:59 +00003602 // Make the call expr early, before semantic checks. This guarantees cleanup
3603 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003604 CallExpr *TheCall;
3605 if (Config) {
3606 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3607 cast<CallExpr>(Config),
3608 Args, NumArgs,
3609 Context.BoolTy,
3610 VK_RValue,
3611 RParenLoc);
3612 } else {
3613 TheCall = new (Context) CallExpr(Context, Fn,
3614 Args, NumArgs,
3615 Context.BoolTy,
3616 VK_RValue,
3617 RParenLoc);
3618 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003619
John McCallbebede42011-02-26 05:39:39 +00003620 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3621
3622 // Bail out early if calling a builtin with custom typechecking.
3623 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3624 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3625
John McCall31996342011-04-07 08:22:57 +00003626 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003627 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003628 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003629 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3630 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003631 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003632 if (FuncT == 0)
3633 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3634 << Fn->getType() << Fn->getSourceRange());
3635 } else if (const BlockPointerType *BPT =
3636 Fn->getType()->getAs<BlockPointerType>()) {
3637 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3638 } else {
John McCall31996342011-04-07 08:22:57 +00003639 // Handle calls to expressions of unknown-any type.
3640 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003641 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003642 if (rewrite.isInvalid()) return ExprError();
3643 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003644 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003645 goto retry;
3646 }
3647
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003648 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3649 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003650 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003651
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003652 if (getLangOptions().CUDA) {
3653 if (Config) {
3654 // CUDA: Kernel calls must be to global functions
3655 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3656 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3657 << FDecl->getName() << Fn->getSourceRange());
3658
3659 // CUDA: Kernel function must have 'void' return type
3660 if (!FuncT->getResultType()->isVoidType())
3661 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3662 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne34a20b02011-10-02 23:49:15 +00003663 } else {
3664 // CUDA: Calls to global functions must be configured
3665 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
3666 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
3667 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003668 }
3669 }
3670
Eli Friedman3164fb12009-03-22 22:00:50 +00003671 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003672 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00003673 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003674 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003675 return ExprError();
3676
Chris Lattner08464942007-12-28 05:29:59 +00003677 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003678 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003679 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003680
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003681 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003682 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003683 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003684 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003685 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003686 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003687
Douglas Gregord8e97de2009-04-02 15:37:10 +00003688 if (FDecl) {
3689 // Check if we have too few/too many template arguments, based
3690 // on our knowledge of the function definition.
3691 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003692 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003693 const FunctionProtoType *Proto
3694 = Def->getType()->getAs<FunctionProtoType>();
3695 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003696 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3697 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003698 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003699
3700 // If the function we're calling isn't a function prototype, but we have
3701 // a function prototype from a prior declaratiom, use that prototype.
3702 if (!FDecl->hasPrototype())
3703 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003704 }
3705
Steve Naroff0b661582007-08-28 23:30:39 +00003706 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003707 for (unsigned i = 0; i != NumArgs; i++) {
3708 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003709
3710 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003711 InitializedEntity Entity
3712 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003713 Proto->getArgType(i),
3714 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003715 ExprResult ArgE = PerformCopyInitialization(Entity,
3716 SourceLocation(),
3717 Owned(Arg));
3718 if (ArgE.isInvalid())
3719 return true;
3720
3721 Arg = ArgE.takeAs<Expr>();
3722
3723 } else {
John Wiegley01296292011-04-08 18:41:53 +00003724 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3725
3726 if (ArgE.isInvalid())
3727 return true;
3728
3729 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003730 }
3731
Douglas Gregor83025412010-10-26 05:45:40 +00003732 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3733 Arg->getType(),
3734 PDiag(diag::err_call_incomplete_argument)
3735 << Arg->getSourceRange()))
3736 return ExprError();
3737
Chris Lattner08464942007-12-28 05:29:59 +00003738 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003739 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003740 }
Chris Lattner08464942007-12-28 05:29:59 +00003741
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003742 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3743 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003744 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3745 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003746
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003747 // Check for sentinels
3748 if (NDecl)
3749 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003750
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003751 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003752 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003753 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003754 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003755
John McCallbebede42011-02-26 05:39:39 +00003756 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003757 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003758 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003759 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003760 return ExprError();
3761 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003762
John McCallb268a282010-08-23 23:25:46 +00003763 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003764}
3765
John McCalldadc5752010-08-24 06:29:42 +00003766ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003767Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003768 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003769 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003770 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003771 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003772
3773 TypeSourceInfo *TInfo;
3774 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3775 if (!TInfo)
3776 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3777
John McCallb268a282010-08-23 23:25:46 +00003778 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003779}
3780
John McCalldadc5752010-08-24 06:29:42 +00003781ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003782Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00003783 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003784 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003785
Eli Friedman37a186d2008-05-20 05:22:08 +00003786 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003787 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3788 PDiag(diag::err_illegal_decl_array_incomplete_type)
3789 << SourceRange(LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003790 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003791 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00003792 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003793 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00003794 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003795 } else if (!literalType->isDependentType() &&
3796 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003797 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003798 << SourceRange(LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003799 LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003800 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003801
Douglas Gregor85dabae2009-12-16 01:38:02 +00003802 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003803 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003804 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00003805 = InitializationKind::CreateCStyleCast(LParenLoc,
3806 SourceRange(LParenLoc, RParenLoc));
Richard Trieuba63ce62011-09-09 01:45:06 +00003807 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003808 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuba63ce62011-09-09 01:45:06 +00003809 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003810 &literalType);
3811 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003812 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00003813 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003814
Chris Lattner79413952008-12-04 23:50:19 +00003815 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003816 if (isFileScope) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00003817 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003818 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003819 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003820
John McCall7decc9e2010-11-18 06:31:45 +00003821 // In C, compound literals are l-values for some reason.
3822 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3823
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00003824 return MaybeBindToTemporary(
3825 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00003826 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003827}
3828
John McCalldadc5752010-08-24 06:29:42 +00003829ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00003830Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003831 SourceLocation RBraceLoc) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003832 unsigned NumInit = InitArgList.size();
3833 Expr **InitList = InitArgList.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00003834
Steve Naroff30d242c2007-09-15 18:49:24 +00003835 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003836 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003837
Ted Kremenekac034612010-04-13 23:39:13 +00003838 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3839 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003840 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003841 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003842}
3843
John McCallcd78e802011-09-10 01:16:55 +00003844/// Do an explicit extend of the given block pointer if we're in ARC.
3845static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
3846 assert(E.get()->getType()->isBlockPointerType());
3847 assert(E.get()->isRValue());
3848
3849 // Only do this in an r-value context.
3850 if (!S.getLangOptions().ObjCAutoRefCount) return;
3851
3852 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00003853 CK_ARCExtendBlockObject, E.get(),
John McCallcd78e802011-09-10 01:16:55 +00003854 /*base path*/ 0, VK_RValue);
3855 S.ExprNeedsCleanups = true;
3856}
3857
3858/// Prepare a conversion of the given expression to an ObjC object
3859/// pointer type.
3860CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
3861 QualType type = E.get()->getType();
3862 if (type->isObjCObjectPointerType()) {
3863 return CK_BitCast;
3864 } else if (type->isBlockPointerType()) {
3865 maybeExtendBlockObject(*this, E);
3866 return CK_BlockPointerToObjCPointerCast;
3867 } else {
3868 assert(type->isPointerType());
3869 return CK_CPointerToObjCPointerCast;
3870 }
3871}
3872
John McCalld7646252010-11-14 08:17:51 +00003873/// Prepares for a scalar cast, performing all the necessary stages
3874/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00003875static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00003876 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3877 // Also, callers should have filtered out the invalid cases with
3878 // pointers. Everything else should be possible.
3879
John Wiegley01296292011-04-08 18:41:53 +00003880 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00003881 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00003882 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00003883
John McCall9320b872011-09-09 05:25:32 +00003884 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00003885 case Type::STK_MemberPointer:
3886 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00003887
John McCall9320b872011-09-09 05:25:32 +00003888 case Type::STK_CPointer:
3889 case Type::STK_BlockPointer:
3890 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00003891 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00003892 case Type::STK_CPointer:
3893 return CK_BitCast;
3894 case Type::STK_BlockPointer:
3895 return (SrcKind == Type::STK_BlockPointer
3896 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
3897 case Type::STK_ObjCObjectPointer:
3898 if (SrcKind == Type::STK_ObjCObjectPointer)
3899 return CK_BitCast;
3900 else if (SrcKind == Type::STK_CPointer)
3901 return CK_CPointerToObjCPointerCast;
John McCallcd78e802011-09-10 01:16:55 +00003902 else {
3903 maybeExtendBlockObject(S, Src);
John McCall9320b872011-09-09 05:25:32 +00003904 return CK_BlockPointerToObjCPointerCast;
John McCallcd78e802011-09-10 01:16:55 +00003905 }
John McCall8cb679e2010-11-15 09:13:47 +00003906 case Type::STK_Bool:
3907 return CK_PointerToBoolean;
3908 case Type::STK_Integral:
3909 return CK_PointerToIntegral;
3910 case Type::STK_Floating:
3911 case Type::STK_FloatingComplex:
3912 case Type::STK_IntegralComplex:
3913 case Type::STK_MemberPointer:
3914 llvm_unreachable("illegal cast from pointer");
3915 }
3916 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003917
John McCall8cb679e2010-11-15 09:13:47 +00003918 case Type::STK_Bool: // casting from bool is like casting from an integer
3919 case Type::STK_Integral:
3920 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00003921 case Type::STK_CPointer:
3922 case Type::STK_ObjCObjectPointer:
3923 case Type::STK_BlockPointer:
Richard Trieucfc491d2011-08-02 04:35:43 +00003924 if (Src.get()->isNullPointerConstant(S.Context,
3925 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00003926 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00003927 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00003928 case Type::STK_Bool:
3929 return CK_IntegralToBoolean;
3930 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00003931 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00003932 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003933 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003934 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003935 Src = S.ImpCastExprToType(Src.take(),
3936 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003937 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00003938 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003939 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003940 Src = S.ImpCastExprToType(Src.take(),
3941 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003942 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00003943 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003944 case Type::STK_MemberPointer:
3945 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003946 }
3947 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003948
John McCall8cb679e2010-11-15 09:13:47 +00003949 case Type::STK_Floating:
3950 switch (DestTy->getScalarTypeKind()) {
3951 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003952 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00003953 case Type::STK_Bool:
3954 return CK_FloatingToBoolean;
3955 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00003956 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00003957 case Type::STK_FloatingComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003958 Src = S.ImpCastExprToType(Src.take(),
3959 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003960 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00003961 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003962 case Type::STK_IntegralComplex:
Richard Trieucfc491d2011-08-02 04:35:43 +00003963 Src = S.ImpCastExprToType(Src.take(),
3964 DestTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003965 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00003966 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00003967 case Type::STK_CPointer:
3968 case Type::STK_ObjCObjectPointer:
3969 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00003970 llvm_unreachable("valid float->pointer cast?");
3971 case Type::STK_MemberPointer:
3972 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00003973 }
3974 break;
3975
John McCall8cb679e2010-11-15 09:13:47 +00003976 case Type::STK_FloatingComplex:
3977 switch (DestTy->getScalarTypeKind()) {
3978 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00003979 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00003980 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00003981 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00003982 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00003983 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00003984 if (S.Context.hasSameType(ET, DestTy))
3985 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00003986 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00003987 return CK_FloatingCast;
3988 }
John McCall8cb679e2010-11-15 09:13:47 +00003989 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00003990 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00003991 case Type::STK_Integral:
Richard Trieucfc491d2011-08-02 04:35:43 +00003992 Src = S.ImpCastExprToType(Src.take(),
3993 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00003994 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00003995 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00003996 case Type::STK_CPointer:
3997 case Type::STK_ObjCObjectPointer:
3998 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00003999 llvm_unreachable("valid complex float->pointer cast?");
4000 case Type::STK_MemberPointer:
4001 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004002 }
4003 break;
4004
John McCall8cb679e2010-11-15 09:13:47 +00004005 case Type::STK_IntegralComplex:
4006 switch (DestTy->getScalarTypeKind()) {
4007 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004008 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004009 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004010 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004011 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00004012 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00004013 if (S.Context.hasSameType(ET, DestTy))
4014 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00004015 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004016 return CK_IntegralCast;
4017 }
John McCall8cb679e2010-11-15 09:13:47 +00004018 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004019 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004020 case Type::STK_Floating:
Richard Trieucfc491d2011-08-02 04:35:43 +00004021 Src = S.ImpCastExprToType(Src.take(),
4022 SrcTy->getAs<ComplexType>()->getElementType(),
John Wiegley01296292011-04-08 18:41:53 +00004023 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004024 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00004025 case Type::STK_CPointer:
4026 case Type::STK_ObjCObjectPointer:
4027 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004028 llvm_unreachable("valid complex int->pointer cast?");
4029 case Type::STK_MemberPointer:
4030 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004031 }
4032 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00004033 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004034
John McCalld7646252010-11-14 08:17:51 +00004035 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00004036}
4037
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004038/// CheckCastTypes - Check type constraints for casting between types.
Richard Trieuba63ce62011-09-09 01:45:06 +00004039ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc,
4040 SourceRange TypeRange, QualType CastType,
4041 Expr *CastExpr, CastKind &Kind,
4042 ExprValueKind &VK, CXXCastPath &BasePath,
4043 bool FunctionalStyle) {
4044 if (CastExpr->getType() == Context.UnknownAnyTy)
4045 return checkUnknownAnyCast(TypeRange, CastType, CastExpr, Kind, VK,
4046 BasePath);
John McCall31996342011-04-07 08:22:57 +00004047
Sebastian Redl9f831db2009-07-25 15:41:38 +00004048 if (getLangOptions().CPlusPlus)
John McCall31168b02011-06-15 23:02:42 +00004049 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004050 CastExpr->getLocEnd()),
4051 CastType, VK, CastExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00004052 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00004053
Richard Trieuba63ce62011-09-09 01:45:06 +00004054 assert(!CastExpr->getType()->isPlaceholderType());
John McCall3aef3d82011-04-10 19:13:55 +00004055
John McCall7decc9e2010-11-18 06:31:45 +00004056 // We only support r-value casts in C.
4057 VK = VK_RValue;
4058
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004059 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4060 // type needs to be scalar.
Richard Trieuba63ce62011-09-09 01:45:06 +00004061 if (CastType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00004062 // We don't necessarily do lvalue-to-rvalue conversions on this.
Richard Trieuba63ce62011-09-09 01:45:06 +00004063 ExprResult castExprRes = IgnoredValueConversions(CastExpr);
John Wiegley01296292011-04-08 18:41:53 +00004064 if (castExprRes.isInvalid())
4065 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004066 CastExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00004067
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004068 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00004069 Kind = CK_ToVoid;
Richard Trieuba63ce62011-09-09 01:45:06 +00004070 return Owned(CastExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00004071 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004072
Richard Trieuba63ce62011-09-09 01:45:06 +00004073 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(CastExpr);
John Wiegley01296292011-04-08 18:41:53 +00004074 if (castExprRes.isInvalid())
4075 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004076 CastExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00004077
Richard Trieuba63ce62011-09-09 01:45:06 +00004078 if (RequireCompleteType(TypeRange.getBegin(), CastType,
Eli Friedmane98194d2010-07-17 20:43:49 +00004079 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00004080 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00004081
Richard Trieuba63ce62011-09-09 01:45:06 +00004082 if (!CastType->isScalarType() && !CastType->isVectorType()) {
4083 if (Context.hasSameUnqualifiedType(CastType, CastExpr->getType()) &&
4084 (CastType->isStructureType() || CastType->isUnionType())) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004085 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00004086 // FIXME: Check that the cast destination type is complete.
Richard Trieuba63ce62011-09-09 01:45:06 +00004087 Diag(TypeRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
4088 << CastType << CastExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004089 Kind = CK_NoOp;
Richard Trieuba63ce62011-09-09 01:45:06 +00004090 return Owned(CastExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00004091 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004092
Richard Trieuba63ce62011-09-09 01:45:06 +00004093 if (CastType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004094 // GCC cast to union extension
Richard Trieuba63ce62011-09-09 01:45:06 +00004095 RecordDecl *RD = CastType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004096 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004097 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004098 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004099 if (Context.hasSameUnqualifiedType(Field->getType(),
Richard Trieuba63ce62011-09-09 01:45:06 +00004100 CastExpr->getType()) &&
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00004101 !Field->isUnnamedBitfield()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004102 Diag(TypeRange.getBegin(), diag::ext_typecheck_cast_to_union)
4103 << CastExpr->getSourceRange();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00004104 break;
4105 }
4106 }
John Wiegley01296292011-04-08 18:41:53 +00004107 if (Field == FieldEnd) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004108 Diag(TypeRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
4109 << CastExpr->getType() << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004110 return ExprError();
4111 }
John McCalle3027922010-08-25 11:45:40 +00004112 Kind = CK_ToUnion;
Richard Trieuba63ce62011-09-09 01:45:06 +00004113 return Owned(CastExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004114 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004115
Anders Carlsson525b76b2009-10-16 02:48:28 +00004116 // Reject any other conversions to non-scalar types.
Richard Trieuba63ce62011-09-09 01:45:06 +00004117 Diag(TypeRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
4118 << CastType << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004119 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004120 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004121
John McCalld7646252010-11-14 08:17:51 +00004122 // The type we're casting to is known to be a scalar or vector.
4123
4124 // Require the operand to be a scalar or vector.
Richard Trieuba63ce62011-09-09 01:45:06 +00004125 if (!CastExpr->getType()->isScalarType() &&
4126 !CastExpr->getType()->isVectorType()) {
4127 Diag(CastExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004128 diag::err_typecheck_expect_scalar_operand)
Richard Trieuba63ce62011-09-09 01:45:06 +00004129 << CastExpr->getType() << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004130 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00004131 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004132
Richard Trieuba63ce62011-09-09 01:45:06 +00004133 if (CastType->isExtVectorType())
4134 return CheckExtVectorCast(TypeRange, CastType, CastExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004135
Richard Trieuba63ce62011-09-09 01:45:06 +00004136 if (CastType->isVectorType()) {
4137 if (CastType->getAs<VectorType>()->getVectorKind() ==
Anton Yartsev28ccef72011-03-27 09:32:40 +00004138 VectorType::AltiVecVector &&
Richard Trieuba63ce62011-09-09 01:45:06 +00004139 (CastExpr->getType()->isIntegerType() ||
4140 CastExpr->getType()->isFloatingType())) {
Anton Yartsev28ccef72011-03-27 09:32:40 +00004141 Kind = CK_VectorSplat;
Richard Trieuba63ce62011-09-09 01:45:06 +00004142 return Owned(CastExpr);
4143 } else if (CheckVectorCast(TypeRange, CastType, CastExpr->getType(),
4144 Kind)) {
John Wiegley01296292011-04-08 18:41:53 +00004145 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00004146 } else
Richard Trieuba63ce62011-09-09 01:45:06 +00004147 return Owned(CastExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00004148 }
Richard Trieuba63ce62011-09-09 01:45:06 +00004149 if (CastExpr->getType()->isVectorType()) {
4150 if (CheckVectorCast(TypeRange, CastExpr->getType(), CastType, Kind))
John Wiegley01296292011-04-08 18:41:53 +00004151 return ExprError();
4152 else
Richard Trieuba63ce62011-09-09 01:45:06 +00004153 return Owned(CastExpr);
John Wiegley01296292011-04-08 18:41:53 +00004154 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00004155
John McCalld7646252010-11-14 08:17:51 +00004156 // The source and target types are both scalars, i.e.
4157 // - arithmetic types (fundamental, enum, and complex)
4158 // - all kinds of pointers
4159 // Note that member pointers were filtered out with C++, above.
4160
Richard Trieuba63ce62011-09-09 01:45:06 +00004161 if (isa<ObjCSelectorExpr>(CastExpr)) {
4162 Diag(CastExpr->getLocStart(), diag::err_cast_selector_expr);
John Wiegley01296292011-04-08 18:41:53 +00004163 return ExprError();
4164 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004165
John McCalld7646252010-11-14 08:17:51 +00004166 // If either type is a pointer, the other type has to be either an
4167 // integer or a pointer.
Richard Trieuba63ce62011-09-09 01:45:06 +00004168 QualType CastExprType = CastExpr->getType();
4169 if (!CastType->isArithmeticType()) {
4170 if (!CastExprType->isIntegralType(Context) &&
4171 CastExprType->isArithmeticType()) {
4172 Diag(CastExpr->getLocStart(),
John Wiegley01296292011-04-08 18:41:53 +00004173 diag::err_cast_pointer_from_non_pointer_int)
Richard Trieuba63ce62011-09-09 01:45:06 +00004174 << CastExprType << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004175 return ExprError();
4176 }
Richard Trieuba63ce62011-09-09 01:45:06 +00004177 } else if (!CastExpr->getType()->isArithmeticType()) {
4178 if (!CastType->isIntegralType(Context) && CastType->isArithmeticType()) {
4179 Diag(CastExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
4180 << CastType << CastExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004181 return ExprError();
4182 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004183 }
Anders Carlsson094c4592009-10-18 18:12:03 +00004184
John McCall31168b02011-06-15 23:02:42 +00004185 if (getLangOptions().ObjCAutoRefCount) {
4186 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
Richard Trieuba63ce62011-09-09 01:45:06 +00004187 CheckObjCARCConversion(SourceRange(CastStartLoc, CastExpr->getLocEnd()),
4188 CastType, CastExpr, CCK_CStyleCast);
John McCall31168b02011-06-15 23:02:42 +00004189
Richard Trieuba63ce62011-09-09 01:45:06 +00004190 if (const PointerType *CastPtr = CastType->getAs<PointerType>()) {
4191 if (const PointerType *ExprPtr = CastExprType->getAs<PointerType>()) {
John McCall31168b02011-06-15 23:02:42 +00004192 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
4193 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
4194 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
4195 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
4196 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004197 Diag(CastExpr->getLocStart(),
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00004198 diag::err_typecheck_incompatible_ownership)
Richard Trieuba63ce62011-09-09 01:45:06 +00004199 << CastExprType << CastType << AA_Casting
4200 << CastExpr->getSourceRange();
John McCall31168b02011-06-15 23:02:42 +00004201
4202 return ExprError();
4203 }
4204 }
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00004205 }
Richard Trieuba63ce62011-09-09 01:45:06 +00004206 else if (!CheckObjCARCUnavailableWeakConversion(CastType, CastExprType)) {
4207 Diag(CastExpr->getLocStart(),
Fariborz Jahanianf2913402011-07-08 17:41:42 +00004208 diag::err_arc_convesion_of_weak_unavailable) << 1
Richard Trieuba63ce62011-09-09 01:45:06 +00004209 << CastExprType << CastType
4210 << CastExpr->getSourceRange();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004211 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00004212 }
4213 }
4214
Richard Trieuba63ce62011-09-09 01:45:06 +00004215 castExprRes = Owned(CastExpr);
4216 Kind = PrepareScalarCast(*this, castExprRes, CastType);
John Wiegley01296292011-04-08 18:41:53 +00004217 if (castExprRes.isInvalid())
4218 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004219 CastExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00004220
John McCalld7646252010-11-14 08:17:51 +00004221 if (Kind == CK_BitCast)
Richard Trieuba63ce62011-09-09 01:45:06 +00004222 CheckCastAlign(CastExpr, CastType, TypeRange);
John McCall2b5c1b22010-08-12 21:44:57 +00004223
Richard Trieuba63ce62011-09-09 01:45:06 +00004224 return Owned(CastExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00004225}
4226
Anders Carlsson525b76b2009-10-16 02:48:28 +00004227bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004228 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004229 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004230
Anders Carlssonde71adf2007-11-27 05:51:55 +00004231 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004232 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004233 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004234 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004235 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004236 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004237 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004238 } else
4239 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004240 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004241 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004242
John McCalle3027922010-08-25 11:45:40 +00004243 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004244 return false;
4245}
4246
John Wiegley01296292011-04-08 18:41:53 +00004247ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4248 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004249 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004250
Anders Carlsson43d70f82009-10-16 05:23:41 +00004251 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004252
Nate Begemanc8961a42009-06-27 22:05:55 +00004253 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4254 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00004255 // In OpenCL, casts between vectors of different types are not allowed.
4256 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00004257 if (SrcTy->isVectorType()) {
Tobias Grosser766bcc22011-09-22 13:03:14 +00004258 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4259 || (getLangOptions().OpenCL &&
4260 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004261 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004262 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004263 return ExprError();
4264 }
John McCalle3027922010-08-25 11:45:40 +00004265 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004266 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004267 }
4268
Nate Begemanbd956c42009-06-28 02:36:38 +00004269 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004270 // conversion will take place first from scalar to elt type, and then
4271 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004272 if (SrcTy->isPointerType())
4273 return Diag(R.getBegin(),
4274 diag::err_invalid_conversion_between_vector_and_scalar)
4275 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004276
4277 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004278 ExprResult CastExprRes = Owned(CastExpr);
4279 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
4280 if (CastExprRes.isInvalid())
4281 return ExprError();
4282 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004283
John McCalle3027922010-08-25 11:45:40 +00004284 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004285 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004286}
4287
John McCalldadc5752010-08-24 06:29:42 +00004288ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004289Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4290 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004291 SourceLocation RParenLoc, Expr *CastExpr) {
4292 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004293 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004294
Richard Trieuba63ce62011-09-09 01:45:06 +00004295 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004296 if (D.isInvalidType())
4297 return ExprError();
4298
4299 if (getLangOptions().CPlusPlus) {
4300 // Check that there are no default arguments (C++ only).
4301 CheckExtraCXXDefaultArguments(D);
4302 }
4303
John McCall42856de2011-10-01 05:17:03 +00004304 checkUnusedDeclAttributes(D);
4305
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004306 QualType castType = castTInfo->getType();
4307 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004308
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004309 bool isVectorLiteral = false;
4310
4311 // Check for an altivec or OpenCL literal,
4312 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00004313 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4314 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00004315 if ((getLangOptions().AltiVec || getLangOptions().OpenCL)
4316 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004317 if (PLE && PLE->getNumExprs() == 0) {
4318 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4319 return ExprError();
4320 }
4321 if (PE || PLE->getNumExprs() == 1) {
4322 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4323 if (!E->getType()->isVectorType())
4324 isVectorLiteral = true;
4325 }
4326 else
4327 isVectorLiteral = true;
4328 }
4329
4330 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4331 // then handle it as such.
4332 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00004333 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004334
Nate Begeman5ec4b312009-08-10 23:49:36 +00004335 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004336 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4337 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00004338 if (isa<ParenListExpr>(CastExpr)) {
4339 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004340 if (Result.isInvalid()) return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004341 CastExpr = Result.take();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004342 }
John McCallebe54742010-01-15 18:56:44 +00004343
Richard Trieuba63ce62011-09-09 01:45:06 +00004344 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00004345}
4346
John McCalldadc5752010-08-24 06:29:42 +00004347ExprResult
John McCallebe54742010-01-15 18:56:44 +00004348Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004349 SourceLocation RParenLoc, Expr *CastExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00004350 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00004351 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00004352 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00004353 ExprResult CastResult =
John McCall31168b02011-06-15 23:02:42 +00004354 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
Richard Trieuba63ce62011-09-09 01:45:06 +00004355 CastExpr, Kind, VK, BasePath);
John Wiegley01296292011-04-08 18:41:53 +00004356 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004357 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004358 CastExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00004359
Richard Trieucfc491d2011-08-02 04:35:43 +00004360 return Owned(CStyleCastExpr::Create(
Richard Trieuba63ce62011-09-09 01:45:06 +00004361 Context, Ty->getType().getNonLValueExprType(Context), VK, Kind, CastExpr,
Richard Trieucfc491d2011-08-02 04:35:43 +00004362 &BasePath, Ty, LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00004363}
4364
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004365ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4366 SourceLocation RParenLoc, Expr *E,
4367 TypeSourceInfo *TInfo) {
4368 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4369 "Expected paren or paren list expression");
4370
4371 Expr **exprs;
4372 unsigned numExprs;
4373 Expr *subExpr;
4374 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4375 exprs = PE->getExprs();
4376 numExprs = PE->getNumExprs();
4377 } else {
4378 subExpr = cast<ParenExpr>(E)->getSubExpr();
4379 exprs = &subExpr;
4380 numExprs = 1;
4381 }
4382
4383 QualType Ty = TInfo->getType();
4384 assert(Ty->isVectorType() && "Expected vector type");
4385
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004386 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004387 const VectorType *VTy = Ty->getAs<VectorType>();
4388 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4389
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004390 // '(...)' form of vector initialization in AltiVec: the number of
4391 // initializers must be one or must match the size of the vector.
4392 // If a single value is specified in the initializer then it will be
4393 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004394 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004395 // The number of initializers must be one or must match the size of the
4396 // vector. If a single value is specified in the initializer then it will
4397 // be replicated to all the components of the vector
4398 if (numExprs == 1) {
4399 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4400 ExprResult Literal = Owned(exprs[0]);
4401 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4402 PrepareScalarCast(*this, Literal, ElemTy));
4403 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4404 }
4405 else if (numExprs < numElems) {
4406 Diag(E->getExprLoc(),
4407 diag::err_incorrect_number_of_vector_initializers);
4408 return ExprError();
4409 }
4410 else
4411 for (unsigned i = 0, e = numExprs; i != e; ++i)
4412 initExprs.push_back(exprs[i]);
4413 }
Tanya Lattner83559382011-07-15 23:07:01 +00004414 else {
4415 // For OpenCL, when the number of initializers is a single value,
4416 // it will be replicated to all components of the vector.
4417 if (getLangOptions().OpenCL &&
4418 VTy->getVectorKind() == VectorType::GenericVector &&
4419 numExprs == 1) {
4420 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4421 ExprResult Literal = Owned(exprs[0]);
4422 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4423 PrepareScalarCast(*this, Literal, ElemTy));
4424 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4425 }
4426
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004427 for (unsigned i = 0, e = numExprs; i != e; ++i)
4428 initExprs.push_back(exprs[i]);
Tanya Lattner83559382011-07-15 23:07:01 +00004429 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004430 // FIXME: This means that pretty-printing the final AST will produce curly
4431 // braces instead of the original commas.
4432 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4433 &initExprs[0],
4434 initExprs.size(), RParenLoc);
4435 initE->setType(Ty);
4436 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4437}
4438
Nate Begeman5ec4b312009-08-10 23:49:36 +00004439/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4440/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004441ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004442Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4443 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004444 if (!E)
Richard Trieuba63ce62011-09-09 01:45:06 +00004445 return Owned(OrigExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004446
John McCalldadc5752010-08-24 06:29:42 +00004447 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004448
Nate Begeman5ec4b312009-08-10 23:49:36 +00004449 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004450 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4451 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004452
John McCallb268a282010-08-23 23:25:46 +00004453 if (Result.isInvalid()) return ExprError();
4454
4455 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004456}
4457
John McCalldadc5752010-08-24 06:29:42 +00004458ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Richard Trieuba63ce62011-09-09 01:45:06 +00004459 SourceLocation R,
4460 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004461 unsigned nexprs = Val.size();
4462 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004463 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4464 Expr *expr;
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004465 if (nexprs == 1)
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004466 expr = new (Context) ParenExpr(L, R, exprs[0]);
4467 else
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004468 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4469 exprs[nexprs-1]->getType());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004470 return Owned(expr);
4471}
4472
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004473/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004474/// constant and the other is not a pointer. Returns true if a diagnostic is
4475/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00004476bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004477 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004478 Expr *NullExpr = LHSExpr;
4479 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004480 Expr::NullPointerConstantKind NullKind =
4481 NullExpr->isNullPointerConstant(Context,
4482 Expr::NPC_ValueDependentIsNotNull);
4483
4484 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004485 NullExpr = RHSExpr;
4486 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004487 NullKind =
4488 NullExpr->isNullPointerConstant(Context,
4489 Expr::NPC_ValueDependentIsNotNull);
4490 }
4491
4492 if (NullKind == Expr::NPCK_NotNull)
4493 return false;
4494
4495 if (NullKind == Expr::NPCK_ZeroInteger) {
4496 // In this case, check to make sure that we got here from a "NULL"
4497 // string in the source code.
4498 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004499 SourceLocation loc = NullExpr->getExprLoc();
4500 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004501 return false;
4502 }
4503
4504 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4505 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4506 << NonPointerExpr->getType() << DiagType
4507 << NonPointerExpr->getSourceRange();
4508 return true;
4509}
4510
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004511/// \brief Return false if the condition expression is valid, true otherwise.
4512static bool checkCondition(Sema &S, Expr *Cond) {
4513 QualType CondTy = Cond->getType();
4514
4515 // C99 6.5.15p2
4516 if (CondTy->isScalarType()) return false;
4517
4518 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4519 if (S.getLangOptions().OpenCL && CondTy->isVectorType())
4520 return false;
4521
4522 // Emit the proper error message.
4523 S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ?
4524 diag::err_typecheck_cond_expect_scalar :
4525 diag::err_typecheck_cond_expect_scalar_or_vector)
4526 << CondTy;
4527 return true;
4528}
4529
4530/// \brief Return false if the two expressions can be converted to a vector,
4531/// true otherwise
4532static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4533 ExprResult &RHS,
4534 QualType CondTy) {
4535 // Both operands should be of scalar type.
4536 if (!LHS.get()->getType()->isScalarType()) {
4537 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4538 << CondTy;
4539 return true;
4540 }
4541 if (!RHS.get()->getType()->isScalarType()) {
4542 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4543 << CondTy;
4544 return true;
4545 }
4546
4547 // Implicity convert these scalars to the type of the condition.
4548 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4549 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4550 return false;
4551}
4552
4553/// \brief Handle when one or both operands are void type.
4554static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4555 ExprResult &RHS) {
4556 Expr *LHSExpr = LHS.get();
4557 Expr *RHSExpr = RHS.get();
4558
4559 if (!LHSExpr->getType()->isVoidType())
4560 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4561 << RHSExpr->getSourceRange();
4562 if (!RHSExpr->getType()->isVoidType())
4563 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4564 << LHSExpr->getSourceRange();
4565 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4566 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4567 return S.Context.VoidTy;
4568}
4569
4570/// \brief Return false if the NullExpr can be promoted to PointerTy,
4571/// true otherwise.
4572static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4573 QualType PointerTy) {
4574 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4575 !NullExpr.get()->isNullPointerConstant(S.Context,
4576 Expr::NPC_ValueDependentIsNull))
4577 return true;
4578
4579 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4580 return false;
4581}
4582
4583/// \brief Checks compatibility between two pointers and return the resulting
4584/// type.
4585static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4586 ExprResult &RHS,
4587 SourceLocation Loc) {
4588 QualType LHSTy = LHS.get()->getType();
4589 QualType RHSTy = RHS.get()->getType();
4590
4591 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4592 // Two identical pointers types are always compatible.
4593 return LHSTy;
4594 }
4595
4596 QualType lhptee, rhptee;
4597
4598 // Get the pointee types.
John McCall9320b872011-09-09 05:25:32 +00004599 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4600 lhptee = LHSBTy->getPointeeType();
4601 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004602 } else {
John McCall9320b872011-09-09 05:25:32 +00004603 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4604 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004605 }
4606
4607 if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4608 rhptee.getUnqualifiedType())) {
4609 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4610 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4611 << RHS.get()->getSourceRange();
4612 // In this situation, we assume void* type. No especially good
4613 // reason, but this is what gcc does, and we do have to pick
4614 // to get a consistent AST.
4615 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4616 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4617 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4618 return incompatTy;
4619 }
4620
4621 // The pointer types are compatible.
4622 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4623 // differently qualified versions of compatible types, the result type is
4624 // a pointer to an appropriately qualified version of the *composite*
4625 // type.
4626 // FIXME: Need to calculate the composite type.
4627 // FIXME: Need to add qualifiers
4628
4629 LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4630 RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4631 return LHSTy;
4632}
4633
4634/// \brief Return the resulting type when the operands are both block pointers.
4635static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4636 ExprResult &LHS,
4637 ExprResult &RHS,
4638 SourceLocation Loc) {
4639 QualType LHSTy = LHS.get()->getType();
4640 QualType RHSTy = RHS.get()->getType();
4641
4642 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4643 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4644 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4645 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4646 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4647 return destType;
4648 }
4649 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4650 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4651 << RHS.get()->getSourceRange();
4652 return QualType();
4653 }
4654
4655 // We have 2 block pointer types.
4656 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4657}
4658
4659/// \brief Return the resulting type when the operands are both pointers.
4660static QualType
4661checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4662 ExprResult &RHS,
4663 SourceLocation Loc) {
4664 // get the pointer types
4665 QualType LHSTy = LHS.get()->getType();
4666 QualType RHSTy = RHS.get()->getType();
4667
4668 // get the "pointed to" types
4669 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4670 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4671
4672 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4673 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4674 // Figure out necessary qualifiers (C99 6.5.15p6)
4675 QualType destPointee
4676 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4677 QualType destType = S.Context.getPointerType(destPointee);
4678 // Add qualifiers if necessary.
4679 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4680 // Promote to void*.
4681 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4682 return destType;
4683 }
4684 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4685 QualType destPointee
4686 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4687 QualType destType = S.Context.getPointerType(destPointee);
4688 // Add qualifiers if necessary.
4689 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4690 // Promote to void*.
4691 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4692 return destType;
4693 }
4694
4695 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4696}
4697
4698/// \brief Return false if the first expression is not an integer and the second
4699/// expression is not a pointer, true otherwise.
4700static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4701 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004702 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004703 if (!PointerExpr->getType()->isPointerType() ||
4704 !Int.get()->getType()->isIntegerType())
4705 return false;
4706
Richard Trieuba63ce62011-09-09 01:45:06 +00004707 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4708 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004709
4710 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4711 << Expr1->getType() << Expr2->getType()
4712 << Expr1->getSourceRange() << Expr2->getSourceRange();
4713 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4714 CK_IntegralToPointer);
4715 return true;
4716}
4717
Richard Trieud33e46e2011-09-06 20:06:39 +00004718/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4719/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004720/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004721QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4722 ExprResult &RHS, ExprValueKind &VK,
4723 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004724 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004725
Richard Trieud33e46e2011-09-06 20:06:39 +00004726 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4727 if (!LHSResult.isUsable()) return QualType();
4728 LHS = move(LHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004729
Richard Trieud33e46e2011-09-06 20:06:39 +00004730 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4731 if (!RHSResult.isUsable()) return QualType();
4732 RHS = move(RHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004733
Sebastian Redl1a99f442009-04-16 17:51:27 +00004734 // C++ is sufficiently different to merit its own checker.
4735 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004736 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004737
4738 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004739 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004740
John Wiegley01296292011-04-08 18:41:53 +00004741 Cond = UsualUnaryConversions(Cond.take());
4742 if (Cond.isInvalid())
4743 return QualType();
4744 LHS = UsualUnaryConversions(LHS.take());
4745 if (LHS.isInvalid())
4746 return QualType();
4747 RHS = UsualUnaryConversions(RHS.take());
4748 if (RHS.isInvalid())
4749 return QualType();
4750
4751 QualType CondTy = Cond.get()->getType();
4752 QualType LHSTy = LHS.get()->getType();
4753 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004754
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004755 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004756 if (checkCondition(*this, Cond.get()))
4757 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004758
Chris Lattnere2949f42008-01-06 22:42:25 +00004759 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004760 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004761 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004762
Nate Begemanabb5a732010-09-20 22:41:17 +00004763 // OpenCL: If the condition is a vector, and both operands are scalar,
4764 // attempt to implicity convert them to the vector type to act like the
4765 // built in select.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004766 if (getLangOptions().OpenCL && CondTy->isVectorType())
4767 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00004768 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00004769
Chris Lattnere2949f42008-01-06 22:42:25 +00004770 // If both operands have arithmetic type, do the usual arithmetic conversions
4771 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004772 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4773 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004774 if (LHS.isInvalid() || RHS.isInvalid())
4775 return QualType();
4776 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004777 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004778
Chris Lattnere2949f42008-01-06 22:42:25 +00004779 // If both operands are the same structure or union type, the result is that
4780 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004781 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4782 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004783 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004784 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004785 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004786 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004787 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004788 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004789
Chris Lattnere2949f42008-01-06 22:42:25 +00004790 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004791 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004792 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004793 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00004794 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004795
Steve Naroff039ad3c2008-01-08 01:11:38 +00004796 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4797 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004798 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4799 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004800
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004801 // All objective-c pointer type analysis is done here.
4802 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4803 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004804 if (LHS.isInvalid() || RHS.isInvalid())
4805 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004806 if (!compositeType.isNull())
4807 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004808
4809
Steve Naroff05efa972009-07-01 14:36:47 +00004810 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004811 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4812 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4813 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004814
Steve Naroff05efa972009-07-01 14:36:47 +00004815 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004816 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4817 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4818 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004819
John McCalle84af4e2010-11-13 01:35:44 +00004820 // GCC compatibility: soften pointer/integer mismatch. Note that
4821 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004822 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4823 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00004824 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004825 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4826 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00004827 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00004828
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004829 // Emit a better diagnostic if one of the expressions is a null pointer
4830 // constant and the other is not a pointer type. In this case, the user most
4831 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004832 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004833 return QualType();
4834
Chris Lattnere2949f42008-01-06 22:42:25 +00004835 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004836 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004837 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4838 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004839 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004840}
4841
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004842/// FindCompositeObjCPointerType - Helper method to find composite type of
4843/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004844QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00004845 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004846 QualType LHSTy = LHS.get()->getType();
4847 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004848
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004849 // Handle things like Class and struct objc_class*. Here we case the result
4850 // to the pseudo-builtin, because that will be implicitly cast back to the
4851 // redefinition type if an attempt is made to access its fields.
4852 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004853 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004854 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004855 return LHSTy;
4856 }
4857 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004858 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004859 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004860 return RHSTy;
4861 }
4862 // And the same for struct objc_object* / id
4863 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004864 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004865 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004866 return LHSTy;
4867 }
4868 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004869 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004870 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004871 return RHSTy;
4872 }
4873 // And the same for struct objc_selector* / SEL
4874 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004875 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004876 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004877 return LHSTy;
4878 }
4879 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004880 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004881 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004882 return RHSTy;
4883 }
4884 // Check constraints for Objective-C object pointers types.
4885 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004886
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004887 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4888 // Two identical object pointer types are always compatible.
4889 return LHSTy;
4890 }
John McCall9320b872011-09-09 05:25:32 +00004891 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
4892 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004893 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004894
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004895 // If both operands are interfaces and either operand can be
4896 // assigned to the other, use that type as the composite
4897 // type. This allows
4898 // xxx ? (A*) a : (B*) b
4899 // where B is a subclass of A.
4900 //
4901 // Additionally, as for assignment, if either type is 'id'
4902 // allow silent coercion. Finally, if the types are
4903 // incompatible then make sure to use 'id' as the composite
4904 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004905
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004906 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4907 // It could return the composite type.
4908 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4909 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4910 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4911 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4912 } else if ((LHSTy->isObjCQualifiedIdType() ||
4913 RHSTy->isObjCQualifiedIdType()) &&
4914 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4915 // Need to handle "id<xx>" explicitly.
4916 // GCC allows qualified id and any Objective-C type to devolve to
4917 // id. Currently localizing to here until clear this should be
4918 // part of ObjCQualifiedIdTypesAreCompatible.
4919 compositeType = Context.getObjCIdType();
4920 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4921 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004922 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004923 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4924 ;
4925 else {
4926 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4927 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004928 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004929 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004930 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4931 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004932 return incompatTy;
4933 }
4934 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004935 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4936 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004937 return compositeType;
4938 }
4939 // Check Objective-C object pointer types and 'void *'
4940 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4941 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4942 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4943 QualType destPointee
4944 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4945 QualType destType = Context.getPointerType(destPointee);
4946 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004947 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004948 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004949 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004950 return destType;
4951 }
4952 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4953 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4954 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4955 QualType destPointee
4956 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4957 QualType destType = Context.getPointerType(destPointee);
4958 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004959 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004960 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004961 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004962 return destType;
4963 }
4964 return QualType();
4965}
4966
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004967/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004968/// ParenRange in parentheses.
4969static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004970 const PartialDiagnostic &Note,
4971 SourceRange ParenRange) {
4972 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4973 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4974 EndLoc.isValid()) {
4975 Self.Diag(Loc, Note)
4976 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4977 << FixItHint::CreateInsertion(EndLoc, ")");
4978 } else {
4979 // We can't display the parentheses, so just show the bare note.
4980 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004981 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004982}
4983
4984static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4985 return Opc >= BO_Mul && Opc <= BO_Shr;
4986}
4987
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004988/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4989/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00004990/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
4991/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004992static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00004993 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00004994 // Don't strip parenthesis: we should not warn if E is in parenthesis.
4995 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004996 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00004997 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004998
4999 // Built-in binary operator.
5000 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5001 if (IsArithmeticOp(OP->getOpcode())) {
5002 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00005003 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005004 return true;
5005 }
5006 }
5007
5008 // Overloaded operator.
5009 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5010 if (Call->getNumArgs() != 2)
5011 return false;
5012
5013 // Make sure this is really a binary operator that is safe to pass into
5014 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5015 OverloadedOperatorKind OO = Call->getOperator();
5016 if (OO < OO_Plus || OO > OO_Arrow)
5017 return false;
5018
5019 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5020 if (IsArithmeticOp(OpKind)) {
5021 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00005022 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005023 return true;
5024 }
5025 }
5026
5027 return false;
5028}
5029
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005030static bool IsLogicOp(BinaryOperatorKind Opc) {
5031 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5032}
5033
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005034/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5035/// or is a logical expression such as (x==y) which has int type, but is
5036/// commonly interpreted as boolean.
5037static bool ExprLooksBoolean(Expr *E) {
5038 E = E->IgnoreParenImpCasts();
5039
5040 if (E->getType()->isBooleanType())
5041 return true;
5042 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5043 return IsLogicOp(OP->getOpcode());
5044 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5045 return OP->getOpcode() == UO_LNot;
5046
5047 return false;
5048}
5049
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005050/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5051/// and binary operator are mixed in a way that suggests the programmer assumed
5052/// the conditional operator has higher precedence, for example:
5053/// "int x = a + someBinaryCondition ? 1 : 2".
5054static void DiagnoseConditionalPrecedence(Sema &Self,
5055 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005056 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00005057 Expr *LHSExpr,
5058 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005059 BinaryOperatorKind CondOpcode;
5060 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005061
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005062 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005063 return;
5064 if (!ExprLooksBoolean(CondRHS))
5065 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005066
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005067 // The condition is an arithmetic binary expression, with a right-
5068 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005069
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005070 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005071 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005072 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005073
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005074 SuggestParentheses(Self, OpLoc,
5075 Self.PDiag(diag::note_precedence_conditional_silence)
5076 << BinaryOperator::getOpcodeStr(CondOpcode),
5077 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00005078
5079 SuggestParentheses(Self, OpLoc,
5080 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00005081 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005082}
5083
Steve Naroff83895f72007-09-16 03:34:24 +00005084/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005085/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005086ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005087 SourceLocation ColonLoc,
5088 Expr *CondExpr, Expr *LHSExpr,
5089 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005090 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5091 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005092 OpaqueValueExpr *opaqueValue = 0;
5093 Expr *commonExpr = 0;
5094 if (LHSExpr == 0) {
5095 commonExpr = CondExpr;
5096
5097 // We usually want to apply unary conversions *before* saving, except
5098 // in the special case of a C++ l-value conditional.
5099 if (!(getLangOptions().CPlusPlus
5100 && !commonExpr->isTypeDependent()
5101 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5102 && commonExpr->isGLValue()
5103 && commonExpr->isOrdinaryOrBitFieldObject()
5104 && RHSExpr->isOrdinaryOrBitFieldObject()
5105 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005106 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5107 if (commonRes.isInvalid())
5108 return ExprError();
5109 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005110 }
5111
5112 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5113 commonExpr->getType(),
5114 commonExpr->getValueKind(),
5115 commonExpr->getObjectKind());
5116 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005117 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005118
John McCall7decc9e2010-11-18 06:31:45 +00005119 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005120 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005121 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5122 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005123 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005124 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5125 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005126 return ExprError();
5127
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005128 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5129 RHS.get());
5130
John McCallc07a0c72011-02-17 10:25:35 +00005131 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005132 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5133 LHS.take(), ColonLoc,
5134 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005135
5136 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005137 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005138 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5139 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005140}
5141
John McCallaba90822011-01-31 23:13:11 +00005142// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005143// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005144// routine is it effectively iqnores the qualifiers on the top level pointee.
5145// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5146// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005147static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005148checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5149 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5150 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005151
Steve Naroff1f4d7272007-05-11 04:00:31 +00005152 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005153 const Type *lhptee, *rhptee;
5154 Qualifiers lhq, rhq;
Richard Trieua871b972011-09-06 20:21:22 +00005155 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5156 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005157
John McCallaba90822011-01-31 23:13:11 +00005158 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005159
5160 // C99 6.5.16.1p1: This following citation is common to constraints
5161 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5162 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005163 Qualifiers lq;
5164
John McCall31168b02011-06-15 23:02:42 +00005165 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5166 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5167 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5168 // Ignore lifetime for further calculation.
5169 lhq.removeObjCLifetime();
5170 rhq.removeObjCLifetime();
5171 }
5172
John McCall4fff8f62011-02-01 00:10:29 +00005173 if (!lhq.compatiblyIncludes(rhq)) {
5174 // Treat address-space mismatches as fatal. TODO: address subspaces
5175 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5176 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5177
John McCall31168b02011-06-15 23:02:42 +00005178 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005179 // and from void*.
John McCall31168b02011-06-15 23:02:42 +00005180 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5181 .compatiblyIncludes(
5182 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall78535952011-03-26 02:56:45 +00005183 && (lhptee->isVoidType() || rhptee->isVoidType()))
5184 ; // keep old
5185
John McCall31168b02011-06-15 23:02:42 +00005186 // Treat lifetime mismatches as fatal.
5187 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5188 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5189
John McCall4fff8f62011-02-01 00:10:29 +00005190 // For GCC compatibility, other qualifier mismatches are treated
5191 // as still compatible in C.
5192 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5193 }
Steve Naroff3f597292007-05-11 22:18:03 +00005194
Mike Stump4e1f26a2009-02-19 03:04:26 +00005195 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5196 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005197 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005198 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005199 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005200 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005201
Chris Lattner0a788432008-01-03 22:56:36 +00005202 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005203 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005204 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005205 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005206
Chris Lattner0a788432008-01-03 22:56:36 +00005207 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005208 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005209 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005210
5211 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005212 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005213 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005214 }
John McCall4fff8f62011-02-01 00:10:29 +00005215
Mike Stump4e1f26a2009-02-19 03:04:26 +00005216 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005217 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005218 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5219 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005220 // Check if the pointee types are compatible ignoring the sign.
5221 // We explicitly check for char so that we catch "char" vs
5222 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005223 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005224 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005225 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005226 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005227
Chris Lattnerec3a1562009-10-17 20:33:28 +00005228 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005229 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005230 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005231 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005232
John McCall4fff8f62011-02-01 00:10:29 +00005233 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005234 // Types are compatible ignoring the sign. Qualifier incompatibility
5235 // takes priority over sign incompatibility because the sign
5236 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005237 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005238 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005239
John McCallaba90822011-01-31 23:13:11 +00005240 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005241 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005242
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005243 // If we are a multi-level pointer, it's possible that our issue is simply
5244 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5245 // the eventual target type is the same and the pointers have the same
5246 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005247 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005248 do {
John McCall4fff8f62011-02-01 00:10:29 +00005249 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5250 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005251 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005252
John McCall4fff8f62011-02-01 00:10:29 +00005253 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005254 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005255 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005256
Eli Friedman80160bd2009-03-22 23:59:44 +00005257 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005258 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005259 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005260 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005261}
5262
John McCallaba90822011-01-31 23:13:11 +00005263/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005264/// block pointer types are compatible or whether a block and normal pointer
5265/// are compatible. It is more restrict than comparing two function pointer
5266// types.
John McCallaba90822011-01-31 23:13:11 +00005267static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005268checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5269 QualType RHSType) {
5270 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5271 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005272
Steve Naroff081c7422008-09-04 15:10:53 +00005273 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005274
Steve Naroff081c7422008-09-04 15:10:53 +00005275 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00005276 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5277 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005278
John McCallaba90822011-01-31 23:13:11 +00005279 // In C++, the types have to match exactly.
5280 if (S.getLangOptions().CPlusPlus)
5281 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005282
John McCallaba90822011-01-31 23:13:11 +00005283 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005284
Steve Naroff081c7422008-09-04 15:10:53 +00005285 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005286 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5287 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005288
Richard Trieua871b972011-09-06 20:21:22 +00005289 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005290 return Sema::IncompatibleBlockPointer;
5291
Steve Naroff081c7422008-09-04 15:10:53 +00005292 return ConvTy;
5293}
5294
John McCallaba90822011-01-31 23:13:11 +00005295/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005296/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005297static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005298checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5299 QualType RHSType) {
5300 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5301 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005302
Richard Trieua871b972011-09-06 20:21:22 +00005303 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005304 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005305 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5306 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005307 return Sema::IncompatiblePointer;
5308 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005309 }
Richard Trieua871b972011-09-06 20:21:22 +00005310 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00005311 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5312 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00005313 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00005314 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005315 }
Richard Trieua871b972011-09-06 20:21:22 +00005316 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5317 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005318
John McCallaba90822011-01-31 23:13:11 +00005319 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5320 return Sema::CompatiblePointerDiscardsQualifiers;
5321
Richard Trieua871b972011-09-06 20:21:22 +00005322 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005323 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00005324 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005325 return Sema::IncompatibleObjCQualifiedId;
5326 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005327}
5328
John McCall29600e12010-11-16 02:32:08 +00005329Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005330Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00005331 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00005332 // Fake up an opaque expression. We don't actually care about what
5333 // cast operations are required, so if CheckAssignmentConstraints
5334 // adds casts to this they'll be wasted, but fortunately that doesn't
5335 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00005336 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5337 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00005338 CastKind K = CK_Invalid;
5339
Richard Trieua871b972011-09-06 20:21:22 +00005340 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall29600e12010-11-16 02:32:08 +00005341}
5342
Mike Stump4e1f26a2009-02-19 03:04:26 +00005343/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5344/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005345/// pointers. Here are some objectionable examples that GCC considers warnings:
5346///
5347/// int a, *pint;
5348/// short *pshort;
5349/// struct foo *pfoo;
5350///
5351/// pint = pshort; // warning: assignment from incompatible pointer type
5352/// a = pint; // warning: assignment makes integer from pointer without a cast
5353/// pint = a; // warning: assignment makes pointer from integer without a cast
5354/// pint = pfoo; // warning: assignment from incompatible pointer type
5355///
5356/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005357/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005358///
John McCall8cb679e2010-11-15 09:13:47 +00005359/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005360Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00005361Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCall8cb679e2010-11-15 09:13:47 +00005362 CastKind &Kind) {
Richard Trieude4958f2011-09-06 20:30:53 +00005363 QualType RHSType = RHS.get()->getType();
5364 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00005365
Chris Lattnera52c2f22008-01-04 23:18:45 +00005366 // Get canonical types. We're not formatting these types, just comparing
5367 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00005368 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5369 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005370
John McCalle5255932011-01-31 22:28:28 +00005371 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00005372 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00005373 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005374 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005375 }
5376
Douglas Gregor6b754842008-10-28 00:22:11 +00005377 // If the left-hand side is a reference type, then we are in a
5378 // (rare!) case where we've allowed the use of references in C,
5379 // e.g., as a parameter type in a built-in function. In this case,
5380 // just make sure that the type referenced is compatible with the
5381 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00005382 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00005383 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00005384 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5385 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005386 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005387 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005388 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005389 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005390 }
John McCalle5255932011-01-31 22:28:28 +00005391
Nate Begemanbd956c42009-06-28 02:36:38 +00005392 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5393 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005394 if (LHSType->isExtVectorType()) {
5395 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005396 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00005397 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005398 // CK_VectorSplat does T -> vector T, so first cast to the
5399 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00005400 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5401 if (elType != RHSType) {
5402 Kind = PrepareScalarCast(*this, RHS, elType);
5403 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005404 }
5405 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005406 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005407 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005408 }
Mike Stump11289f42009-09-09 15:08:12 +00005409
John McCalle5255932011-01-31 22:28:28 +00005410 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005411 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5412 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005413 // Allow assignments of an AltiVec vector type to an equivalent GCC
5414 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00005415 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00005416 Kind = CK_BitCast;
5417 return Compatible;
5418 }
5419
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005420 // If we are allowing lax vector conversions, and LHS and RHS are both
5421 // vectors, the total size only needs to be the same. This is a bitcast;
5422 // no bits are changed but the result type is different.
5423 if (getLangOptions().LaxVectorConversions &&
Richard Trieude4958f2011-09-06 20:30:53 +00005424 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall3065d042010-11-15 10:08:00 +00005425 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005426 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005427 }
Chris Lattner881a2122008-01-04 23:32:24 +00005428 }
5429 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005430 }
Eli Friedman3360d892008-05-30 18:07:22 +00005431
John McCalle5255932011-01-31 22:28:28 +00005432 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00005433 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5434 !(getLangOptions().CPlusPlus && LHSType->isEnumeralType())) {
5435 Kind = PrepareScalarCast(*this, RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005436 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005437 }
Eli Friedman3360d892008-05-30 18:07:22 +00005438
John McCalle5255932011-01-31 22:28:28 +00005439 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005440 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005441 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005442 if (isa<PointerType>(RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005443 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005444 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005445 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005446
John McCalle5255932011-01-31 22:28:28 +00005447 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005448 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00005449 Kind = CK_IntegralToPointer; // FIXME: null?
5450 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005451 }
John McCalle5255932011-01-31 22:28:28 +00005452
5453 // C pointers are not compatible with ObjC object pointers,
5454 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005455 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005456 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00005457 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00005458 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00005459 return Compatible;
5460 }
5461
5462 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005463 if (RHSType->isObjCClassType() &&
5464 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005465 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005466 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005467 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005468 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00005469
John McCalle5255932011-01-31 22:28:28 +00005470 Kind = CK_BitCast;
5471 return IncompatiblePointer;
5472 }
5473
5474 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00005475 if (RHSType->getAs<BlockPointerType>()) {
5476 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00005477 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005478 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005479 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005480 }
John McCalle5255932011-01-31 22:28:28 +00005481
Steve Naroff081c7422008-09-04 15:10:53 +00005482 return Incompatible;
5483 }
5484
John McCalle5255932011-01-31 22:28:28 +00005485 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005486 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005487 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005488 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00005489 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005490 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00005491 }
5492
5493 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005494 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005495 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005496 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005497 }
5498
John McCalle5255932011-01-31 22:28:28 +00005499 // id -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005500 if (getLangOptions().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00005501 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005502 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005503 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005504
John McCalle5255932011-01-31 22:28:28 +00005505 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005506 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005507 if (RHSPT->getPointeeType()->isVoidType()) {
5508 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005509 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005510 }
John McCall8cb679e2010-11-15 09:13:47 +00005511
Chris Lattnera52c2f22008-01-04 23:18:45 +00005512 return Incompatible;
5513 }
5514
John McCalle5255932011-01-31 22:28:28 +00005515 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005516 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005517 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00005518 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005519 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005520 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00005521 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005522 if (getLangOptions().ObjCAutoRefCount &&
5523 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00005524 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005525 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005526 return result;
John McCalle5255932011-01-31 22:28:28 +00005527 }
5528
5529 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005530 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005531 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005532 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005533 }
5534
John McCalle5255932011-01-31 22:28:28 +00005535 // In general, C pointers are not compatible with ObjC object pointers,
5536 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005537 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00005538 Kind = CK_CPointerToObjCPointerCast;
5539
John McCalle5255932011-01-31 22:28:28 +00005540 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00005541 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005542 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005543 }
5544
5545 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005546 if (LHSType->isObjCClassType() &&
5547 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005548 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005549 return Compatible;
5550 }
5551
Steve Naroffaccc4882009-07-20 17:56:53 +00005552 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005553 }
John McCalle5255932011-01-31 22:28:28 +00005554
5555 // T^ -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005556 if (RHSType->isBlockPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00005557 maybeExtendBlockObject(*this, RHS);
John McCall9320b872011-09-09 05:25:32 +00005558 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005559 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005560 }
5561
Steve Naroff7cae42b2009-07-10 23:34:53 +00005562 return Incompatible;
5563 }
John McCalle5255932011-01-31 22:28:28 +00005564
5565 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005566 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005567 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005568 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005569 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005570 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005571 }
Eli Friedman3360d892008-05-30 18:07:22 +00005572
John McCalle5255932011-01-31 22:28:28 +00005573 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005574 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005575 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005576 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005577 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005578
Chris Lattnera52c2f22008-01-04 23:18:45 +00005579 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005580 }
John McCalle5255932011-01-31 22:28:28 +00005581
5582 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005583 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005584 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005585 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005586 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005587 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005588 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005589
John McCalle5255932011-01-31 22:28:28 +00005590 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005591 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005592 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005593 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005594 }
5595
Steve Naroff7cae42b2009-07-10 23:34:53 +00005596 return Incompatible;
5597 }
Eli Friedman3360d892008-05-30 18:07:22 +00005598
John McCalle5255932011-01-31 22:28:28 +00005599 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00005600 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5601 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005602 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005603 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005604 }
Bill Wendling216423b2007-05-30 06:30:29 +00005605 }
John McCalle5255932011-01-31 22:28:28 +00005606
Steve Naroff98cf3e92007-06-06 18:38:38 +00005607 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005608}
5609
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005610/// \brief Constructs a transparent union from an expression that is
5611/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005612static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5613 ExprResult &EResult, QualType UnionType,
5614 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005615 // Build an initializer list that designates the appropriate member
5616 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005617 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005618 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005619 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005620 SourceLocation());
5621 Initializer->setType(UnionType);
5622 Initializer->setInitializedFieldInUnion(Field);
5623
5624 // Build a compound literal constructing a value of the transparent
5625 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005626 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005627 EResult = S.Owned(
5628 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5629 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005630}
5631
5632Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005633Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00005634 ExprResult &RHS) {
5635 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005636
Mike Stump11289f42009-09-09 15:08:12 +00005637 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005638 // transparent_union GCC extension.
5639 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005640 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005641 return Incompatible;
5642
5643 // The field to initialize within the transparent union.
5644 RecordDecl *UD = UT->getDecl();
5645 FieldDecl *InitField = 0;
5646 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005647 for (RecordDecl::field_iterator it = UD->field_begin(),
5648 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005649 it != itend; ++it) {
5650 if (it->getType()->isPointerType()) {
5651 // If the transparent union contains a pointer type, we allow:
5652 // 1) void pointer
5653 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00005654 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00005655 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieueb299142011-09-06 20:40:12 +00005656 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005657 InitField = *it;
5658 break;
5659 }
Mike Stump11289f42009-09-09 15:08:12 +00005660
Richard Trieueb299142011-09-06 20:40:12 +00005661 if (RHS.get()->isNullPointerConstant(Context,
5662 Expr::NPC_ValueDependentIsNull)) {
5663 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5664 CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005665 InitField = *it;
5666 break;
5667 }
5668 }
5669
John McCall8cb679e2010-11-15 09:13:47 +00005670 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00005671 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005672 == Compatible) {
Richard Trieueb299142011-09-06 20:40:12 +00005673 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005674 InitField = *it;
5675 break;
5676 }
5677 }
5678
5679 if (!InitField)
5680 return Incompatible;
5681
Richard Trieueb299142011-09-06 20:40:12 +00005682 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005683 return Compatible;
5684}
5685
Chris Lattner9bad62c2008-01-04 18:04:52 +00005686Sema::AssignConvertType
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005687Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5688 bool Diagnose) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005689 if (getLangOptions().CPlusPlus) {
Richard Trieueb299142011-09-06 20:40:12 +00005690 if (!LHSType->isRecordType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005691 // C++ 5.17p3: If the left operand is not of class type, the
5692 // expression is implicitly converted (C++ 4) to the
5693 // cv-unqualified type of the left operand.
Richard Trieueb299142011-09-06 20:40:12 +00005694 ExprResult Res = PerformImplicitConversion(RHS.get(),
5695 LHSType.getUnqualifiedType(),
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005696 AA_Assigning, Diagnose);
John Wiegley01296292011-04-08 18:41:53 +00005697 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005698 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005699 Sema::AssignConvertType result = Compatible;
5700 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00005701 !CheckObjCARCUnavailableWeakConversion(LHSType,
5702 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005703 result = IncompatibleObjCWeakRef;
Richard Trieueb299142011-09-06 20:40:12 +00005704 RHS = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005705 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005706 }
5707
5708 // FIXME: Currently, we fall through and treat C++ classes like C
5709 // structures.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005710 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005711
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005712 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5713 // a null pointer constant.
Richard Trieueb299142011-09-06 20:40:12 +00005714 if ((LHSType->isPointerType() ||
5715 LHSType->isObjCObjectPointerType() ||
5716 LHSType->isBlockPointerType())
5717 && RHS.get()->isNullPointerConstant(Context,
5718 Expr::NPC_ValueDependentIsNull)) {
5719 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005720 return Compatible;
5721 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005722
Chris Lattnere6dcd502007-10-16 02:55:40 +00005723 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005724 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005725 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005726 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005727 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005728 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00005729 if (!LHSType->isReferenceType()) {
5730 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5731 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005732 return Incompatible;
5733 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005734
John McCall8cb679e2010-11-15 09:13:47 +00005735 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005736 Sema::AssignConvertType result =
Richard Trieueb299142011-09-06 20:40:12 +00005737 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005738
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005739 // C99 6.5.16.1p2: The value of the right operand is converted to the
5740 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005741 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5742 // so that we can use references in built-in functions even in C.
5743 // The getNonReferenceType() call makes sure that the resulting expression
5744 // does not have reference type.
Richard Trieueb299142011-09-06 20:40:12 +00005745 if (result != Incompatible && RHS.get()->getType() != LHSType)
5746 RHS = ImpCastExprToType(RHS.take(),
5747 LHSType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005748 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005749}
5750
Richard Trieueb299142011-09-06 20:40:12 +00005751QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5752 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005753 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00005754 << LHS.get()->getType() << RHS.get()->getType()
5755 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005756 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005757}
5758
Richard Trieu859d23f2011-09-06 21:01:04 +00005759QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00005760 SourceLocation Loc, bool IsCompAssign) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00005761 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005762 // For example, "const float" and "float" are equivalent.
Richard Trieu859d23f2011-09-06 21:01:04 +00005763 QualType LHSType =
5764 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5765 QualType RHSType =
5766 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005767
Nate Begeman191a6b12008-07-14 18:02:46 +00005768 // If the vector types are identical, return.
Richard Trieu859d23f2011-09-06 21:01:04 +00005769 if (LHSType == RHSType)
5770 return LHSType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005771
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005772 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu859d23f2011-09-06 21:01:04 +00005773 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5774 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5775 if (LHSType->isExtVectorType()) {
5776 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5777 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005778 }
5779
Richard Trieuba63ce62011-09-09 01:45:06 +00005780 if (!IsCompAssign)
Richard Trieu859d23f2011-09-06 21:01:04 +00005781 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5782 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005783 }
5784
Eli Friedman1408bc92011-06-23 18:10:35 +00005785 if (getLangOptions().LaxVectorConversions &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005786 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005787 // If we are allowing lax vector conversions, and LHS and RHS are both
5788 // vectors, the total size only needs to be the same. This is a
5789 // bitcast; no bits are changed but the result type is different.
5790 // FIXME: Should we really be allowing this?
Richard Trieu859d23f2011-09-06 21:01:04 +00005791 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5792 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005793 }
5794
Nate Begemanbd956c42009-06-28 02:36:38 +00005795 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5796 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5797 bool swapped = false;
Richard Trieuba63ce62011-09-09 01:45:06 +00005798 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005799 swapped = true;
Richard Trieu859d23f2011-09-06 21:01:04 +00005800 std::swap(RHS, LHS);
5801 std::swap(RHSType, LHSType);
Nate Begemanbd956c42009-06-28 02:36:38 +00005802 }
Mike Stump11289f42009-09-09 15:08:12 +00005803
Nate Begeman886448d2009-06-28 19:12:57 +00005804 // Handle the case of an ext vector and scalar.
Richard Trieu859d23f2011-09-06 21:01:04 +00005805 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005806 QualType EltTy = LV->getElementType();
Richard Trieu859d23f2011-09-06 21:01:04 +00005807 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5808 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005809 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005810 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005811 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005812 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5813 if (swapped) std::swap(RHS, LHS);
5814 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005815 }
5816 }
Richard Trieu859d23f2011-09-06 21:01:04 +00005817 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5818 RHSType->isRealFloatingType()) {
5819 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005820 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005821 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005822 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005823 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5824 if (swapped) std::swap(RHS, LHS);
5825 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005826 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005827 }
5828 }
Mike Stump11289f42009-09-09 15:08:12 +00005829
Nate Begeman886448d2009-06-28 19:12:57 +00005830 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu859d23f2011-09-06 21:01:04 +00005831 if (swapped) std::swap(RHS, LHS);
Chris Lattner377d1f82008-11-18 22:52:51 +00005832 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu859d23f2011-09-06 21:01:04 +00005833 << LHS.get()->getType() << RHS.get()->getType()
5834 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005835 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005836}
5837
Richard Trieuf8916e12011-09-16 00:53:10 +00005838// checkArithmeticNull - Detect when a NULL constant is used improperly in an
5839// expression. These are mainly cases where the null pointer is used as an
5840// integer instead of a pointer.
5841static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
5842 SourceLocation Loc, bool IsCompare) {
5843 // The canonical way to check for a GNU null is with isNullPointerConstant,
5844 // but we use a bit of a hack here for speed; this is a relatively
5845 // hot path, and isNullPointerConstant is slow.
5846 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
5847 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
5848
5849 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
5850
5851 // Avoid analyzing cases where the result will either be invalid (and
5852 // diagnosed as such) or entirely valid and not something to warn about.
5853 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
5854 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
5855 return;
5856
5857 // Comparison operations would not make sense with a null pointer no matter
5858 // what the other expression is.
5859 if (!IsCompare) {
5860 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
5861 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
5862 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
5863 return;
5864 }
5865
5866 // The rest of the operations only make sense with a null pointer
5867 // if the other expression is a pointer.
5868 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
5869 NonNullType->canDecayToPointerType())
5870 return;
5871
5872 S.Diag(Loc, diag::warn_null_in_comparison_operation)
5873 << LHSNull /* LHS is NULL */ << NonNullType
5874 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5875}
5876
Richard Trieu859d23f2011-09-06 21:01:04 +00005877QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00005878 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00005879 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005880 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5881
Richard Trieu859d23f2011-09-06 21:01:04 +00005882 if (LHS.get()->getType()->isVectorType() ||
5883 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00005884 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005885
Richard Trieuba63ce62011-09-09 01:45:06 +00005886 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005887 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005888 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005889
Richard Trieu859d23f2011-09-06 21:01:04 +00005890 if (!LHS.get()->getType()->isArithmeticType() ||
5891 !RHS.get()->getType()->isArithmeticType())
5892 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005893
Chris Lattnerfaa54172010-01-12 21:23:57 +00005894 // Check for division by zero.
Richard Trieuba63ce62011-09-09 01:45:06 +00005895 if (IsDiv &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005896 RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005897 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005898 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
5899 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005900
Chris Lattnerfaa54172010-01-12 21:23:57 +00005901 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005902}
5903
Chris Lattnerfaa54172010-01-12 21:23:57 +00005904QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00005905 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005906 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5907
Richard Trieu859d23f2011-09-06 21:01:04 +00005908 if (LHS.get()->getType()->isVectorType() ||
5909 RHS.get()->getType()->isVectorType()) {
5910 if (LHS.get()->getType()->hasIntegerRepresentation() &&
5911 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00005912 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005913 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005914 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005915
Richard Trieuba63ce62011-09-09 01:45:06 +00005916 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005917 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005918 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005919
Richard Trieu859d23f2011-09-06 21:01:04 +00005920 if (!LHS.get()->getType()->isIntegerType() ||
5921 !RHS.get()->getType()->isIntegerType())
5922 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005923
Chris Lattnerfaa54172010-01-12 21:23:57 +00005924 // Check for remainder by zero.
Richard Trieu859d23f2011-09-06 21:01:04 +00005925 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005926 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005927 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
5928 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005929
Chris Lattnerfaa54172010-01-12 21:23:57 +00005930 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005931}
5932
Chandler Carruthc9332212011-06-27 08:02:19 +00005933/// \brief Diagnose invalid arithmetic on two void pointers.
5934static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00005935 Expr *LHSExpr, Expr *RHSExpr) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005936 S.Diag(Loc, S.getLangOptions().CPlusPlus
5937 ? diag::err_typecheck_pointer_arith_void_type
5938 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00005939 << 1 /* two pointers */ << LHSExpr->getSourceRange()
5940 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00005941}
5942
5943/// \brief Diagnose invalid arithmetic on a void pointer.
5944static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5945 Expr *Pointer) {
5946 S.Diag(Loc, S.getLangOptions().CPlusPlus
5947 ? diag::err_typecheck_pointer_arith_void_type
5948 : diag::ext_gnu_void_ptr)
5949 << 0 /* one pointer */ << Pointer->getSourceRange();
5950}
5951
5952/// \brief Diagnose invalid arithmetic on two function pointers.
5953static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5954 Expr *LHS, Expr *RHS) {
5955 assert(LHS->getType()->isAnyPointerType());
5956 assert(RHS->getType()->isAnyPointerType());
5957 S.Diag(Loc, S.getLangOptions().CPlusPlus
5958 ? diag::err_typecheck_pointer_arith_function_type
5959 : diag::ext_gnu_ptr_func_arith)
5960 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5961 // We only show the second type if it differs from the first.
5962 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5963 RHS->getType())
5964 << RHS->getType()->getPointeeType()
5965 << LHS->getSourceRange() << RHS->getSourceRange();
5966}
5967
5968/// \brief Diagnose invalid arithmetic on a function pointer.
5969static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5970 Expr *Pointer) {
5971 assert(Pointer->getType()->isAnyPointerType());
5972 S.Diag(Loc, S.getLangOptions().CPlusPlus
5973 ? diag::err_typecheck_pointer_arith_function_type
5974 : diag::ext_gnu_ptr_func_arith)
5975 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5976 << 0 /* one pointer, so only one type */
5977 << Pointer->getSourceRange();
5978}
5979
Richard Trieu993f3ab2011-09-12 18:08:02 +00005980/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00005981///
5982/// \returns True if pointer has incomplete type
5983static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
5984 Expr *Operand) {
5985 if ((Operand->getType()->isPointerType() &&
5986 !Operand->getType()->isDependentType()) ||
5987 Operand->getType()->isObjCObjectPointerType()) {
5988 QualType PointeeTy = Operand->getType()->getPointeeType();
5989 if (S.RequireCompleteType(
5990 Loc, PointeeTy,
5991 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5992 << PointeeTy << Operand->getSourceRange()))
5993 return true;
5994 }
5995 return false;
5996}
5997
Chandler Carruthc9332212011-06-27 08:02:19 +00005998/// \brief Check the validity of an arithmetic pointer operand.
5999///
6000/// If the operand has pointer type, this code will check for pointer types
6001/// which are invalid in arithmetic operations. These will be diagnosed
6002/// appropriately, including whether or not the use is supported as an
6003/// extension.
6004///
6005/// \returns True when the operand is valid to use (even if as an extension).
6006static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6007 Expr *Operand) {
6008 if (!Operand->getType()->isAnyPointerType()) return true;
6009
6010 QualType PointeeTy = Operand->getType()->getPointeeType();
6011 if (PointeeTy->isVoidType()) {
6012 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6013 return !S.getLangOptions().CPlusPlus;
6014 }
6015 if (PointeeTy->isFunctionType()) {
6016 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6017 return !S.getLangOptions().CPlusPlus;
6018 }
6019
Richard Trieuaba22802011-09-02 02:15:37 +00006020 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00006021
6022 return true;
6023}
6024
6025/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6026/// operands.
6027///
6028/// This routine will diagnose any invalid arithmetic on pointer operands much
6029/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6030/// for emitting a single diagnostic even for operations where both LHS and RHS
6031/// are (potentially problematic) pointers.
6032///
6033/// \returns True when the operand is valid to use (even if as an extension).
6034static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006035 Expr *LHSExpr, Expr *RHSExpr) {
6036 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6037 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006038 if (!isLHSPointer && !isRHSPointer) return true;
6039
6040 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00006041 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6042 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006043
6044 // Check for arithmetic on pointers to incomplete types.
6045 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6046 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6047 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006048 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6049 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6050 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006051
6052 return !S.getLangOptions().CPlusPlus;
6053 }
6054
6055 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6056 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6057 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006058 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6059 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6060 RHSExpr);
6061 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006062
6063 return !S.getLangOptions().CPlusPlus;
6064 }
6065
Richard Trieu4ae7e972011-09-06 21:13:51 +00006066 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
6067 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
Richard Trieuaba22802011-09-02 02:15:37 +00006068
Chandler Carruthc9332212011-06-27 08:02:19 +00006069 return true;
6070}
6071
Richard Trieub10c6312011-09-01 22:53:23 +00006072/// \brief Check bad cases where we step over interface counts.
6073static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
6074 SourceLocation OpLoc,
6075 Expr *Op) {
6076 assert(Op->getType()->isAnyPointerType());
6077 QualType PointeeTy = Op->getType()->getPointeeType();
6078 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
6079 return true;
6080
6081 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6082 << PointeeTy << Op->getSourceRange();
6083 return false;
6084}
6085
Richard Trieu993f3ab2011-09-12 18:08:02 +00006086/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00006087static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006088 Expr *LHSExpr, Expr *RHSExpr) {
6089 assert(LHSExpr->getType()->isAnyPointerType());
6090 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00006091 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006092 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6093 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00006094}
6095
Chris Lattnerfaa54172010-01-12 21:23:57 +00006096QualType Sema::CheckAdditionOperands( // C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006097 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006098 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6099
Richard Trieu4ae7e972011-09-06 21:13:51 +00006100 if (LHS.get()->getType()->isVectorType() ||
6101 RHS.get()->getType()->isVectorType()) {
6102 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006103 if (CompLHSTy) *CompLHSTy = compType;
6104 return compType;
6105 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006106
Richard Trieu4ae7e972011-09-06 21:13:51 +00006107 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6108 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006109 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006110
Steve Naroffe4718892007-04-27 18:30:00 +00006111 // handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006112 if (LHS.get()->getType()->isArithmeticType() &&
6113 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006114 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006115 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006116 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006117
Eli Friedman8e122982008-05-18 18:08:51 +00006118 // Put any potential pointer into PExp
Richard Trieu4ae7e972011-09-06 21:13:51 +00006119 Expr* PExp = LHS.get(), *IExp = RHS.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00006120 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006121 std::swap(PExp, IExp);
6122
Richard Trieub420bca2011-09-12 18:37:54 +00006123 if (!PExp->getType()->isAnyPointerType())
6124 return InvalidOperands(Loc, LHS, RHS);
Chandler Carruthc9332212011-06-27 08:02:19 +00006125
Richard Trieub420bca2011-09-12 18:37:54 +00006126 if (!IExp->getType()->isIntegerType())
6127 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006128
Richard Trieub420bca2011-09-12 18:37:54 +00006129 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6130 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006131
Richard Trieub420bca2011-09-12 18:37:54 +00006132 // Diagnose bad cases where we step over interface counts.
6133 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6134 return QualType();
6135
6136 // Check array bounds for pointer arithemtic
6137 CheckArrayAccess(PExp, IExp);
6138
6139 if (CompLHSTy) {
6140 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6141 if (LHSTy.isNull()) {
6142 LHSTy = LHS.get()->getType();
6143 if (LHSTy->isPromotableIntegerType())
6144 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006145 }
Richard Trieub420bca2011-09-12 18:37:54 +00006146 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00006147 }
6148
Richard Trieub420bca2011-09-12 18:37:54 +00006149 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006150}
6151
Chris Lattner2a3569b2008-04-07 05:30:13 +00006152// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006153QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006154 SourceLocation Loc,
6155 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006156 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6157
Richard Trieu4ae7e972011-09-06 21:13:51 +00006158 if (LHS.get()->getType()->isVectorType() ||
6159 RHS.get()->getType()->isVectorType()) {
6160 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006161 if (CompLHSTy) *CompLHSTy = compType;
6162 return compType;
6163 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006164
Richard Trieu4ae7e972011-09-06 21:13:51 +00006165 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6166 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006167 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006168
Chris Lattner4d62f422007-12-09 21:53:25 +00006169 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006170
Chris Lattner4d62f422007-12-09 21:53:25 +00006171 // Handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006172 if (LHS.get()->getType()->isArithmeticType() &&
6173 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006174 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006175 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006176 }
Mike Stump11289f42009-09-09 15:08:12 +00006177
Chris Lattner4d62f422007-12-09 21:53:25 +00006178 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006179 if (LHS.get()->getType()->isAnyPointerType()) {
6180 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006181
Chris Lattner12bdebb2009-04-24 23:50:08 +00006182 // Diagnose bad cases where we step over interface counts.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006183 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006184 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006185
Chris Lattner4d62f422007-12-09 21:53:25 +00006186 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006187 if (RHS.get()->getType()->isIntegerType()) {
6188 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006189 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006190
Richard Trieu4ae7e972011-09-06 21:13:51 +00006191 Expr *IExpr = RHS.get()->IgnoreParenCasts();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006192 UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6193 OK_Ordinary, IExpr->getExprLoc());
6194 // Check array bounds for pointer arithemtic
Richard Trieu4ae7e972011-09-06 21:13:51 +00006195 CheckArrayAccess(LHS.get()->IgnoreParenCasts(), &negRex);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006196
Richard Trieu4ae7e972011-09-06 21:13:51 +00006197 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6198 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006199 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006200
Chris Lattner4d62f422007-12-09 21:53:25 +00006201 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006202 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00006203 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006204 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006205
Eli Friedman168fe152009-05-16 13:54:38 +00006206 if (getLangOptions().CPlusPlus) {
6207 // Pointee types must be the same: C++ [expr.add]
6208 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006209 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006210 }
6211 } else {
6212 // Pointee types must be compatible C99 6.5.6p3
6213 if (!Context.typesAreCompatible(
6214 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6215 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006216 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006217 return QualType();
6218 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006219 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006220
Chandler Carruthc9332212011-06-27 08:02:19 +00006221 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006222 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006223 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006224
Richard Trieu4ae7e972011-09-06 21:13:51 +00006225 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006226 return Context.getPointerDiffType();
6227 }
6228 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006229
Richard Trieu4ae7e972011-09-06 21:13:51 +00006230 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006231}
6232
Douglas Gregor0bf31402010-10-08 23:50:27 +00006233static bool isScopedEnumerationType(QualType T) {
6234 if (const EnumType *ET = dyn_cast<EnumType>(T))
6235 return ET->getDecl()->isScoped();
6236 return false;
6237}
6238
Richard Trieue4a19fb2011-09-06 21:21:28 +00006239static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006240 SourceLocation Loc, unsigned Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00006241 QualType LHSType) {
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006242 llvm::APSInt Right;
6243 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00006244 if (RHS.get()->isValueDependent() ||
6245 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006246 return;
6247
6248 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006249 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006250 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006251 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006252 return;
6253 }
6254 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00006255 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006256 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006257 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006258 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006259 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006260 return;
6261 }
6262 if (Opc != BO_Shl)
6263 return;
6264
6265 // When left shifting an ICE which is signed, we can check for overflow which
6266 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6267 // integers have defined behavior modulo one more than the maximum value
6268 // representable in the result type, so never warn for those.
6269 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00006270 if (LHS.get()->isValueDependent() ||
6271 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6272 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006273 return;
6274 llvm::APInt ResultBits =
6275 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6276 if (LeftBits.uge(ResultBits))
6277 return;
6278 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6279 Result = Result.shl(Right);
6280
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006281 // Print the bit representation of the signed integer as an unsigned
6282 // hexadecimal number.
6283 llvm::SmallString<40> HexResult;
6284 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6285
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006286 // If we are only missing a sign bit, this is less likely to result in actual
6287 // bugs -- if the result is cast back to an unsigned type, it will have the
6288 // expected value. Thus we place this behind a different warning that can be
6289 // turned off separately if needed.
6290 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006291 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006292 << HexResult.str() << LHSType
6293 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006294 return;
6295 }
6296
6297 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006298 << HexResult.str() << Result.getMinSignedBits() << LHSType
6299 << Left.getBitWidth() << LHS.get()->getSourceRange()
6300 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006301}
6302
Chris Lattner2a3569b2008-04-07 05:30:13 +00006303// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00006304QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006305 SourceLocation Loc, unsigned Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006306 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006307 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6308
Chris Lattner5c11c412007-12-12 05:47:28 +00006309 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006310 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6311 !RHS.get()->getType()->hasIntegerRepresentation())
6312 return InvalidOperands(Loc, LHS, RHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006313
Douglas Gregor0bf31402010-10-08 23:50:27 +00006314 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6315 // hasIntegerRepresentation() above instead of this.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006316 if (isScopedEnumerationType(LHS.get()->getType()) ||
6317 isScopedEnumerationType(RHS.get()->getType())) {
6318 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006319 }
6320
Nate Begemane46ee9a2009-10-25 02:26:48 +00006321 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006322 if (LHS.get()->getType()->isVectorType() ||
6323 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006324 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006325
Chris Lattner5c11c412007-12-12 05:47:28 +00006326 // Shifts don't perform usual arithmetic conversions, they just do integer
6327 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006328
John McCall57cdd882010-12-16 19:28:59 +00006329 // For the LHS, do usual unary conversions, but then reset them away
6330 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006331 ExprResult OldLHS = LHS;
6332 LHS = UsualUnaryConversions(LHS.take());
6333 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006334 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00006335 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00006336 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00006337
6338 // The RHS is simpler.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006339 RHS = UsualUnaryConversions(RHS.take());
6340 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006341 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006342
Ryan Flynnf53fab82009-08-07 16:20:20 +00006343 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00006344 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006345
Chris Lattner5c11c412007-12-12 05:47:28 +00006346 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00006347 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006348}
6349
Chandler Carruth17773fc2010-07-10 12:30:03 +00006350static bool IsWithinTemplateSpecialization(Decl *D) {
6351 if (DeclContext *DC = D->getDeclContext()) {
6352 if (isa<ClassTemplateSpecializationDecl>(DC))
6353 return true;
6354 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6355 return FD->isFunctionTemplateSpecialization();
6356 }
6357 return false;
6358}
6359
Richard Trieueea56f72011-09-02 03:48:46 +00006360/// If two different enums are compared, raise a warning.
Richard Trieu1762d7c2011-09-06 21:27:33 +00006361static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6362 ExprResult &RHS) {
6363 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6364 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00006365
6366 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6367 if (!LHSEnumType)
6368 return;
6369 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6370 if (!RHSEnumType)
6371 return;
6372
6373 // Ignore anonymous enums.
6374 if (!LHSEnumType->getDecl()->getIdentifier())
6375 return;
6376 if (!RHSEnumType->getDecl()->getIdentifier())
6377 return;
6378
6379 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6380 return;
6381
6382 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6383 << LHSStrippedType << RHSStrippedType
Richard Trieu1762d7c2011-09-06 21:27:33 +00006384 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00006385}
6386
Richard Trieudd82a5c2011-09-02 02:55:45 +00006387/// \brief Diagnose bad pointer comparisons.
6388static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006389 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006390 bool IsError) {
6391 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00006392 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006393 << LHS.get()->getType() << RHS.get()->getType()
6394 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006395}
6396
6397/// \brief Returns false if the pointers are converted to a composite type,
6398/// true otherwise.
6399static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006400 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006401 // C++ [expr.rel]p2:
6402 // [...] Pointer conversions (4.10) and qualification
6403 // conversions (4.4) are performed on pointer operands (or on
6404 // a pointer operand and a null pointer constant) to bring
6405 // them to their composite pointer type. [...]
6406 //
6407 // C++ [expr.eq]p1 uses the same notion for (in)equality
6408 // comparisons of pointers.
6409
6410 // C++ [expr.eq]p2:
6411 // In addition, pointers to members can be compared, or a pointer to
6412 // member and a null pointer constant. Pointer to member conversions
6413 // (4.11) and qualification conversions (4.4) are performed to bring
6414 // them to a common type. If one operand is a null pointer constant,
6415 // the common type is the type of the other operand. Otherwise, the
6416 // common type is a pointer to member type similar (4.4) to the type
6417 // of one of the operands, with a cv-qualification signature (4.4)
6418 // that is the union of the cv-qualification signatures of the operand
6419 // types.
6420
Richard Trieu1762d7c2011-09-06 21:27:33 +00006421 QualType LHSType = LHS.get()->getType();
6422 QualType RHSType = RHS.get()->getType();
6423 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6424 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00006425
6426 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00006427 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00006428 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006429 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00006430 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006431 return true;
6432 }
6433
6434 if (NonStandardCompositeType)
6435 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006436 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6437 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006438
Richard Trieu1762d7c2011-09-06 21:27:33 +00006439 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6440 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006441 return false;
6442}
6443
6444static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006445 ExprResult &LHS,
6446 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006447 bool IsError) {
6448 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6449 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006450 << LHS.get()->getType() << RHS.get()->getType()
6451 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006452}
6453
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006454// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00006455QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006456 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006457 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006458 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6459
John McCalle3027922010-08-25 11:45:40 +00006460 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006461
Chris Lattner9a152e22009-12-05 05:40:13 +00006462 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00006463 if (LHS.get()->getType()->isVectorType() ||
6464 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006465 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006466
Richard Trieub80728f2011-09-06 21:43:51 +00006467 QualType LHSType = LHS.get()->getType();
6468 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00006469
Richard Trieub80728f2011-09-06 21:43:51 +00006470 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6471 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006472
Richard Trieub80728f2011-09-06 21:43:51 +00006473 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth712563b2011-02-17 08:37:06 +00006474
Richard Trieub80728f2011-09-06 21:43:51 +00006475 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00006476 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00006477 !LHS.get()->getLocStart().isMacroID() &&
6478 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006479 // For non-floating point types, check for self-comparisons of the form
6480 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6481 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006482 //
6483 // NOTE: Don't warn about comparison expressions resulting from macro
6484 // expansion. Also don't warn about comparisons which are only self
6485 // comparisons within a template specialization. The warnings should catch
6486 // obvious cases in the definition of the template anyways. The idea is to
6487 // warn when the typed comparison operator will always evaluate to the same
6488 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006489 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006490 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006491 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006492 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006493 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006494 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006495 << (Opc == BO_EQ
6496 || Opc == BO_LE
6497 || Opc == BO_GE));
Richard Trieub80728f2011-09-06 21:43:51 +00006498 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregorec170db2010-06-08 19:50:34 +00006499 !DRL->getDecl()->getType()->isReferenceType() &&
6500 !DRR->getDecl()->getType()->isReferenceType()) {
6501 // what is it always going to eval to?
6502 char always_evals_to;
6503 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006504 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006505 always_evals_to = 0; // false
6506 break;
John McCalle3027922010-08-25 11:45:40 +00006507 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006508 always_evals_to = 1; // true
6509 break;
6510 default:
6511 // best we can say is 'a constant'
6512 always_evals_to = 2; // e.g. array1 <= array2
6513 break;
6514 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006515 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006516 << 1 // array
6517 << always_evals_to);
6518 }
6519 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006520 }
Mike Stump11289f42009-09-09 15:08:12 +00006521
Chris Lattner222b8bd2009-03-08 19:39:53 +00006522 if (isa<CastExpr>(LHSStripped))
6523 LHSStripped = LHSStripped->IgnoreParenCasts();
6524 if (isa<CastExpr>(RHSStripped))
6525 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006526
Chris Lattner222b8bd2009-03-08 19:39:53 +00006527 // Warn about comparisons against a string constant (unless the other
6528 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006529 Expr *literalString = 0;
6530 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006531 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006532 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006533 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006534 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006535 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006536 } else if ((isa<StringLiteral>(RHSStripped) ||
6537 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006538 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006539 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006540 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006541 literalStringStripped = RHSStripped;
6542 }
6543
6544 if (literalString) {
6545 std::string resultComparison;
6546 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006547 case BO_LT: resultComparison = ") < 0"; break;
6548 case BO_GT: resultComparison = ") > 0"; break;
6549 case BO_LE: resultComparison = ") <= 0"; break;
6550 case BO_GE: resultComparison = ") >= 0"; break;
6551 case BO_EQ: resultComparison = ") == 0"; break;
6552 case BO_NE: resultComparison = ") != 0"; break;
David Blaikie83d382b2011-09-23 05:06:16 +00006553 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006554 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006555
Ted Kremenek3427fac2011-02-23 01:52:04 +00006556 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006557 PDiag(diag::warn_stringcompare)
6558 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006559 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006560 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006561 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006562
Douglas Gregorec170db2010-06-08 19:50:34 +00006563 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieub80728f2011-09-06 21:43:51 +00006564 if (LHS.get()->getType()->isArithmeticType() &&
6565 RHS.get()->getType()->isArithmeticType()) {
6566 UsualArithmeticConversions(LHS, RHS);
6567 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006568 return QualType();
6569 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006570 else {
Richard Trieub80728f2011-09-06 21:43:51 +00006571 LHS = UsualUnaryConversions(LHS.take());
6572 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006573 return QualType();
6574
Richard Trieub80728f2011-09-06 21:43:51 +00006575 RHS = UsualUnaryConversions(RHS.take());
6576 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006577 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006578 }
6579
Richard Trieub80728f2011-09-06 21:43:51 +00006580 LHSType = LHS.get()->getType();
6581 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006582
Douglas Gregorca63811b2008-11-19 03:25:36 +00006583 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006584 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006585
Richard Trieuba63ce62011-09-09 01:45:06 +00006586 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00006587 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006588 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006589 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006590 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00006591 if (LHSType->hasFloatingRepresentation())
6592 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006593
Richard Trieub80728f2011-09-06 21:43:51 +00006594 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006595 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006596 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006597
Richard Trieub80728f2011-09-06 21:43:51 +00006598 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006599 Expr::NPC_ValueDependentIsNull);
Richard Trieub80728f2011-09-06 21:43:51 +00006600 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006601 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006602
Douglas Gregorf267edd2010-06-15 21:38:40 +00006603 // All of the following pointer-related warnings are GCC extensions, except
6604 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00006605 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006606 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006607 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00006608 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006609 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006610
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006611 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006612 if (LCanPointeeTy == RCanPointeeTy)
6613 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00006614 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006615 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6616 // Valid unless comparison between non-null pointer and function pointer
6617 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006618 // In a SFINAE context, we treat this as a hard error to maintain
6619 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006620 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6621 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006622 diagnoseFunctionPointerToVoidComparison(
Richard Trieub80728f2011-09-06 21:43:51 +00006623 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00006624
6625 if (isSFINAEContext())
6626 return QualType();
6627
Richard Trieub80728f2011-09-06 21:43:51 +00006628 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006629 return ResultTy;
6630 }
6631 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006632
Richard Trieub80728f2011-09-06 21:43:51 +00006633 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006634 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006635 else
6636 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006637 }
Eli Friedman16c209612009-08-23 00:27:47 +00006638 // C99 6.5.9p2 and C99 6.5.8p2
6639 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6640 RCanPointeeTy.getUnqualifiedType())) {
6641 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00006642 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00006643 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00006644 << LHSType << RHSType << LHS.get()->getSourceRange()
6645 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006646 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006647 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00006648 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6649 // Valid unless comparison between non-null pointer and function pointer
6650 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00006651 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006652 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006653 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00006654 } else {
6655 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00006656 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00006657 }
John McCall7684dde2011-03-11 04:25:25 +00006658 if (LCanPointeeTy != RCanPointeeTy) {
6659 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006660 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006661 else
Richard Trieub80728f2011-09-06 21:43:51 +00006662 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006663 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006664 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006665 }
Mike Stump11289f42009-09-09 15:08:12 +00006666
Sebastian Redl576fd422009-05-10 18:38:11 +00006667 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006668 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00006669 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00006670 return ResultTy;
6671
Mike Stump11289f42009-09-09 15:08:12 +00006672 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006673 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006674 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006675 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006676 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006677 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
6678 RHS = ImpCastExprToType(RHS.take(), LHSType,
6679 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006680 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006681 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006682 return ResultTy;
6683 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006684 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006685 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006686 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006687 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
6688 LHS = ImpCastExprToType(LHS.take(), RHSType,
6689 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006690 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006691 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006692 return ResultTy;
6693 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006694
6695 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006696 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006697 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
6698 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006699 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006700 else
6701 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006702 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006703
6704 // Handle scoped enumeration types specifically, since they don't promote
6705 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00006706 if (LHS.get()->getType()->isEnumeralType() &&
6707 Context.hasSameUnqualifiedType(LHS.get()->getType(),
6708 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006709 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00006710 }
Mike Stump11289f42009-09-09 15:08:12 +00006711
Steve Naroff081c7422008-09-04 15:10:53 +00006712 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00006713 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00006714 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00006715 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
6716 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006717
Steve Naroff081c7422008-09-04 15:10:53 +00006718 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006719 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006720 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006721 << LHSType << RHSType << LHS.get()->getSourceRange()
6722 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006723 }
Richard Trieub80728f2011-09-06 21:43:51 +00006724 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006725 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006726 }
John Wiegley01296292011-04-08 18:41:53 +00006727
Steve Naroffe18f94c2008-09-28 01:11:11 +00006728 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00006729 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00006730 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
6731 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006732 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00006733 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006734 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00006735 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006736 ->getPointeeType()->isVoidType())))
6737 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006738 << LHSType << RHSType << LHS.get()->getSourceRange()
6739 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006740 }
John McCall7684dde2011-03-11 04:25:25 +00006741 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006742 LHS = ImpCastExprToType(LHS.take(), RHSType,
6743 RHSType->isPointerType() ? CK_BitCast
6744 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006745 else
John McCall9320b872011-09-09 05:25:32 +00006746 RHS = ImpCastExprToType(RHS.take(), LHSType,
6747 LHSType->isPointerType() ? CK_BitCast
6748 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006749 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006750 }
Steve Naroff081c7422008-09-04 15:10:53 +00006751
Richard Trieub80728f2011-09-06 21:43:51 +00006752 if (LHSType->isObjCObjectPointerType() ||
6753 RHSType->isObjCObjectPointerType()) {
6754 const PointerType *LPT = LHSType->getAs<PointerType>();
6755 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00006756 if (LPT || RPT) {
6757 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6758 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006759
Steve Naroff753567f2008-11-17 19:49:16 +00006760 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00006761 !Context.typesAreCompatible(LHSType, RHSType)) {
6762 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006763 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006764 }
John McCall7684dde2011-03-11 04:25:25 +00006765 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006766 LHS = ImpCastExprToType(LHS.take(), RHSType,
6767 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006768 else
John McCall9320b872011-09-09 05:25:32 +00006769 RHS = ImpCastExprToType(RHS.take(), LHSType,
6770 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006771 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006772 }
Richard Trieub80728f2011-09-06 21:43:51 +00006773 if (LHSType->isObjCObjectPointerType() &&
6774 RHSType->isObjCObjectPointerType()) {
6775 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
6776 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006777 /*isError*/false);
John McCall7684dde2011-03-11 04:25:25 +00006778 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006779 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006780 else
Richard Trieub80728f2011-09-06 21:43:51 +00006781 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006782 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006783 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006784 }
Richard Trieub80728f2011-09-06 21:43:51 +00006785 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
6786 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006787 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006788 bool isError = false;
Richard Trieub80728f2011-09-06 21:43:51 +00006789 if ((LHSIsNull && LHSType->isIntegerType()) ||
6790 (RHSIsNull && RHSType->isIntegerType())) {
Richard Trieuba63ce62011-09-09 01:45:06 +00006791 if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006792 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Richard Trieuba63ce62011-09-09 01:45:06 +00006793 } else if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006794 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006795 else if (getLangOptions().CPlusPlus) {
6796 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6797 isError = true;
6798 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006799 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006800
Chris Lattnerd99bd522009-08-23 00:03:44 +00006801 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006802 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00006803 << LHSType << RHSType << LHS.get()->getSourceRange()
6804 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006805 if (isError)
6806 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006807 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006808
Richard Trieub80728f2011-09-06 21:43:51 +00006809 if (LHSType->isIntegerType())
6810 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006811 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006812 else
Richard Trieub80728f2011-09-06 21:43:51 +00006813 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006814 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006815 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006816 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006817
Steve Naroff4b191572008-09-04 16:56:14 +00006818 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006819 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006820 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
6821 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006822 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006823 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006824 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006825 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
6826 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006827 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006828 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006829
Richard Trieub80728f2011-09-06 21:43:51 +00006830 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006831}
6832
Nate Begeman191a6b12008-07-14 18:02:46 +00006833/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006834/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006835/// like a scalar comparison, a vector comparison produces a vector of integer
6836/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00006837QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00006838 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006839 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006840 // Check to make sure we're operating on vectors of the same type and width,
6841 // Allowing one side to be a scalar of element type.
Richard Trieubcce2f72011-09-07 01:19:57 +00006842 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00006843 if (vType.isNull())
6844 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006845
Richard Trieubcce2f72011-09-07 01:19:57 +00006846 QualType LHSType = LHS.get()->getType();
6847 QualType RHSType = RHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006848
Anton Yartsev530deb92011-03-27 15:36:07 +00006849 // If AltiVec, the comparison results in a numeric type, i.e.
6850 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00006851 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00006852 return Context.getLogicalOperationType();
6853
Nate Begeman191a6b12008-07-14 18:02:46 +00006854 // For non-floating point types, check for self-comparisons of the form
6855 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6856 // often indicate logic errors in the program.
Richard Trieubcce2f72011-09-07 01:19:57 +00006857 if (!LHSType->hasFloatingRepresentation()) {
6858 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
6859 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00006860 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00006861 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00006862 PDiag(diag::warn_comparison_always)
6863 << 0 // self-
6864 << 2 // "a constant"
6865 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006866 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006867
Nate Begeman191a6b12008-07-14 18:02:46 +00006868 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00006869 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
Richard Trieubcce2f72011-09-07 01:19:57 +00006870 assert (RHSType->hasFloatingRepresentation());
6871 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00006872 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006873
Nate Begeman191a6b12008-07-14 18:02:46 +00006874 // Return the type for the comparison, which is the same as vector type for
6875 // integer vectors, or an integer type of identical size and number of
6876 // elements for floating point vectors.
Richard Trieubcce2f72011-09-07 01:19:57 +00006877 if (LHSType->hasIntegerRepresentation())
6878 return LHSType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006879
Richard Trieubcce2f72011-09-07 01:19:57 +00006880 const VectorType *VTy = LHSType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00006881 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006882 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00006883 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00006884 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006885 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6886
Mike Stump4e1f26a2009-02-19 03:04:26 +00006887 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006888 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00006889 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6890}
6891
Steve Naroff218bc2b2007-05-04 21:54:46 +00006892inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00006893 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006894 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6895
Richard Trieubcce2f72011-09-07 01:19:57 +00006896 if (LHS.get()->getType()->isVectorType() ||
6897 RHS.get()->getType()->isVectorType()) {
6898 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6899 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00006900 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006901
Richard Trieubcce2f72011-09-07 01:19:57 +00006902 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006903 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006904
Richard Trieubcce2f72011-09-07 01:19:57 +00006905 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
6906 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00006907 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00006908 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006909 return QualType();
Richard Trieubcce2f72011-09-07 01:19:57 +00006910 LHS = LHSResult.take();
6911 RHS = RHSResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006912
Richard Trieubcce2f72011-09-07 01:19:57 +00006913 if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6914 RHS.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006915 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00006916 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006917}
6918
Steve Naroff218bc2b2007-05-04 21:54:46 +00006919inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieubcce2f72011-09-07 01:19:57 +00006920 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00006921
6922 // Diagnose cases where the user write a logical and/or but probably meant a
6923 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6924 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00006925 if (LHS.get()->getType()->isIntegerType() &&
6926 !LHS.get()->getType()->isBooleanType() &&
6927 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00006928 // Don't warn in macros or template instantiations.
6929 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00006930 // If the RHS can be constant folded, and if it constant folds to something
6931 // that isn't 0 or 1 (which indicate a potential logical operation that
6932 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006933 // Parens on the RHS are ignored.
Chris Lattner938533d2010-07-24 01:10:11 +00006934 Expr::EvalResult Result;
Richard Trieubcce2f72011-09-07 01:19:57 +00006935 if (RHS.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6936 if ((getLangOptions().Bool && !RHS.get()->getType()->isBooleanType()) ||
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006937 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6938 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00006939 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006940 << (Opc == BO_LAnd ? "&&" : "||");
6941 // Suggest replacing the logical operator with the bitwise version
6942 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6943 << (Opc == BO_LAnd ? "&" : "|")
6944 << FixItHint::CreateReplacement(SourceRange(
6945 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6946 getLangOptions())),
6947 Opc == BO_LAnd ? "&" : "|");
6948 if (Opc == BO_LAnd)
6949 // Suggest replacing "Foo() && kNonZero" with "Foo()"
6950 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6951 << FixItHint::CreateRemoval(
6952 SourceRange(
Richard Trieubcce2f72011-09-07 01:19:57 +00006953 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006954 0, getSourceManager(),
6955 getLangOptions()),
Richard Trieubcce2f72011-09-07 01:19:57 +00006956 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006957 }
Chris Lattner938533d2010-07-24 01:10:11 +00006958 }
Chris Lattner8406c512010-07-13 19:41:32 +00006959
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006960 if (!Context.getLangOptions().CPlusPlus) {
Richard Trieubcce2f72011-09-07 01:19:57 +00006961 LHS = UsualUnaryConversions(LHS.take());
6962 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006963 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006964
Richard Trieubcce2f72011-09-07 01:19:57 +00006965 RHS = UsualUnaryConversions(RHS.take());
6966 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006967 return QualType();
6968
Richard Trieubcce2f72011-09-07 01:19:57 +00006969 if (!LHS.get()->getType()->isScalarType() ||
6970 !RHS.get()->getType()->isScalarType())
6971 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006972
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006973 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006974 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006975
John McCall4a2429a2010-06-04 00:29:51 +00006976 // The following is safe because we only use this method for
6977 // non-overloadable operands.
6978
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006979 // C++ [expr.log.and]p1
6980 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006981 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00006982 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
6983 if (LHSRes.isInvalid())
6984 return InvalidOperands(Loc, LHS, RHS);
6985 LHS = move(LHSRes);
John Wiegley01296292011-04-08 18:41:53 +00006986
Richard Trieubcce2f72011-09-07 01:19:57 +00006987 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
6988 if (RHSRes.isInvalid())
6989 return InvalidOperands(Loc, LHS, RHS);
6990 RHS = move(RHSRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006991
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006992 // C++ [expr.log.and]p2
6993 // C++ [expr.log.or]p2
6994 // The result is a bool.
6995 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006996}
6997
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006998/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6999/// is a read-only property; return true if so. A readonly property expression
7000/// depends on various declarations and thus must be treated specially.
7001///
Mike Stump11289f42009-09-09 15:08:12 +00007002static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007003 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7004 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00007005 if (PropExpr->isImplicitProperty()) return false;
7006
7007 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7008 QualType BaseType = PropExpr->isSuperReceiver() ?
7009 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007010 PropExpr->getBase()->getType();
7011
John McCallb7bd14f2010-12-02 01:19:52 +00007012 if (const ObjCObjectPointerType *OPT =
7013 BaseType->getAsObjCInterfacePointerType())
7014 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7015 if (S.isPropertyReadonly(PDecl, IFace))
7016 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007017 }
7018 return false;
7019}
7020
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007021static bool IsConstProperty(Expr *E, Sema &S) {
7022 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7023 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
7024 if (PropExpr->isImplicitProperty()) return false;
7025
7026 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7027 QualType T = PDecl->getType();
7028 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00007029 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007030 CanQualType CT = S.Context.getCanonicalType(T);
7031 return CT.isConstQualified();
7032 }
7033 return false;
7034}
7035
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007036static bool IsReadonlyMessage(Expr *E, Sema &S) {
7037 if (E->getStmtClass() != Expr::MemberExprClass)
7038 return false;
7039 const MemberExpr *ME = cast<MemberExpr>(E);
7040 NamedDecl *Member = ME->getMemberDecl();
7041 if (isa<FieldDecl>(Member)) {
7042 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
7043 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
7044 return false;
7045 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
7046 }
7047 return false;
7048}
7049
Chris Lattner30bd3272008-11-18 01:22:49 +00007050/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7051/// emit an error and return true. If so, return false.
7052static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007053 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007054 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007055 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007056 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7057 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007058 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7059 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007060 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7061 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007062 if (IsLV == Expr::MLV_Valid)
7063 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007064
Chris Lattner30bd3272008-11-18 01:22:49 +00007065 unsigned Diag = 0;
7066 bool NeedType = false;
7067 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00007068 case Expr::MLV_ConstQualified:
7069 Diag = diag::err_typecheck_assign_const;
7070
John McCalld4631322011-06-17 06:42:21 +00007071 // In ARC, use some specialized diagnostics for occasions where we
7072 // infer 'const'. These are always pseudo-strong variables.
John McCall31168b02011-06-15 23:02:42 +00007073 if (S.getLangOptions().ObjCAutoRefCount) {
7074 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7075 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7076 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7077
John McCalld4631322011-06-17 06:42:21 +00007078 // Use the normal diagnostic if it's pseudo-__strong but the
7079 // user actually wrote 'const'.
7080 if (var->isARCPseudoStrong() &&
7081 (!var->getTypeSourceInfo() ||
7082 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7083 // There are two pseudo-strong cases:
7084 // - self
John McCall31168b02011-06-15 23:02:42 +00007085 ObjCMethodDecl *method = S.getCurMethodDecl();
7086 if (method && var == method->getSelfDecl())
7087 Diag = diag::err_typecheck_arr_assign_self;
John McCalld4631322011-06-17 06:42:21 +00007088
7089 // - fast enumeration variables
7090 else
John McCall31168b02011-06-15 23:02:42 +00007091 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00007092
John McCall31168b02011-06-15 23:02:42 +00007093 SourceRange Assign;
7094 if (Loc != OrigLoc)
7095 Assign = SourceRange(OrigLoc, OrigLoc);
7096 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7097 // We need to preserve the AST regardless, so migration tool
7098 // can do its job.
7099 return false;
7100 }
7101 }
7102 }
7103
7104 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007105 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007106 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7107 NeedType = true;
7108 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007109 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007110 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7111 NeedType = true;
7112 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007113 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007114 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7115 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007116 case Expr::MLV_Valid:
7117 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007118 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007119 case Expr::MLV_MemberFunction:
7120 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007121 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7122 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007123 case Expr::MLV_IncompleteType:
7124 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007125 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007126 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00007127 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00007128 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007129 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7130 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00007131 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00007132 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7133 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007134 case Expr::MLV_ReadonlyProperty:
7135 Diag = diag::error_readonly_property_assignment;
7136 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007137 case Expr::MLV_NoSetterProperty:
7138 Diag = diag::error_nosetter_property_assignment;
7139 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007140 case Expr::MLV_InvalidMessageExpression:
7141 Diag = diag::error_readonly_message_assignment;
7142 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007143 case Expr::MLV_SubObjCPropertySetting:
7144 Diag = diag::error_no_subobject_property_setting;
7145 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007146 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007147
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007148 SourceRange Assign;
7149 if (Loc != OrigLoc)
7150 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007151 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007152 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007153 else
Mike Stump11289f42009-09-09 15:08:12 +00007154 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007155 return true;
7156}
7157
7158
7159
7160// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00007161QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007162 SourceLocation Loc,
7163 QualType CompoundType) {
7164 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007165 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007166 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007167
Richard Trieuda4f43a62011-09-07 01:33:52 +00007168 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00007169 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7170 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007171 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007172 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007173 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007174 // Simple assignment "x = y".
Richard Trieuda4f43a62011-09-07 01:33:52 +00007175 if (LHSExpr->getObjectKind() == OK_ObjCProperty) {
7176 ExprResult LHSResult = Owned(LHSExpr);
John Wiegley01296292011-04-08 18:41:53 +00007177 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7178 if (LHSResult.isInvalid())
7179 return QualType();
Richard Trieuda4f43a62011-09-07 01:33:52 +00007180 LHSExpr = LHSResult.take();
John Wiegley01296292011-04-08 18:41:53 +00007181 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007182 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007183 if (RHS.isInvalid())
7184 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007185 // Special case of NSObject attributes on c-style pointer types.
7186 if (ConvTy == IncompatiblePointer &&
7187 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007188 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007189 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007190 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007191 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007192
John McCall7decc9e2010-11-18 06:31:45 +00007193 if (ConvTy == Compatible &&
7194 getLangOptions().ObjCNonFragileABI &&
7195 LHSType->isObjCObjectType())
7196 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7197 << LHSType;
7198
Chris Lattnerea714382008-08-21 18:04:13 +00007199 // If the RHS is a unary plus or minus, check to see if they = and + are
7200 // right next to each other. If so, the user may have typo'd "x =+ 4"
7201 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00007202 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00007203 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7204 RHSCheck = ICE->getSubExpr();
7205 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007206 if ((UO->getOpcode() == UO_Plus ||
7207 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007208 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007209 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007210 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00007211 // And there is a space or other character before the subexpr of the
7212 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007213 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00007214 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007215 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007216 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007217 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007218 }
Chris Lattnerea714382008-08-21 18:04:13 +00007219 }
John McCall31168b02011-06-15 23:02:42 +00007220
7221 if (ConvTy == Compatible) {
7222 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007223 checkRetainCycles(LHSExpr, RHS.get());
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007224 else if (getLangOptions().ObjCAutoRefCount)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007225 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00007226 }
Chris Lattnerea714382008-08-21 18:04:13 +00007227 } else {
7228 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007229 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007230 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007231
Chris Lattner326f7572008-11-18 01:30:42 +00007232 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007233 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007234 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007235
Richard Trieuda4f43a62011-09-07 01:33:52 +00007236 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007237
Steve Naroff98cf3e92007-06-06 18:38:38 +00007238 // C99 6.5.16p3: The type of an assignment expression is the type of the
7239 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007240 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007241 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7242 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007243 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007244 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007245 return (getLangOptions().CPlusPlus
7246 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007247}
7248
Chris Lattner326f7572008-11-18 01:30:42 +00007249// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007250static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007251 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00007252 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007253
John McCall3aef3d82011-04-10 19:13:55 +00007254 LHS = S.CheckPlaceholderExpr(LHS.take());
7255 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007256 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007257 return QualType();
7258
John McCall73d36182010-10-12 07:14:40 +00007259 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7260 // operands, but not unary promotions.
7261 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007262
John McCall34376a62010-12-04 03:47:34 +00007263 // So we treat the LHS as a ignored value, and in C++ we allow the
7264 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007265 LHS = S.IgnoredValueConversions(LHS.take());
7266 if (LHS.isInvalid())
7267 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007268
7269 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007270 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7271 if (RHS.isInvalid())
7272 return QualType();
7273 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007274 S.RequireCompleteType(Loc, RHS.get()->getType(),
7275 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007276 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007277
John Wiegley01296292011-04-08 18:41:53 +00007278 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007279}
7280
Steve Naroff7a5af782007-07-13 16:58:59 +00007281/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7282/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007283static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7284 ExprValueKind &VK,
7285 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007286 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007287 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007288 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007289
Chris Lattner6b0cf142008-11-21 07:05:48 +00007290 QualType ResType = Op->getType();
7291 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007292
John McCall4bc41ae2010-11-18 19:01:18 +00007293 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007294 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +00007295 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007296 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007297 return QualType();
7298 }
7299 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007300 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007301 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007302 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007303 } else if (ResType->isAnyPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007304 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007305 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007306 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007307
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007308 // Diagnose bad cases where we step over interface counts.
Richard Trieub10c6312011-09-01 22:53:23 +00007309 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007310 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00007311 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007312 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007313 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007314 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007315 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007316 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007317 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007318 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007319 IsInc, IsPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007320 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7321 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007322 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007323 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +00007324 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007325 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007326 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007327 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007328 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007329 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007330 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007331 // In C++, a prefix increment is the same type as the operand. Otherwise
7332 // (in C or with postfix), the increment is the unqualified type of the
7333 // operand.
Richard Trieuba63ce62011-09-09 01:45:06 +00007334 if (IsPrefix && S.getLangOptions().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007335 VK = VK_LValue;
7336 return ResType;
7337 } else {
7338 VK = VK_RValue;
7339 return ResType.getUnqualifiedType();
7340 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007341}
7342
John Wiegley01296292011-04-08 18:41:53 +00007343ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00007344 assert(E->getValueKind() == VK_LValue &&
7345 E->getObjectKind() == OK_ObjCProperty);
7346 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7347
Douglas Gregor33823722011-06-11 01:09:30 +00007348 QualType T = E->getType();
7349 QualType ReceiverType;
7350 if (PRE->isObjectReceiver())
7351 ReceiverType = PRE->getBase()->getType();
7352 else if (PRE->isSuperReceiver())
7353 ReceiverType = PRE->getSuperReceiverType();
7354 else
7355 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
7356
John McCall34376a62010-12-04 03:47:34 +00007357 ExprValueKind VK = VK_RValue;
7358 if (PRE->isImplicitProperty()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007359 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007360 PRE->getImplicitPropertyGetter()) {
Douglas Gregor33823722011-06-11 01:09:30 +00007361 T = getMessageSendResultType(ReceiverType, GetterMethod,
7362 PRE->isClassReceiver(),
7363 PRE->isSuperReceiver());
7364 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00007365 }
7366 else {
7367 Diag(PRE->getLocation(), diag::err_getter_not_found)
7368 << PRE->getBase()->getType();
7369 }
John McCall34376a62010-12-04 03:47:34 +00007370 }
Douglas Gregor33823722011-06-11 01:09:30 +00007371
7372 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCall34376a62010-12-04 03:47:34 +00007373 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00007374
7375 ExprResult Result = MaybeBindToTemporary(E);
7376 if (!Result.isInvalid())
7377 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00007378
7379 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00007380}
7381
Richard Trieucfc491d2011-08-02 04:35:43 +00007382void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
7383 QualType &LHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00007384 assert(LHS.get()->getValueKind() == VK_LValue &&
7385 LHS.get()->getObjectKind() == OK_ObjCProperty);
7386 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00007387
John McCall31168b02011-06-15 23:02:42 +00007388 bool Consumed = false;
7389
John Wiegley01296292011-04-08 18:41:53 +00007390 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00007391 // If using property-dot syntax notation for assignment, and there is a
7392 // setter, RHS expression is being passed to the setter argument. So,
7393 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00007394 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00007395 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7396 LHSTy = (*P)->getType();
John McCall31168b02011-06-15 23:02:42 +00007397 Consumed = (getLangOptions().ObjCAutoRefCount &&
7398 (*P)->hasAttr<NSConsumedAttr>());
John McCall34376a62010-12-04 03:47:34 +00007399
7400 // Otherwise, if the getter returns an l-value, just call that.
7401 } else {
John Wiegley01296292011-04-08 18:41:53 +00007402 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00007403 ExprValueKind VK = Expr::getValueKindForType(Result);
7404 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00007405 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7406 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00007407 return;
John McCallb7bd14f2010-12-02 01:19:52 +00007408 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007409 }
John McCall31168b02011-06-15 23:02:42 +00007410 } else if (getLangOptions().ObjCAutoRefCount) {
7411 const ObjCMethodDecl *setter
7412 = PropRef->getExplicitProperty()->getSetterMethodDecl();
7413 if (setter) {
7414 ObjCMethodDecl::param_iterator P = setter->param_begin();
7415 LHSTy = (*P)->getType();
7416 Consumed = (*P)->hasAttr<NSConsumedAttr>();
7417 }
John McCall34376a62010-12-04 03:47:34 +00007418 }
7419
John McCall31168b02011-06-15 23:02:42 +00007420 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7421 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007422 InitializedEntity Entity =
John McCall31168b02011-06-15 23:02:42 +00007423 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley01296292011-04-08 18:41:53 +00007424 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCall31168b02011-06-15 23:02:42 +00007425 if (!ArgE.isInvalid()) {
John Wiegley01296292011-04-08 18:41:53 +00007426 RHS = ArgE;
John McCall31168b02011-06-15 23:02:42 +00007427 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7428 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7429 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007430 }
7431}
7432
7433
Anders Carlsson806700f2008-02-01 07:15:58 +00007434/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007435/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007436/// where the declaration is needed for type checking. We only need to
7437/// handle cases when the expression references a function designator
7438/// or is an lvalue. Here are some examples:
7439/// - &(x) => x
7440/// - &*****f => f for f a function designator.
7441/// - &s.xx => s
7442/// - &s.zz[1].yy -> s, if zz is an array
7443/// - *(x + 1) -> x, if x is an array
7444/// - &"123"[2] -> 0
7445/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007446static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007447 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007448 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007449 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007450 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007451 // If this is an arrow operator, the address is an offset from
7452 // the base's value, so the object the base refers to is
7453 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007454 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007455 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007456 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007457 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007458 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007459 // FIXME: This code shouldn't be necessary! We should catch the implicit
7460 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007461 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7462 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7463 if (ICE->getSubExpr()->getType()->isArrayType())
7464 return getPrimaryDecl(ICE->getSubExpr());
7465 }
7466 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007467 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007468 case Stmt::UnaryOperatorClass: {
7469 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007470
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007471 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007472 case UO_Real:
7473 case UO_Imag:
7474 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007475 return getPrimaryDecl(UO->getSubExpr());
7476 default:
7477 return 0;
7478 }
7479 }
Steve Naroff47500512007-04-19 23:00:49 +00007480 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007481 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007482 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007483 // If the result of an implicit cast is an l-value, we care about
7484 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007485 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007486 default:
7487 return 0;
7488 }
7489}
7490
Richard Trieu5f376f62011-09-07 21:46:33 +00007491namespace {
7492 enum {
7493 AO_Bit_Field = 0,
7494 AO_Vector_Element = 1,
7495 AO_Property_Expansion = 2,
7496 AO_Register_Variable = 3,
7497 AO_No_Error = 4
7498 };
7499}
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007500/// \brief Diagnose invalid operand for address of operations.
7501///
7502/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007503static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7504 Expr *E, unsigned Type) {
7505 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7506}
7507
Steve Naroff47500512007-04-19 23:00:49 +00007508/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007509/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007510/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007511/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007512/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007513/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007514/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00007515static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7516 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00007517 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007518 return S.Context.DependentTy;
7519 if (OrigOp->getType() == S.Context.OverloadTy)
7520 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00007521 if (OrigOp->getType() == S.Context.UnknownAnyTy)
7522 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00007523 if (OrigOp->getType() == S.Context.BoundMemberTy) {
7524 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7525 << OrigOp->getSourceRange();
7526 return QualType();
7527 }
John McCall8d08b9b2010-08-27 09:08:28 +00007528
John McCall2979fe02011-04-12 00:42:48 +00007529 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007530
John McCall8d08b9b2010-08-27 09:08:28 +00007531 // Make sure to ignore parentheses in subsequent checks
7532 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007533
John McCall4bc41ae2010-11-18 19:01:18 +00007534 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007535 // Implement C99-only parts of addressof rules.
7536 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007537 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007538 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7539 // (assuming the deref expression is valid).
7540 return uOp->getSubExpr()->getType();
7541 }
7542 // Technically, there should be a check for array subscript
7543 // expressions here, but the result of one is always an lvalue anyway.
7544 }
John McCallf3a88602011-02-03 08:15:49 +00007545 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007546 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5f376f62011-09-07 21:46:33 +00007547 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +00007548
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007549 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007550 bool sfinae = S.isSFINAEContext();
7551 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7552 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007553 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007554 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007555 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007556 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007557 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007558 } else if (lval == Expr::LV_MemberFunction) {
7559 // If it's an instance method, make a member pointer.
7560 // The expression must have exactly the form &A::foo.
7561
7562 // If the underlying expression isn't a decl ref, give up.
7563 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007564 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007565 << OrigOp->getSourceRange();
7566 return QualType();
7567 }
7568 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7569 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7570
7571 // The id-expression was parenthesized.
7572 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007573 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007574 << OrigOp->getSourceRange();
7575
7576 // The method was named without a qualifier.
7577 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007578 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007579 << op->getSourceRange();
7580 }
7581
John McCall4bc41ae2010-11-18 19:01:18 +00007582 return S.Context.getMemberPointerType(op->getType(),
7583 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007584 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007585 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007586 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007587 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00007588 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00007589 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00007590 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00007591 return QualType();
7592 }
John McCall086a4642010-11-24 05:12:34 +00007593 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007594 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +00007595 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +00007596 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007597 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +00007598 AddressOfError = AO_Vector_Element;
John McCall086a4642010-11-24 05:12:34 +00007599 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00007600 // cannot take address of a property expression.
Richard Trieu5f376f62011-09-07 21:46:33 +00007601 AddressOfError = AO_Property_Expansion;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007602 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007603 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007604 // with the register storage-class specifier.
7605 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007606 // in C++ it is not error to take address of a register
7607 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007608 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007609 !S.getLangOptions().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +00007610 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +00007611 }
John McCalld14a8642009-11-21 08:51:07 +00007612 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007613 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007614 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007615 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007616 // Could be a pointer to member, though, if there is an explicit
7617 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007618 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007619 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007620 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007621 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007622 S.Diag(OpLoc,
7623 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007624 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007625 return QualType();
7626 }
Mike Stump11289f42009-09-09 15:08:12 +00007627
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007628 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7629 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007630 return S.Context.getMemberPointerType(op->getType(),
7631 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007632 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007633 }
Eli Friedman755c0c92011-08-26 20:28:17 +00007634 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +00007635 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007636 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007637
Richard Trieu5f376f62011-09-07 21:46:33 +00007638 if (AddressOfError != AO_No_Error) {
7639 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7640 return QualType();
7641 }
7642
Eli Friedmance7f9002009-05-16 23:27:50 +00007643 if (lval == Expr::LV_IncompleteVoidType) {
7644 // Taking the address of a void variable is technically illegal, but we
7645 // allow it in cases which are otherwise valid.
7646 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007647 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007648 }
7649
Steve Naroff47500512007-04-19 23:00:49 +00007650 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007651 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007652 return S.Context.getObjCObjectPointerType(op->getType());
7653 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007654}
7655
Chris Lattner9156f1b2010-07-05 19:17:26 +00007656/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007657static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7658 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007659 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007660 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007661
John Wiegley01296292011-04-08 18:41:53 +00007662 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7663 if (ConvResult.isInvalid())
7664 return QualType();
7665 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007666 QualType OpTy = Op->getType();
7667 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007668
7669 if (isa<CXXReinterpretCastExpr>(Op)) {
7670 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7671 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7672 Op->getSourceRange());
7673 }
7674
Chris Lattner9156f1b2010-07-05 19:17:26 +00007675 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7676 // is an incomplete type or void. It would be possible to warn about
7677 // dereferencing a void pointer, but it's completely well-defined, and such a
7678 // warning is unlikely to catch any mistakes.
7679 if (const PointerType *PT = OpTy->getAs<PointerType>())
7680 Result = PT->getPointeeType();
7681 else if (const ObjCObjectPointerType *OPT =
7682 OpTy->getAs<ObjCObjectPointerType>())
7683 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007684 else {
John McCall3aef3d82011-04-10 19:13:55 +00007685 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007686 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007687 if (PR.take() != Op)
7688 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007689 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007690
Chris Lattner9156f1b2010-07-05 19:17:26 +00007691 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007692 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007693 << OpTy << Op->getSourceRange();
7694 return QualType();
7695 }
John McCall4bc41ae2010-11-18 19:01:18 +00007696
7697 // Dereferences are usually l-values...
7698 VK = VK_LValue;
7699
7700 // ...except that certain expressions are never l-values in C.
Douglas Gregor5476205b2011-06-23 00:49:38 +00007701 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007702 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007703
7704 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007705}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007706
John McCalle3027922010-08-25 11:45:40 +00007707static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007708 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007709 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007710 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007711 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007712 case tok::periodstar: Opc = BO_PtrMemD; break;
7713 case tok::arrowstar: Opc = BO_PtrMemI; break;
7714 case tok::star: Opc = BO_Mul; break;
7715 case tok::slash: Opc = BO_Div; break;
7716 case tok::percent: Opc = BO_Rem; break;
7717 case tok::plus: Opc = BO_Add; break;
7718 case tok::minus: Opc = BO_Sub; break;
7719 case tok::lessless: Opc = BO_Shl; break;
7720 case tok::greatergreater: Opc = BO_Shr; break;
7721 case tok::lessequal: Opc = BO_LE; break;
7722 case tok::less: Opc = BO_LT; break;
7723 case tok::greaterequal: Opc = BO_GE; break;
7724 case tok::greater: Opc = BO_GT; break;
7725 case tok::exclaimequal: Opc = BO_NE; break;
7726 case tok::equalequal: Opc = BO_EQ; break;
7727 case tok::amp: Opc = BO_And; break;
7728 case tok::caret: Opc = BO_Xor; break;
7729 case tok::pipe: Opc = BO_Or; break;
7730 case tok::ampamp: Opc = BO_LAnd; break;
7731 case tok::pipepipe: Opc = BO_LOr; break;
7732 case tok::equal: Opc = BO_Assign; break;
7733 case tok::starequal: Opc = BO_MulAssign; break;
7734 case tok::slashequal: Opc = BO_DivAssign; break;
7735 case tok::percentequal: Opc = BO_RemAssign; break;
7736 case tok::plusequal: Opc = BO_AddAssign; break;
7737 case tok::minusequal: Opc = BO_SubAssign; break;
7738 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7739 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7740 case tok::ampequal: Opc = BO_AndAssign; break;
7741 case tok::caretequal: Opc = BO_XorAssign; break;
7742 case tok::pipeequal: Opc = BO_OrAssign; break;
7743 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007744 }
7745 return Opc;
7746}
7747
John McCalle3027922010-08-25 11:45:40 +00007748static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007749 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007750 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007751 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007752 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007753 case tok::plusplus: Opc = UO_PreInc; break;
7754 case tok::minusminus: Opc = UO_PreDec; break;
7755 case tok::amp: Opc = UO_AddrOf; break;
7756 case tok::star: Opc = UO_Deref; break;
7757 case tok::plus: Opc = UO_Plus; break;
7758 case tok::minus: Opc = UO_Minus; break;
7759 case tok::tilde: Opc = UO_Not; break;
7760 case tok::exclaim: Opc = UO_LNot; break;
7761 case tok::kw___real: Opc = UO_Real; break;
7762 case tok::kw___imag: Opc = UO_Imag; break;
7763 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007764 }
7765 return Opc;
7766}
7767
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007768/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7769/// This warning is only emitted for builtin assignment operations. It is also
7770/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007771static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007772 SourceLocation OpLoc) {
7773 if (!S.ActiveTemplateInstantiations.empty())
7774 return;
7775 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7776 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007777 LHSExpr = LHSExpr->IgnoreParenImpCasts();
7778 RHSExpr = RHSExpr->IgnoreParenImpCasts();
7779 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
7780 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
7781 if (!LHSDeclRef || !RHSDeclRef ||
7782 LHSDeclRef->getLocation().isMacroID() ||
7783 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007784 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007785 const ValueDecl *LHSDecl =
7786 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
7787 const ValueDecl *RHSDecl =
7788 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
7789 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007790 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007791 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007792 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007793 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007794 if (RefTy->getPointeeType().isVolatileQualified())
7795 return;
7796
7797 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007798 << LHSDeclRef->getType()
7799 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007800}
7801
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007802/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7803/// operator @p Opc at location @c TokLoc. This routine only supports
7804/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007805ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007806 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007807 Expr *LHSExpr, Expr *RHSExpr) {
7808 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007809 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007810 // The following two variables are used for compound assignment operators
7811 QualType CompLHSTy; // Type of LHS after promotions for computation
7812 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007813 ExprValueKind VK = VK_RValue;
7814 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007815
Douglas Gregor1beec452011-03-12 01:48:56 +00007816 // Check if a 'foo<int>' involved in a binary op, identifies a single
7817 // function unambiguously (i.e. an lvalue ala 13.4)
7818 // But since an assignment can trigger target based overload, exclude it in
7819 // our blind search. i.e:
7820 // template<class T> void f(); template<class T, class U> void f(U);
7821 // f<int> == 0; // resolve f<int> blindly
7822 // void (*p)(int); p = f<int>; // resolve f<int> using target
7823 if (Opc != BO_Assign) {
Richard Trieu4a287fb2011-09-07 01:49:20 +00007824 ExprResult resolvedLHS = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00007825 if (!resolvedLHS.isUsable()) return ExprError();
Richard Trieu4a287fb2011-09-07 01:49:20 +00007826 LHS = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00007827
Richard Trieu4a287fb2011-09-07 01:49:20 +00007828 ExprResult resolvedRHS = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00007829 if (!resolvedRHS.isUsable()) return ExprError();
Richard Trieu4a287fb2011-09-07 01:49:20 +00007830 RHS = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00007831 }
7832
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007833 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007834 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007835 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007836 if (getLangOptions().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +00007837 LHS.get()->getObjectKind() != OK_ObjCProperty) {
7838 VK = LHS.get()->getValueKind();
7839 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007840 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007841 if (!ResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00007842 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007843 break;
John McCalle3027922010-08-25 11:45:40 +00007844 case BO_PtrMemD:
7845 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007846 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007847 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007848 break;
John McCalle3027922010-08-25 11:45:40 +00007849 case BO_Mul:
7850 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007851 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007852 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007853 break;
John McCalle3027922010-08-25 11:45:40 +00007854 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007855 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007856 break;
John McCalle3027922010-08-25 11:45:40 +00007857 case BO_Add:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007858 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007859 break;
John McCalle3027922010-08-25 11:45:40 +00007860 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007861 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007862 break;
John McCalle3027922010-08-25 11:45:40 +00007863 case BO_Shl:
7864 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007865 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007866 break;
John McCalle3027922010-08-25 11:45:40 +00007867 case BO_LE:
7868 case BO_LT:
7869 case BO_GE:
7870 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007871 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007872 break;
John McCalle3027922010-08-25 11:45:40 +00007873 case BO_EQ:
7874 case BO_NE:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007875 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007876 break;
John McCalle3027922010-08-25 11:45:40 +00007877 case BO_And:
7878 case BO_Xor:
7879 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007880 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007881 break;
John McCalle3027922010-08-25 11:45:40 +00007882 case BO_LAnd:
7883 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007884 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007885 break;
John McCalle3027922010-08-25 11:45:40 +00007886 case BO_MulAssign:
7887 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007888 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007889 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007890 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007891 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7892 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007893 break;
John McCalle3027922010-08-25 11:45:40 +00007894 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007895 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007896 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007897 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7898 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007899 break;
John McCalle3027922010-08-25 11:45:40 +00007900 case BO_AddAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007901 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7902 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7903 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007904 break;
John McCalle3027922010-08-25 11:45:40 +00007905 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007906 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7907 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7908 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007909 break;
John McCalle3027922010-08-25 11:45:40 +00007910 case BO_ShlAssign:
7911 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007912 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007913 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007914 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7915 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007916 break;
John McCalle3027922010-08-25 11:45:40 +00007917 case BO_AndAssign:
7918 case BO_XorAssign:
7919 case BO_OrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007920 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007921 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007922 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7923 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007924 break;
John McCalle3027922010-08-25 11:45:40 +00007925 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007926 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
7927 if (getLangOptions().CPlusPlus && !RHS.isInvalid()) {
7928 VK = RHS.get()->getValueKind();
7929 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007930 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007931 break;
7932 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00007933 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007934 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007935
7936 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +00007937 CheckArrayAccess(LHS.get());
7938 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007939
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007940 if (CompResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00007941 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00007942 ResultTy, VK, OK, OpLoc));
Richard Trieu4a287fb2011-09-07 01:49:20 +00007943 if (getLangOptions().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +00007944 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007945 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007946 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007947 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00007948 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00007949 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00007950 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007951}
7952
Sebastian Redl44615072009-10-27 12:10:02 +00007953/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7954/// operators are mixed in a way that suggests that the programmer forgot that
7955/// comparison operators have higher precedence. The most typical example of
7956/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007957static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007958 SourceLocation OpLoc, Expr *LHSExpr,
7959 Expr *RHSExpr) {
Sebastian Redl44615072009-10-27 12:10:02 +00007960 typedef BinaryOperator BinOp;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007961 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
7962 RHSopc = static_cast<BinOp::Opcode>(-1);
7963 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
7964 LHSopc = BO->getOpcode();
7965 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
7966 RHSopc = BO->getOpcode();
Sebastian Redl43028242009-10-26 15:24:15 +00007967
7968 // Subs are not binary operators.
Richard Trieu4a287fb2011-09-07 01:49:20 +00007969 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl43028242009-10-26 15:24:15 +00007970 return;
7971
7972 // Bitwise operations are sometimes used as eager logical ops.
7973 // Don't diagnose this.
Richard Trieu4a287fb2011-09-07 01:49:20 +00007974 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
7975 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007976 return;
7977
Richard Trieu4a287fb2011-09-07 01:49:20 +00007978 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
7979 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00007980 if (!isLeftComp && !isRightComp) return;
7981
Richard Trieu4a287fb2011-09-07 01:49:20 +00007982 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
7983 OpLoc)
7984 : SourceRange(OpLoc, RHSExpr->getLocEnd());
7985 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
7986 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00007987 SourceRange ParensRange = isLeftComp ?
Richard Trieu4a287fb2011-09-07 01:49:20 +00007988 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
7989 RHSExpr->getLocEnd())
7990 : SourceRange(LHSExpr->getLocStart(),
7991 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu73088052011-08-10 22:41:34 +00007992
7993 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7994 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
7995 SuggestParentheses(Self, OpLoc,
7996 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007997 RHSExpr->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +00007998 SuggestParentheses(Self, OpLoc,
7999 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8000 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00008001}
8002
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008003/// \brief It accepts a '&' expr that is inside a '|' one.
8004/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8005/// in parentheses.
8006static void
8007EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8008 BinaryOperator *Bop) {
8009 assert(Bop->getOpcode() == BO_And);
8010 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8011 << Bop->getSourceRange() << OpLoc;
8012 SuggestParentheses(Self, Bop->getOperatorLoc(),
8013 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8014 Bop->getSourceRange());
8015}
8016
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008017/// \brief It accepts a '&&' expr that is inside a '||' one.
8018/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8019/// in parentheses.
8020static void
8021EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008022 BinaryOperator *Bop) {
8023 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008024 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8025 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008026 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008027 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008028 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008029}
8030
8031/// \brief Returns true if the given expression can be evaluated as a constant
8032/// 'true'.
8033static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8034 bool Res;
8035 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8036}
8037
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008038/// \brief Returns true if the given expression can be evaluated as a constant
8039/// 'false'.
8040static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8041 bool Res;
8042 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8043}
8044
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008045/// \brief Look for '&&' in the left hand of a '||' expr.
8046static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008047 Expr *LHSExpr, Expr *RHSExpr) {
8048 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008049 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008050 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008051 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008052 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008053 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8054 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8055 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8056 } else if (Bop->getOpcode() == BO_LOr) {
8057 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8058 // If it's "a || b && 1 || c" we didn't warn earlier for
8059 // "a || b && 1", but warn now.
8060 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8061 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8062 }
8063 }
8064 }
8065}
8066
8067/// \brief Look for '&&' in the right hand of a '||' expr.
8068static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008069 Expr *LHSExpr, Expr *RHSExpr) {
8070 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008071 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008072 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008073 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008074 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008075 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8076 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8077 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008078 }
8079 }
8080}
8081
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008082/// \brief Look for '&' in the left or right hand of a '|' expr.
8083static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8084 Expr *OrArg) {
8085 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8086 if (Bop->getOpcode() == BO_And)
8087 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8088 }
8089}
8090
Sebastian Redl43028242009-10-26 15:24:15 +00008091/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008092/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008093static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008094 SourceLocation OpLoc, Expr *LHSExpr,
8095 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008096 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008097 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008098 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008099
8100 // Diagnose "arg1 & arg2 | arg3"
8101 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008102 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8103 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008104 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008105
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008106 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8107 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008108 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008109 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8110 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008111 }
Sebastian Redl43028242009-10-26 15:24:15 +00008112}
8113
Steve Naroff218bc2b2007-05-04 21:54:46 +00008114// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008115ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008116 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008117 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +00008118 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008119 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8120 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008121
Sebastian Redl43028242009-10-26 15:24:15 +00008122 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008123 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00008124
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008125 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +00008126}
8127
John McCalldadc5752010-08-24 06:29:42 +00008128ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008129 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008130 Expr *LHSExpr, Expr *RHSExpr) {
John McCall622114c2010-12-06 05:26:58 +00008131 if (getLangOptions().CPlusPlus) {
8132 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008133
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008134 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) {
John McCall622114c2010-12-06 05:26:58 +00008135 UseBuiltinOperator = false;
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008136 } else if (Opc == BO_Assign &&
8137 LHSExpr->getObjectKind() == OK_ObjCProperty) {
John McCall622114c2010-12-06 05:26:58 +00008138 UseBuiltinOperator = true;
8139 } else {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008140 UseBuiltinOperator = !LHSExpr->getType()->isOverloadableType() &&
8141 !RHSExpr->getType()->isOverloadableType();
John McCall622114c2010-12-06 05:26:58 +00008142 }
8143
8144 if (!UseBuiltinOperator) {
8145 // Find all of the overloaded operators visible from this
8146 // point. We perform both an operator-name lookup from the local
8147 // scope and an argument-dependent lookup based on the types of
8148 // the arguments.
8149 UnresolvedSet<16> Functions;
8150 OverloadedOperatorKind OverOp
8151 = BinaryOperator::getOverloadedOperator(Opc);
8152 if (S && OverOp != OO_None)
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008153 LookupOverloadedOperatorName(OverOp, S, LHSExpr->getType(),
8154 RHSExpr->getType(), Functions);
John McCall622114c2010-12-06 05:26:58 +00008155
8156 // Build the (potentially-overloaded, potentially-dependent)
8157 // binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008158 return CreateOverloadedBinOp(OpLoc, Opc, Functions, LHSExpr, RHSExpr);
John McCall622114c2010-12-06 05:26:58 +00008159 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00008160 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008161
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008162 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008163 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008164}
8165
John McCalldadc5752010-08-24 06:29:42 +00008166ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008167 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008168 Expr *InputExpr) {
8169 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008170 ExprValueKind VK = VK_RValue;
8171 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008172 QualType resultType;
8173 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008174 case UO_PreInc:
8175 case UO_PreDec:
8176 case UO_PostInc:
8177 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008178 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008179 Opc == UO_PreInc ||
8180 Opc == UO_PostInc,
8181 Opc == UO_PreInc ||
8182 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008183 break;
John McCalle3027922010-08-25 11:45:40 +00008184 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00008185 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008186 break;
John McCall31996342011-04-07 08:22:57 +00008187 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00008188 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00008189 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008190 Input = move(resolved);
8191 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8192 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008193 break;
John McCall31996342011-04-07 08:22:57 +00008194 }
John McCalle3027922010-08-25 11:45:40 +00008195 case UO_Plus:
8196 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008197 Input = UsualUnaryConversions(Input.take());
8198 if (Input.isInvalid()) return ExprError();
8199 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008200 if (resultType->isDependentType())
8201 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008202 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8203 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008204 break;
8205 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8206 resultType->isEnumeralType())
8207 break;
8208 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008209 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008210 resultType->isPointerType())
8211 break;
John McCall36226622010-10-12 02:09:17 +00008212 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008213 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008214 if (Input.isInvalid()) return ExprError();
8215 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008216 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008217
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008218 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008219 << resultType << Input.get()->getSourceRange());
8220
John McCalle3027922010-08-25 11:45:40 +00008221 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008222 Input = UsualUnaryConversions(Input.take());
8223 if (Input.isInvalid()) return ExprError();
8224 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008225 if (resultType->isDependentType())
8226 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008227 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8228 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8229 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008230 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008231 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008232 else if (resultType->hasIntegerRepresentation())
8233 break;
8234 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008235 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008236 if (Input.isInvalid()) return ExprError();
8237 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008238 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008239 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008240 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008241 }
Steve Naroff35d85152007-05-07 00:24:15 +00008242 break;
John Wiegley01296292011-04-08 18:41:53 +00008243
John McCalle3027922010-08-25 11:45:40 +00008244 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008245 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008246 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8247 if (Input.isInvalid()) return ExprError();
8248 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008249 if (resultType->isDependentType())
8250 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008251 if (resultType->isScalarType()) {
8252 // C99 6.5.3.3p1: ok, fallthrough;
8253 if (Context.getLangOptions().CPlusPlus) {
8254 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8255 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008256 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8257 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008258 }
John McCall36226622010-10-12 02:09:17 +00008259 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008260 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008261 if (Input.isInvalid()) return ExprError();
8262 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008263 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008264 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008265 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008266 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008267
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008268 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008269 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008270 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008271 break;
John McCalle3027922010-08-25 11:45:40 +00008272 case UO_Real:
8273 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008274 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008275 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00008276 if (Input.isInvalid()) return ExprError();
8277 if (Input.get()->getValueKind() != VK_RValue &&
8278 Input.get()->getObjectKind() == OK_Ordinary)
8279 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008280 break;
John McCalle3027922010-08-25 11:45:40 +00008281 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008282 resultType = Input.get()->getType();
8283 VK = Input.get()->getValueKind();
8284 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008285 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008286 }
John Wiegley01296292011-04-08 18:41:53 +00008287 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008288 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008289
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008290 // Check for array bounds violations in the operand of the UnaryOperator,
8291 // except for the '*' and '&' operators that have to be handled specially
8292 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8293 // that are explicitly defined as valid by the standard).
8294 if (Opc != UO_AddrOf && Opc != UO_Deref)
8295 CheckArrayAccess(Input.get());
8296
John Wiegley01296292011-04-08 18:41:53 +00008297 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008298 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008299}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008300
John McCalldadc5752010-08-24 06:29:42 +00008301ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008302 UnaryOperatorKind Opc, Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008303 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008304 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008305 // Find all of the overloaded operators visible from this
8306 // point. We perform both an operator-name lookup from the local
8307 // scope and an argument-dependent lookup based on the types of
8308 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008309 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008310 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008311 if (S && OverOp != OO_None)
8312 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8313 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008314
John McCallb268a282010-08-23 23:25:46 +00008315 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008316 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008317
John McCallb268a282010-08-23 23:25:46 +00008318 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008319}
8320
Douglas Gregor5287f092009-11-05 00:51:44 +00008321// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008322ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008323 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008324 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008325}
8326
Steve Naroff66356bd2007-09-16 14:56:35 +00008327/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008328ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008329 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008330 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008331 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008332 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008333 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008334}
8335
John McCall31168b02011-06-15 23:02:42 +00008336/// Given the last statement in a statement-expression, check whether
8337/// the result is a producing expression (like a call to an
8338/// ns_returns_retained function) and, if so, rebuild it to hoist the
8339/// release out of the full-expression. Otherwise, return null.
8340/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +00008341static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +00008342 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +00008343 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCall31168b02011-06-15 23:02:42 +00008344 if (!cleanups) return 0;
8345
8346 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +00008347 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCall31168b02011-06-15 23:02:42 +00008348 return 0;
8349
8350 // Splice out the cast. This shouldn't modify any interesting
8351 // features of the statement.
8352 Expr *producer = cast->getSubExpr();
8353 assert(producer->getType() == cast->getType());
8354 assert(producer->getValueKind() == cast->getValueKind());
8355 cleanups->setSubExpr(producer);
8356 return cleanups;
8357}
8358
John McCalldadc5752010-08-24 06:29:42 +00008359ExprResult
John McCallb268a282010-08-23 23:25:46 +00008360Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008361 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008362 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8363 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8364
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008365 bool isFileScope
8366 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008367 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008368 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008369
Chris Lattner366727f2007-07-24 16:58:17 +00008370 // FIXME: there are a variety of strange constraints to enforce here, for
8371 // example, it is not possible to goto into a stmt expression apparently.
8372 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008373
Chris Lattner366727f2007-07-24 16:58:17 +00008374 // If there are sub stmts in the compound stmt, take the type of the last one
8375 // as the type of the stmtexpr.
8376 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008377 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008378 if (!Compound->body_empty()) {
8379 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008380 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008381 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008382 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8383 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008384 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008385 }
John McCall31168b02011-06-15 23:02:42 +00008386
John Wiegley01296292011-04-08 18:41:53 +00008387 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008388 // Do function/array conversion on the last expression, but not
8389 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008390 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8391 if (LastExpr.isInvalid())
8392 return ExprError();
8393 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008394
John Wiegley01296292011-04-08 18:41:53 +00008395 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008396 // In ARC, if the final expression ends in a consume, splice
8397 // the consume out and bind it later. In the alternate case
8398 // (when dealing with a retainable type), the result
8399 // initialization will create a produce. In both cases the
8400 // result will be +1, and we'll need to balance that out with
8401 // a bind.
8402 if (Expr *rebuiltLastStmt
8403 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8404 LastExpr = rebuiltLastStmt;
8405 } else {
8406 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008407 InitializedEntity::InitializeResult(LPLoc,
8408 Ty,
8409 false),
8410 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008411 LastExpr);
8412 }
8413
John Wiegley01296292011-04-08 18:41:53 +00008414 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008415 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008416 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008417 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008418 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008419 else
John Wiegley01296292011-04-08 18:41:53 +00008420 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008421 StmtExprMayBindToTemp = true;
8422 }
8423 }
8424 }
Chris Lattner944d3062008-07-26 19:51:01 +00008425 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008426
Eli Friedmanba961a92009-03-23 00:24:07 +00008427 // FIXME: Check that expression type is complete/non-abstract; statement
8428 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008429 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8430 if (StmtExprMayBindToTemp)
8431 return MaybeBindToTemporary(ResStmtExpr);
8432 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008433}
Steve Naroff78864672007-08-01 22:05:33 +00008434
John McCalldadc5752010-08-24 06:29:42 +00008435ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008436 TypeSourceInfo *TInfo,
8437 OffsetOfComponent *CompPtr,
8438 unsigned NumComponents,
8439 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008440 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008441 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008442 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008443
Chris Lattnerf17bd422007-08-30 17:45:32 +00008444 // We must have at least one component that refers to the type, and the first
8445 // one is known to be a field designator. Verify that the ArgTy represents
8446 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008447 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008448 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8449 << ArgTy << TypeRange);
8450
8451 // Type must be complete per C99 7.17p3 because a declaring a variable
8452 // with an incomplete type would be ill-formed.
8453 if (!Dependent
8454 && RequireCompleteType(BuiltinLoc, ArgTy,
8455 PDiag(diag::err_offsetof_incomplete_type)
8456 << TypeRange))
8457 return ExprError();
8458
Chris Lattner78502cf2007-08-31 21:49:13 +00008459 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8460 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008461 // FIXME: This diagnostic isn't actually visible because the location is in
8462 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008463 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008464 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8465 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008466
8467 bool DidWarnAboutNonPOD = false;
8468 QualType CurrentType = ArgTy;
8469 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008470 SmallVector<OffsetOfNode, 4> Comps;
8471 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008472 for (unsigned i = 0; i != NumComponents; ++i) {
8473 const OffsetOfComponent &OC = CompPtr[i];
8474 if (OC.isBrackets) {
8475 // Offset of an array sub-field. TODO: Should we allow vector elements?
8476 if (!CurrentType->isDependentType()) {
8477 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8478 if(!AT)
8479 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8480 << CurrentType);
8481 CurrentType = AT->getElementType();
8482 } else
8483 CurrentType = Context.DependentTy;
8484
8485 // The expression must be an integral expression.
8486 // FIXME: An integral constant expression?
8487 Expr *Idx = static_cast<Expr*>(OC.U.E);
8488 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8489 !Idx->getType()->isIntegerType())
8490 return ExprError(Diag(Idx->getLocStart(),
8491 diag::err_typecheck_subscript_not_integer)
8492 << Idx->getSourceRange());
8493
8494 // Record this array index.
8495 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8496 Exprs.push_back(Idx);
8497 continue;
8498 }
8499
8500 // Offset of a field.
8501 if (CurrentType->isDependentType()) {
8502 // We have the offset of a field, but we can't look into the dependent
8503 // type. Just record the identifier of the field.
8504 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8505 CurrentType = Context.DependentTy;
8506 continue;
8507 }
8508
8509 // We need to have a complete type to look into.
8510 if (RequireCompleteType(OC.LocStart, CurrentType,
8511 diag::err_offsetof_incomplete_type))
8512 return ExprError();
8513
8514 // Look for the designated field.
8515 const RecordType *RC = CurrentType->getAs<RecordType>();
8516 if (!RC)
8517 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8518 << CurrentType);
8519 RecordDecl *RD = RC->getDecl();
8520
8521 // C++ [lib.support.types]p5:
8522 // The macro offsetof accepts a restricted set of type arguments in this
8523 // International Standard. type shall be a POD structure or a POD union
8524 // (clause 9).
8525 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8526 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008527 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008528 PDiag(diag::warn_offsetof_non_pod_type)
8529 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8530 << CurrentType))
8531 DidWarnAboutNonPOD = true;
8532 }
8533
8534 // Look for the field.
8535 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8536 LookupQualifiedName(R, RD);
8537 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008538 IndirectFieldDecl *IndirectMemberDecl = 0;
8539 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008540 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008541 MemberDecl = IndirectMemberDecl->getAnonField();
8542 }
8543
Douglas Gregor882211c2010-04-28 22:16:22 +00008544 if (!MemberDecl)
8545 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8546 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8547 OC.LocEnd));
8548
Douglas Gregor10982ea2010-04-28 22:36:06 +00008549 // C99 7.17p3:
8550 // (If the specified member is a bit-field, the behavior is undefined.)
8551 //
8552 // We diagnose this as an error.
8553 if (MemberDecl->getBitWidth()) {
8554 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8555 << MemberDecl->getDeclName()
8556 << SourceRange(BuiltinLoc, RParenLoc);
8557 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8558 return ExprError();
8559 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008560
8561 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008562 if (IndirectMemberDecl)
8563 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008564
Douglas Gregord1702062010-04-29 00:18:15 +00008565 // If the member was found in a base class, introduce OffsetOfNodes for
8566 // the base class indirections.
8567 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8568 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008569 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008570 CXXBasePath &Path = Paths.front();
8571 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8572 B != BEnd; ++B)
8573 Comps.push_back(OffsetOfNode(B->Base));
8574 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008575
Francois Pichet783dd6e2010-11-21 06:08:52 +00008576 if (IndirectMemberDecl) {
8577 for (IndirectFieldDecl::chain_iterator FI =
8578 IndirectMemberDecl->chain_begin(),
8579 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8580 assert(isa<FieldDecl>(*FI));
8581 Comps.push_back(OffsetOfNode(OC.LocStart,
8582 cast<FieldDecl>(*FI), OC.LocEnd));
8583 }
8584 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008585 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008586
Douglas Gregor882211c2010-04-28 22:16:22 +00008587 CurrentType = MemberDecl->getType().getNonReferenceType();
8588 }
8589
8590 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8591 TInfo, Comps.data(), Comps.size(),
8592 Exprs.data(), Exprs.size(), RParenLoc));
8593}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008594
John McCalldadc5752010-08-24 06:29:42 +00008595ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008596 SourceLocation BuiltinLoc,
8597 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008598 ParsedType ParsedArgTy,
John McCall36226622010-10-12 02:09:17 +00008599 OffsetOfComponent *CompPtr,
8600 unsigned NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008601 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +00008602
Douglas Gregor882211c2010-04-28 22:16:22 +00008603 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00008604 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +00008605 if (ArgTy.isNull())
8606 return ExprError();
8607
Eli Friedman06dcfd92010-08-05 10:15:45 +00008608 if (!ArgTInfo)
8609 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8610
8611 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008612 RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008613}
8614
8615
John McCalldadc5752010-08-24 06:29:42 +00008616ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008617 Expr *CondExpr,
8618 Expr *LHSExpr, Expr *RHSExpr,
8619 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008620 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8621
John McCall7decc9e2010-11-18 06:31:45 +00008622 ExprValueKind VK = VK_RValue;
8623 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008624 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008625 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008626 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008627 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008628 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008629 } else {
8630 // The conditional expression is required to be a constant expression.
8631 llvm::APSInt condEval(32);
8632 SourceLocation ExpLoc;
8633 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008634 return ExprError(Diag(ExpLoc,
8635 diag::err_typecheck_choose_expr_requires_constant)
8636 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00008637
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008638 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008639 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8640
8641 resType = ActiveExpr->getType();
8642 ValueDependent = ActiveExpr->isValueDependent();
8643 VK = ActiveExpr->getValueKind();
8644 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008645 }
8646
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008647 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008648 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008649 resType->isDependentType(),
8650 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008651}
8652
Steve Naroffc540d662008-09-03 18:15:37 +00008653//===----------------------------------------------------------------------===//
8654// Clang Extensions.
8655//===----------------------------------------------------------------------===//
8656
8657/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +00008658void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008659 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuba63ce62011-09-09 01:45:06 +00008660 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008661 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +00008662 if (CurScope)
8663 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008664 else
8665 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008666}
8667
Mike Stump82f071f2009-02-04 22:31:32 +00008668void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008669 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008670 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008671 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008672
John McCall8cb7bdf2010-06-04 23:28:52 +00008673 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008674 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008675
John McCall3882ace2011-01-05 12:14:39 +00008676 // GetTypeForDeclarator always produces a function type for a block
8677 // literal signature. Furthermore, it is always a FunctionProtoType
8678 // unless the function was written with a typedef.
8679 assert(T->isFunctionType() &&
8680 "GetTypeForDeclarator made a non-function block signature");
8681
8682 // Look for an explicit signature in that function type.
8683 FunctionProtoTypeLoc ExplicitSignature;
8684
8685 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8686 if (isa<FunctionProtoTypeLoc>(tmp)) {
8687 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8688
8689 // Check whether that explicit signature was synthesized by
8690 // GetTypeForDeclarator. If so, don't save that as part of the
8691 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008692 if (ExplicitSignature.getLocalRangeBegin() ==
8693 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008694 // This would be much cheaper if we stored TypeLocs instead of
8695 // TypeSourceInfos.
8696 TypeLoc Result = ExplicitSignature.getResultLoc();
8697 unsigned Size = Result.getFullDataSize();
8698 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8699 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8700
8701 ExplicitSignature = FunctionProtoTypeLoc();
8702 }
John McCalla3ccba02010-06-04 11:21:44 +00008703 }
Mike Stump11289f42009-09-09 15:08:12 +00008704
John McCall3882ace2011-01-05 12:14:39 +00008705 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8706 CurBlock->FunctionType = T;
8707
8708 const FunctionType *Fn = T->getAs<FunctionType>();
8709 QualType RetTy = Fn->getResultType();
8710 bool isVariadic =
8711 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8712
John McCall8e346702010-06-04 19:02:56 +00008713 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008714
John McCalla3ccba02010-06-04 11:21:44 +00008715 // Don't allow returning a objc interface by value.
8716 if (RetTy->isObjCObjectType()) {
8717 Diag(ParamInfo.getSourceRange().getBegin(),
8718 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8719 return;
8720 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008721
John McCalla3ccba02010-06-04 11:21:44 +00008722 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008723 // return type. TODO: what should we do with declarators like:
8724 // ^ * { ... }
8725 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00008726 if (RetTy != Context.DependentTy)
8727 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008728
John McCalla3ccba02010-06-04 11:21:44 +00008729 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008730 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008731 if (ExplicitSignature) {
8732 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8733 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008734 if (Param->getIdentifier() == 0 &&
8735 !Param->isImplicit() &&
8736 !Param->isInvalidDecl() &&
8737 !getLangOptions().CPlusPlus)
8738 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008739 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008740 }
John McCalla3ccba02010-06-04 11:21:44 +00008741
8742 // Fake up parameter variables if we have a typedef, like
8743 // ^ fntype { ... }
8744 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8745 for (FunctionProtoType::arg_type_iterator
8746 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8747 ParmVarDecl *Param =
8748 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8749 ParamInfo.getSourceRange().getBegin(),
8750 *I);
John McCall8e346702010-06-04 19:02:56 +00008751 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008752 }
Steve Naroffc540d662008-09-03 18:15:37 +00008753 }
John McCalla3ccba02010-06-04 11:21:44 +00008754
John McCall8e346702010-06-04 19:02:56 +00008755 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008756 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +00008757 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +00008758 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8759 CurBlock->TheDecl->param_end(),
8760 /*CheckParameterNames=*/false);
8761 }
8762
John McCalla3ccba02010-06-04 11:21:44 +00008763 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008764 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008765
John McCall8e346702010-06-04 19:02:56 +00008766 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00008767 Diag(ParamInfo.getAttributes()->getLoc(),
8768 diag::warn_attribute_sentinel_not_variadic) << 1;
8769 // FIXME: remove the attribute.
8770 }
8771
8772 // Put the parameter variables in scope. We can bail out immediately
8773 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008774 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008775 return;
8776
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008777 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008778 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8779 (*AI)->setOwningFunction(CurBlock->TheDecl);
8780
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008781 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008782 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008783 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008784
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008785 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008786 }
John McCallf7b2fb52010-01-22 00:28:27 +00008787 }
Steve Naroffc540d662008-09-03 18:15:37 +00008788}
8789
8790/// ActOnBlockError - If there is an error parsing a block, this callback
8791/// is invoked to pop the information about the block from the action impl.
8792void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00008793 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008794 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00008795 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00008796}
8797
8798/// ActOnBlockStmtExpr - This is called when the body of a block statement
8799/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008800ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008801 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008802 // If blocks are disabled, emit an error.
8803 if (!LangOpts.Blocks)
8804 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008805
Douglas Gregor9a28e842010-03-01 23:15:13 +00008806 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008807
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008808 PopDeclContext();
8809
Steve Naroffc540d662008-09-03 18:15:37 +00008810 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008811 if (!BSI->ReturnType.isNull())
8812 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008813
Mike Stump3bf1ab42009-07-28 22:04:01 +00008814 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008815 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008816
John McCallc63de662011-02-02 13:00:07 +00008817 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00008818 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8819 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00008820
John McCall8e346702010-06-04 19:02:56 +00008821 // If the user wrote a function type in some form, try to use that.
8822 if (!BSI->FunctionType.isNull()) {
8823 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8824
8825 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8826 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8827
8828 // Turn protoless block types into nullary block types.
8829 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008830 FunctionProtoType::ExtProtoInfo EPI;
8831 EPI.ExtInfo = Ext;
8832 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008833
8834 // Otherwise, if we don't need to change anything about the function type,
8835 // preserve its sugar structure.
8836 } else if (FTy->getResultType() == RetTy &&
8837 (!NoReturn || FTy->getNoReturnAttr())) {
8838 BlockTy = BSI->FunctionType;
8839
8840 // Otherwise, make the minimal modifications to the function type.
8841 } else {
8842 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008843 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8844 EPI.TypeQuals = 0; // FIXME: silently?
8845 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008846 BlockTy = Context.getFunctionType(RetTy,
8847 FPT->arg_type_begin(),
8848 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008849 EPI);
John McCall8e346702010-06-04 19:02:56 +00008850 }
8851
8852 // If we don't have a function type, just build one from nothing.
8853 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008854 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00008855 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008856 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008857 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008858
John McCall8e346702010-06-04 19:02:56 +00008859 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8860 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008861 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008862
Chris Lattner45542ea2009-04-19 05:28:12 +00008863 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00008864 if (getCurFunction()->NeedsScopeChecking() &&
8865 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008866 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008867
Chris Lattner60f84492011-02-17 23:58:47 +00008868 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008869
Fariborz Jahanian256d39d2011-07-11 18:04:54 +00008870 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8871 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8872 const VarDecl *variable = ci->getVariable();
8873 QualType T = variable->getType();
8874 QualType::DestructionKind destructKind = T.isDestructedType();
8875 if (destructKind != QualType::DK_none)
8876 getCurFunction()->setHasBranchProtectedScope();
8877 }
8878
Douglas Gregor49695f02011-09-06 20:46:03 +00008879 computeNRVO(Body, getCurBlock());
8880
Benjamin Kramera4fb8362011-07-12 14:11:05 +00008881 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8882 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8883 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8884
Douglas Gregor9a28e842010-03-01 23:15:13 +00008885 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008886}
8887
John McCalldadc5752010-08-24 06:29:42 +00008888ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008889 Expr *E, ParsedType Ty,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008890 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008891 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00008892 GetTypeFromParser(Ty, &TInfo);
8893 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008894}
8895
John McCalldadc5752010-08-24 06:29:42 +00008896ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008897 Expr *E, TypeSourceInfo *TInfo,
8898 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008899 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008900
Eli Friedman121ba0c2008-08-09 23:32:40 +00008901 // Get the va_list type
8902 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008903 if (VaListType->isArrayType()) {
8904 // Deal with implicit array decay; for example, on x86-64,
8905 // va_list is an array, but it's supposed to decay to
8906 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008907 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008908 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00008909 ExprResult Result = UsualUnaryConversions(E);
8910 if (Result.isInvalid())
8911 return ExprError();
8912 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00008913 } else {
8914 // Otherwise, the va_list argument must be an l-value because
8915 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008916 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008917 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008918 return ExprError();
8919 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008920
Douglas Gregorad3150c2009-05-19 23:10:31 +00008921 if (!E->isTypeDependent() &&
8922 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008923 return ExprError(Diag(E->getLocStart(),
8924 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008925 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008926 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008927
David Majnemerc75d1a12011-06-14 05:17:32 +00008928 if (!TInfo->getType()->isDependentType()) {
8929 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8930 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8931 << TInfo->getTypeLoc().getSourceRange()))
8932 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00008933
David Majnemerc75d1a12011-06-14 05:17:32 +00008934 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8935 TInfo->getType(),
8936 PDiag(diag::err_second_parameter_to_va_arg_abstract)
8937 << TInfo->getTypeLoc().getSourceRange()))
8938 return ExprError();
8939
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008940 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00008941 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008942 TInfo->getType()->isObjCLifetimeType()
8943 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8944 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00008945 << TInfo->getType()
8946 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00008947 }
Eli Friedman6290ae42011-07-11 21:45:59 +00008948
8949 // Check for va_arg where arguments of the given type will be promoted
8950 // (i.e. this va_arg is guaranteed to have undefined behavior).
8951 QualType PromoteType;
8952 if (TInfo->getType()->isPromotableIntegerType()) {
8953 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8954 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8955 PromoteType = QualType();
8956 }
8957 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8958 PromoteType = Context.DoubleTy;
8959 if (!PromoteType.isNull())
8960 Diag(TInfo->getTypeLoc().getBeginLoc(),
8961 diag::warn_second_parameter_to_va_arg_never_compatible)
8962 << TInfo->getType()
8963 << PromoteType
8964 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00008965 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008966
Abramo Bagnara27db2392010-08-10 10:06:15 +00008967 QualType T = TInfo->getType().getNonLValueExprType(Context);
8968 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00008969}
8970
John McCalldadc5752010-08-24 06:29:42 +00008971ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00008972 // The type of __null will be int or long, depending on the size of
8973 // pointers on the target.
8974 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008975 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
8976 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008977 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008978 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00008979 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00008980 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008981 Ty = Context.LongLongTy;
8982 else {
David Blaikie83d382b2011-09-23 05:06:16 +00008983 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00008984 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00008985
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008986 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00008987}
8988
Alexis Huntc46382e2010-04-28 23:02:27 +00008989static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00008990 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00008991 if (!SemaRef.getLangOptions().ObjC1)
8992 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008993
Anders Carlssonace5d072009-11-10 04:46:30 +00008994 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8995 if (!PT)
8996 return;
8997
8998 // Check if the destination is of type 'id'.
8999 if (!PT->isObjCIdType()) {
9000 // Check if the destination is the 'NSString' interface.
9001 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9002 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9003 return;
9004 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009005
Anders Carlssonace5d072009-11-10 04:46:30 +00009006 // Strip off any parens and casts.
9007 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
Douglas Gregorfb65e592011-07-27 05:40:30 +00009008 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00009009 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009010
Douglas Gregora771f462010-03-31 17:46:05 +00009011 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009012}
9013
Chris Lattner9bad62c2008-01-04 18:04:52 +00009014bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9015 SourceLocation Loc,
9016 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009017 Expr *SrcExpr, AssignmentAction Action,
9018 bool *Complained) {
9019 if (Complained)
9020 *Complained = false;
9021
Chris Lattner9bad62c2008-01-04 18:04:52 +00009022 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00009023 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009024 bool isInvalid = false;
9025 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00009026 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00009027 ConversionFixItGenerator ConvHints;
9028 bool MayHaveConvFixit = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009029
Chris Lattner9bad62c2008-01-04 18:04:52 +00009030 switch (ConvTy) {
David Blaikie83d382b2011-09-23 05:06:16 +00009031 default: llvm_unreachable("Unknown conversion type");
Chris Lattner9bad62c2008-01-04 18:04:52 +00009032 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009033 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009034 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00009035 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9036 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009037 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009038 case IntToPointer:
9039 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00009040 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9041 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009042 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009043 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009044 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009045 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00009046 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9047 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00009048 if (Hint.isNull() && !CheckInferredResultType) {
9049 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9050 }
9051 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009052 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009053 case IncompatiblePointerSign:
9054 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9055 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009056 case FunctionVoidPointer:
9057 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9058 break;
John McCall4fff8f62011-02-01 00:10:29 +00009059 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009060 // Perform array-to-pointer decay if necessary.
9061 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9062
John McCall4fff8f62011-02-01 00:10:29 +00009063 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9064 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9065 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9066 DiagKind = diag::err_typecheck_incompatible_address_space;
9067 break;
John McCall31168b02011-06-15 23:02:42 +00009068
9069
9070 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009071 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00009072 break;
John McCall4fff8f62011-02-01 00:10:29 +00009073 }
9074
9075 llvm_unreachable("unknown error case for discarding qualifiers!");
9076 // fallthrough
9077 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009078 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009079 // If the qualifiers lost were because we were applying the
9080 // (deprecated) C++ conversion from a string literal to a char*
9081 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9082 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009083 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009084 // bit of refactoring (so that the second argument is an
9085 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009086 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009087 // C++ semantics.
9088 if (getLangOptions().CPlusPlus &&
9089 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9090 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009091 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9092 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009093 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009094 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009095 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009096 case IntToBlockPointer:
9097 DiagKind = diag::err_int_to_block_pointer;
9098 break;
9099 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009100 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009101 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009102 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009103 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009104 // it can give a more specific diagnostic.
9105 DiagKind = diag::warn_incompatible_qualified_id;
9106 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009107 case IncompatibleVectors:
9108 DiagKind = diag::warn_incompatible_vectors;
9109 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00009110 case IncompatibleObjCWeakRef:
9111 DiagKind = diag::err_arc_weak_unavailable_assign;
9112 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009113 case Incompatible:
9114 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00009115 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9116 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009117 isInvalid = true;
9118 break;
9119 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009120
Douglas Gregorc68e1402010-04-09 00:35:39 +00009121 QualType FirstType, SecondType;
9122 switch (Action) {
9123 case AA_Assigning:
9124 case AA_Initializing:
9125 // The destination type comes first.
9126 FirstType = DstType;
9127 SecondType = SrcType;
9128 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009129
Douglas Gregorc68e1402010-04-09 00:35:39 +00009130 case AA_Returning:
9131 case AA_Passing:
9132 case AA_Converting:
9133 case AA_Sending:
9134 case AA_Casting:
9135 // The source type comes first.
9136 FirstType = SrcType;
9137 SecondType = DstType;
9138 break;
9139 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009140
Anna Zaks3b402712011-07-28 19:51:27 +00009141 PartialDiagnostic FDiag = PDiag(DiagKind);
9142 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9143
9144 // If we can fix the conversion, suggest the FixIts.
9145 assert(ConvHints.isNull() || Hint.isNull());
9146 if (!ConvHints.isNull()) {
9147 for (llvm::SmallVector<FixItHint, 1>::iterator
9148 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
9149 HI != HE; ++HI)
9150 FDiag << *HI;
9151 } else {
9152 FDiag << Hint;
9153 }
9154 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9155
9156 Diag(Loc, FDiag);
9157
Douglas Gregor33823722011-06-11 01:09:30 +00009158 if (CheckInferredResultType)
9159 EmitRelatedResultTypeNote(SrcExpr);
9160
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009161 if (Complained)
9162 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009163 return isInvalid;
9164}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009165
Chris Lattnerc71d08b2009-04-25 21:59:05 +00009166bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009167 llvm::APSInt ICEResult;
9168 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9169 if (Result)
9170 *Result = ICEResult;
9171 return false;
9172 }
9173
Anders Carlssone54e8a12008-11-30 19:50:32 +00009174 Expr::EvalResult EvalResult;
9175
Mike Stump4e1f26a2009-02-19 03:04:26 +00009176 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00009177 EvalResult.HasSideEffects) {
9178 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9179
9180 if (EvalResult.Diag) {
9181 // We only show the note if it's not the usual "invalid subexpression"
9182 // or if it's actually in a subexpression.
9183 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9184 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9185 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9186 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009187
Anders Carlssone54e8a12008-11-30 19:50:32 +00009188 return true;
9189 }
9190
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009191 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9192 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009193
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009194 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009195 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
David Blaikie9c902b52011-09-25 23:23:43 +00009196 != DiagnosticsEngine::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009197 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009198
Anders Carlssone54e8a12008-11-30 19:50:32 +00009199 if (Result)
9200 *Result = EvalResult.Val.getInt();
9201 return false;
9202}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009203
Douglas Gregorff790f12009-11-26 00:44:06 +00009204void
Mike Stump11289f42009-09-09 15:08:12 +00009205Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009206 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00009207 ExpressionEvaluationContextRecord(NewContext,
9208 ExprTemporaries.size(),
9209 ExprNeedsCleanups));
9210 ExprNeedsCleanups = false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009211}
9212
Richard Trieucfc491d2011-08-02 04:35:43 +00009213void Sema::PopExpressionEvaluationContext() {
Douglas Gregorff790f12009-11-26 00:44:06 +00009214 // Pop the current expression evaluation context off the stack.
9215 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9216 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009217
Douglas Gregorfab31f42009-12-12 07:57:52 +00009218 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9219 if (Rec.PotentiallyReferenced) {
9220 // Mark any remaining declarations in the current position of the stack
9221 // as "referenced". If they were not meant to be referenced, semantic
9222 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009223 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009224 I = Rec.PotentiallyReferenced->begin(),
9225 IEnd = Rec.PotentiallyReferenced->end();
9226 I != IEnd; ++I)
9227 MarkDeclarationReferenced(I->first, I->second);
9228 }
9229
9230 if (Rec.PotentiallyDiagnosed) {
9231 // Emit any pending diagnostics.
9232 for (PotentiallyEmittedDiagnostics::iterator
9233 I = Rec.PotentiallyDiagnosed->begin(),
9234 IEnd = Rec.PotentiallyDiagnosed->end();
9235 I != IEnd; ++I)
9236 Diag(I->first, I->second);
9237 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009238 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009239
9240 // When are coming out of an unevaluated context, clear out any
9241 // temporaries that we may have created as part of the evaluation of
9242 // the expression in that context: they aren't relevant because they
9243 // will never be constructed.
John McCall31168b02011-06-15 23:02:42 +00009244 if (Rec.Context == Unevaluated) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009245 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9246 ExprTemporaries.end());
John McCall31168b02011-06-15 23:02:42 +00009247 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9248
9249 // Otherwise, merge the contexts together.
9250 } else {
9251 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9252 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009253
9254 // Destroy the popped expression evaluation record.
9255 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009256}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009257
John McCall31168b02011-06-15 23:02:42 +00009258void Sema::DiscardCleanupsInEvaluationContext() {
9259 ExprTemporaries.erase(
9260 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
9261 ExprTemporaries.end());
9262 ExprNeedsCleanups = false;
9263}
9264
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009265/// \brief Note that the given declaration was referenced in the source code.
9266///
9267/// This routine should be invoke whenever a given declaration is referenced
9268/// in the source code, and where that reference occurred. If this declaration
9269/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9270/// C99 6.9p3), then the declaration will be marked as used.
9271///
9272/// \param Loc the location where the declaration was referenced.
9273///
9274/// \param D the declaration that has been referenced by the source code.
9275void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9276 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009277
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00009278 D->setReferenced();
9279
Douglas Gregorebada0772010-06-17 23:14:26 +00009280 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009281 return;
Mike Stump11289f42009-09-09 15:08:12 +00009282
Richard Trieucfc491d2011-08-02 04:35:43 +00009283 // Mark a parameter or variable declaration "used", regardless of whether
9284 // we're in a template or not. The reason for this is that unevaluated
9285 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9286 // (-Wunused-variables and -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009287 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009288 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009289 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009290 return;
9291 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009292
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009293 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9294 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009295
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009296 // Do not mark anything as "used" within a dependent context; wait for
9297 // an instantiation.
9298 if (CurContext->isDependentContext())
9299 return;
Mike Stump11289f42009-09-09 15:08:12 +00009300
Douglas Gregorff790f12009-11-26 00:44:06 +00009301 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009302 case Unevaluated:
9303 // We are in an expression that is not potentially evaluated; do nothing.
9304 return;
Mike Stump11289f42009-09-09 15:08:12 +00009305
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009306 case PotentiallyEvaluated:
9307 // We are in a potentially-evaluated expression, so this declaration is
9308 // "used"; handle this below.
9309 break;
Mike Stump11289f42009-09-09 15:08:12 +00009310
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009311 case PotentiallyPotentiallyEvaluated:
9312 // We are in an expression that may be potentially evaluated; queue this
9313 // declaration reference until we know whether the expression is
9314 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009315 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009316 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009317
9318 case PotentiallyEvaluatedIfUsed:
9319 // Referenced declarations will only be used if the construct in the
9320 // containing expression is used.
9321 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009322 }
Mike Stump11289f42009-09-09 15:08:12 +00009323
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009324 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009325 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009326 if (Constructor->isDefaulted()) {
9327 if (Constructor->isDefaultConstructor()) {
9328 if (Constructor->isTrivial())
9329 return;
9330 if (!Constructor->isUsed(false))
9331 DefineImplicitDefaultConstructor(Loc, Constructor);
9332 } else if (Constructor->isCopyConstructor()) {
9333 if (!Constructor->isUsed(false))
9334 DefineImplicitCopyConstructor(Loc, Constructor);
9335 } else if (Constructor->isMoveConstructor()) {
9336 if (!Constructor->isUsed(false))
9337 DefineImplicitMoveConstructor(Loc, Constructor);
9338 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009339 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009340
Douglas Gregor88d292c2010-05-13 16:44:06 +00009341 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009342 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Alexis Huntf91729462011-05-12 22:46:25 +00009343 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009344 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009345 if (Destructor->isVirtual())
9346 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009347 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Alexis Huntc9a55732011-05-14 05:23:28 +00009348 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009349 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009350 if (!MethodDecl->isUsed(false)) {
9351 if (MethodDecl->isCopyAssignmentOperator())
9352 DefineImplicitCopyAssignment(Loc, MethodDecl);
9353 else
9354 DefineImplicitMoveAssignment(Loc, MethodDecl);
9355 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00009356 } else if (MethodDecl->isVirtual())
9357 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009358 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009359 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009360 // Recursive functions should be marked when used from another function.
9361 if (CurContext == Function) return;
9362
Mike Stump11289f42009-09-09 15:08:12 +00009363 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009364 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009365 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009366 bool AlreadyInstantiated = false;
9367 if (FunctionTemplateSpecializationInfo *SpecInfo
9368 = Function->getTemplateSpecializationInfo()) {
9369 if (SpecInfo->getPointOfInstantiation().isInvalid())
9370 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009371 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009372 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009373 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009374 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009375 = Function->getMemberSpecializationInfo()) {
9376 if (MSInfo->getPointOfInstantiation().isInvalid())
9377 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009378 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009379 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009380 AlreadyInstantiated = true;
9381 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009382
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009383 if (!AlreadyInstantiated) {
9384 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9385 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9386 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9387 Loc));
9388 else
Chandler Carruth54080172010-08-25 08:44:16 +00009389 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009390 }
John McCall83779672011-02-19 02:53:41 +00009391 } else {
9392 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009393 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9394 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009395 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009396 MarkDeclarationReferenced(Loc, *i);
9397 }
John McCall83779672011-02-19 02:53:41 +00009398 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009399
John McCall83779672011-02-19 02:53:41 +00009400 // Keep track of used but undefined functions.
9401 if (!Function->isPure() && !Function->hasBody() &&
9402 Function->getLinkage() != ExternalLinkage) {
9403 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9404 if (old.isInvalid()) old = Loc;
9405 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009406
John McCall83779672011-02-19 02:53:41 +00009407 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009408 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009409 }
Mike Stump11289f42009-09-09 15:08:12 +00009410
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009411 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009412 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009413 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009414 Var->getInstantiatedFromStaticDataMember()) {
9415 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9416 assert(MSInfo && "Missing member specialization information?");
9417 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9418 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9419 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redl2ac2c722011-04-29 08:19:30 +00009420 // This is a modification of an existing AST node. Notify listeners.
9421 if (ASTMutationListener *L = getASTMutationListener())
9422 L->StaticDataMemberInstantiated(Var);
Chandler Carruth54080172010-08-25 08:44:16 +00009423 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009424 }
9425 }
Mike Stump11289f42009-09-09 15:08:12 +00009426
John McCall15dd4042011-02-21 19:25:48 +00009427 // Keep track of used but undefined variables. We make a hole in
9428 // the warning for static const data members with in-line
9429 // initializers.
John McCall83779672011-02-19 02:53:41 +00009430 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009431 && Var->getLinkage() != ExternalLinkage
9432 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009433 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9434 if (old.isInvalid()) old = Loc;
9435 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009436
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009437 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009438 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009439 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009440}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009441
Douglas Gregor5597ab42010-05-07 23:12:07 +00009442namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009443 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009444 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009445 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009446 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9447 Sema &S;
9448 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009449
Douglas Gregor5597ab42010-05-07 23:12:07 +00009450 public:
9451 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009452
Douglas Gregor5597ab42010-05-07 23:12:07 +00009453 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009454
9455 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9456 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009457 };
9458}
9459
Chandler Carruthaf80f662010-06-09 08:17:30 +00009460bool MarkReferencedDecls::TraverseTemplateArgument(
9461 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009462 if (Arg.getKind() == TemplateArgument::Declaration) {
9463 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9464 }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009465
9466 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009467}
9468
Chandler Carruthaf80f662010-06-09 08:17:30 +00009469bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +00009470 if (ClassTemplateSpecializationDecl *Spec
9471 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9472 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +00009473 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +00009474 }
9475
Chandler Carruthc65667c2010-06-10 10:31:57 +00009476 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +00009477}
9478
9479void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9480 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +00009481 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +00009482}
9483
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009484namespace {
9485 /// \brief Helper class that marks all of the declarations referenced by
9486 /// potentially-evaluated subexpressions as "referenced".
9487 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9488 Sema &S;
9489
9490 public:
9491 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9492
9493 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9494
9495 void VisitDeclRefExpr(DeclRefExpr *E) {
9496 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9497 }
9498
9499 void VisitMemberExpr(MemberExpr *E) {
9500 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009501 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009502 }
9503
9504 void VisitCXXNewExpr(CXXNewExpr *E) {
9505 if (E->getConstructor())
9506 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9507 if (E->getOperatorNew())
9508 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9509 if (E->getOperatorDelete())
9510 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009511 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009512 }
9513
9514 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9515 if (E->getOperatorDelete())
9516 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00009517 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9518 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9519 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9520 S.MarkDeclarationReferenced(E->getLocStart(),
9521 S.LookupDestructor(Record));
9522 }
9523
Douglas Gregor32b3de52010-09-11 23:32:50 +00009524 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009525 }
9526
9527 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9528 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +00009529 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009530 }
9531
9532 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9533 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9534 }
Douglas Gregorf0873f42010-10-19 17:17:35 +00009535
9536 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9537 Visit(E->getExpr());
9538 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009539 };
9540}
9541
9542/// \brief Mark any declarations that appear within this expression or any
9543/// potentially-evaluated subexpressions as "referenced".
9544void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9545 EvaluatedExprMarker(*this).Visit(E);
9546}
9547
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009548/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9549/// of the program being compiled.
9550///
9551/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009552/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009553/// possibility that the code will actually be executable. Code in sizeof()
9554/// expressions, code used only during overload resolution, etc., are not
9555/// potentially evaluated. This routine will suppress such diagnostics or,
9556/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009557/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009558/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009559///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009560/// This routine should be used for all diagnostics that describe the run-time
9561/// behavior of a program, such as passing a non-POD value through an ellipsis.
9562/// Failure to do so will likely result in spurious diagnostics or failures
9563/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +00009564bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009565 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +00009566 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009567 case Unevaluated:
9568 // The argument will never be evaluated, so don't complain.
9569 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009570
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009571 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009572 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +00009573 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00009574 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +00009575 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +00009576 }
9577 else
9578 Diag(Loc, PD);
9579
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009580 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009581
Douglas Gregorda8cdbc2009-12-22 01:01:55 +00009582 case PotentiallyPotentiallyEvaluated:
9583 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9584 break;
9585 }
9586
9587 return false;
9588}
9589
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009590bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9591 CallExpr *CE, FunctionDecl *FD) {
9592 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9593 return false;
9594
9595 PartialDiagnostic Note =
9596 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9597 << FD->getDeclName() : PDiag();
9598 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009599
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009600 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009601 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009602 PDiag(diag::err_call_function_incomplete_return)
9603 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009604 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009605 << CE->getSourceRange(),
9606 std::make_pair(NoteLoc, Note)))
9607 return true;
9608
9609 return false;
9610}
9611
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009612// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +00009613// will prevent this condition from triggering, which is what we want.
9614void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9615 SourceLocation Loc;
9616
John McCall0506e4a2009-11-11 02:41:58 +00009617 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009618 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +00009619
Chandler Carruthf87d6c02011-08-16 22:30:10 +00009620 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009621 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +00009622 return;
9623
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009624 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9625
John McCallb0e419e2009-11-12 00:06:05 +00009626 // Greylist some idioms by putting them into a warning subcategory.
9627 if (ObjCMessageExpr *ME
9628 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9629 Selector Sel = ME->getSelector();
9630
John McCallb0e419e2009-11-12 00:06:05 +00009631 // self = [<foo> init...]
Douglas Gregor486b74e2011-09-27 16:10:05 +00009632 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +00009633 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9634
9635 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +00009636 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +00009637 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9638 }
John McCall0506e4a2009-11-11 02:41:58 +00009639
John McCalld5707ab2009-10-12 21:59:07 +00009640 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +00009641 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009642 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +00009643 return;
9644
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009645 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +00009646 Loc = Op->getOperatorLoc();
9647 } else {
9648 // Not an assignment.
9649 return;
9650 }
9651
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009652 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009653
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009654 SourceLocation Open = E->getSourceRange().getBegin();
9655 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9656 Diag(Loc, diag::note_condition_assign_silence)
9657 << FixItHint::CreateInsertion(Open, "(")
9658 << FixItHint::CreateInsertion(Close, ")");
9659
Douglas Gregor2d4f64f2011-01-19 16:50:08 +00009660 if (IsOrAssign)
9661 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9662 << FixItHint::CreateReplacement(Loc, "!=");
9663 else
9664 Diag(Loc, diag::note_condition_assign_to_comparison)
9665 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +00009666}
9667
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009668/// \brief Redundant parentheses over an equality comparison can indicate
9669/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +00009670void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009671 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +00009672 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009673 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9674 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009675 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00009676 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +00009677 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +00009678
Richard Trieuba63ce62011-09-09 01:45:06 +00009679 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009680
9681 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +00009682 if (opE->getOpcode() == BO_EQ &&
9683 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9684 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009685 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +00009686
Ted Kremenekae022092011-02-02 02:20:30 +00009687 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +00009688 Diag(Loc, diag::note_equality_comparison_silence)
Richard Trieuba63ce62011-09-09 01:45:06 +00009689 << FixItHint::CreateRemoval(ParenE->getSourceRange().getBegin())
9690 << FixItHint::CreateRemoval(ParenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009691 Diag(Loc, diag::note_equality_comparison_to_assign)
9692 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009693 }
9694}
9695
John Wiegley01296292011-04-08 18:41:53 +00009696ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +00009697 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +00009698 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9699 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +00009700
John McCall0009fcc2011-04-26 20:42:42 +00009701 ExprResult result = CheckPlaceholderExpr(E);
9702 if (result.isInvalid()) return ExprError();
9703 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00009704
John McCall0009fcc2011-04-26 20:42:42 +00009705 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +00009706 if (getLangOptions().CPlusPlus)
9707 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9708
John Wiegley01296292011-04-08 18:41:53 +00009709 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9710 if (ERes.isInvalid())
9711 return ExprError();
9712 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +00009713
9714 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +00009715 if (!T->isScalarType()) { // C99 6.8.4.1p1
9716 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9717 << T << E->getSourceRange();
9718 return ExprError();
9719 }
John McCalld5707ab2009-10-12 21:59:07 +00009720 }
9721
John Wiegley01296292011-04-08 18:41:53 +00009722 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +00009723}
Douglas Gregore60e41a2010-05-06 17:25:47 +00009724
John McCalldadc5752010-08-24 06:29:42 +00009725ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009726 Expr *SubExpr) {
9727 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +00009728 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009729
Richard Trieuba63ce62011-09-09 01:45:06 +00009730 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +00009731}
John McCall36e7fe32010-10-12 00:20:44 +00009732
John McCall31996342011-04-07 08:22:57 +00009733namespace {
John McCall2979fe02011-04-12 00:42:48 +00009734 /// A visitor for rebuilding a call to an __unknown_any expression
9735 /// to have an appropriate type.
9736 struct RebuildUnknownAnyFunction
9737 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9738
9739 Sema &S;
9740
9741 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9742
9743 ExprResult VisitStmt(Stmt *S) {
9744 llvm_unreachable("unexpected statement!");
9745 return ExprError();
9746 }
9747
Richard Trieu10162ab2011-09-09 03:59:41 +00009748 ExprResult VisitExpr(Expr *E) {
9749 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
9750 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +00009751 return ExprError();
9752 }
9753
9754 /// Rebuild an expression which simply semantically wraps another
9755 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +00009756 template <class T> ExprResult rebuildSugarExpr(T *E) {
9757 ExprResult SubResult = Visit(E->getSubExpr());
9758 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +00009759
Richard Trieu10162ab2011-09-09 03:59:41 +00009760 Expr *SubExpr = SubResult.take();
9761 E->setSubExpr(SubExpr);
9762 E->setType(SubExpr->getType());
9763 E->setValueKind(SubExpr->getValueKind());
9764 assert(E->getObjectKind() == OK_Ordinary);
9765 return E;
John McCall2979fe02011-04-12 00:42:48 +00009766 }
9767
Richard Trieu10162ab2011-09-09 03:59:41 +00009768 ExprResult VisitParenExpr(ParenExpr *E) {
9769 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +00009770 }
9771
Richard Trieu10162ab2011-09-09 03:59:41 +00009772 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9773 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +00009774 }
9775
Richard Trieu10162ab2011-09-09 03:59:41 +00009776 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9777 ExprResult SubResult = Visit(E->getSubExpr());
9778 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +00009779
Richard Trieu10162ab2011-09-09 03:59:41 +00009780 Expr *SubExpr = SubResult.take();
9781 E->setSubExpr(SubExpr);
9782 E->setType(S.Context.getPointerType(SubExpr->getType()));
9783 assert(E->getValueKind() == VK_RValue);
9784 assert(E->getObjectKind() == OK_Ordinary);
9785 return E;
John McCall2979fe02011-04-12 00:42:48 +00009786 }
9787
Richard Trieu10162ab2011-09-09 03:59:41 +00009788 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
9789 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +00009790
Richard Trieu10162ab2011-09-09 03:59:41 +00009791 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +00009792
Richard Trieu10162ab2011-09-09 03:59:41 +00009793 assert(E->getValueKind() == VK_RValue);
John McCall2979fe02011-04-12 00:42:48 +00009794 if (S.getLangOptions().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +00009795 !(isa<CXXMethodDecl>(VD) &&
9796 cast<CXXMethodDecl>(VD)->isInstance()))
9797 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +00009798
Richard Trieu10162ab2011-09-09 03:59:41 +00009799 return E;
John McCall2979fe02011-04-12 00:42:48 +00009800 }
9801
Richard Trieu10162ab2011-09-09 03:59:41 +00009802 ExprResult VisitMemberExpr(MemberExpr *E) {
9803 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +00009804 }
9805
Richard Trieu10162ab2011-09-09 03:59:41 +00009806 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9807 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +00009808 }
9809 };
9810}
9811
9812/// Given a function expression of unknown-any type, try to rebuild it
9813/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +00009814static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
9815 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
9816 if (Result.isInvalid()) return ExprError();
9817 return S.DefaultFunctionArrayConversion(Result.take());
John McCall2979fe02011-04-12 00:42:48 +00009818}
9819
9820namespace {
John McCall2d2e8702011-04-11 07:02:50 +00009821 /// A visitor for rebuilding an expression of type __unknown_anytype
9822 /// into one which resolves the type directly on the referring
9823 /// expression. Strict preservation of the original source
9824 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +00009825 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +00009826 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +00009827
9828 Sema &S;
9829
9830 /// The current destination type.
9831 QualType DestType;
9832
Richard Trieu10162ab2011-09-09 03:59:41 +00009833 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
9834 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +00009835
John McCall39439732011-04-09 22:50:59 +00009836 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +00009837 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +00009838 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009839 }
9840
Richard Trieu10162ab2011-09-09 03:59:41 +00009841 ExprResult VisitExpr(Expr *E) {
9842 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9843 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +00009844 return ExprError();
John McCall31996342011-04-07 08:22:57 +00009845 }
9846
Richard Trieu10162ab2011-09-09 03:59:41 +00009847 ExprResult VisitCallExpr(CallExpr *E);
9848 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +00009849
John McCall39439732011-04-09 22:50:59 +00009850 /// Rebuild an expression which simply semantically wraps another
9851 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +00009852 template <class T> ExprResult rebuildSugarExpr(T *E) {
9853 ExprResult SubResult = Visit(E->getSubExpr());
9854 if (SubResult.isInvalid()) return ExprError();
9855 Expr *SubExpr = SubResult.take();
9856 E->setSubExpr(SubExpr);
9857 E->setType(SubExpr->getType());
9858 E->setValueKind(SubExpr->getValueKind());
9859 assert(E->getObjectKind() == OK_Ordinary);
9860 return E;
John McCall39439732011-04-09 22:50:59 +00009861 }
John McCall31996342011-04-07 08:22:57 +00009862
Richard Trieu10162ab2011-09-09 03:59:41 +00009863 ExprResult VisitParenExpr(ParenExpr *E) {
9864 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +00009865 }
9866
Richard Trieu10162ab2011-09-09 03:59:41 +00009867 ExprResult VisitUnaryExtension(UnaryOperator *E) {
9868 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +00009869 }
9870
Richard Trieu10162ab2011-09-09 03:59:41 +00009871 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9872 const PointerType *Ptr = DestType->getAs<PointerType>();
9873 if (!Ptr) {
9874 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
9875 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +00009876 return ExprError();
9877 }
Richard Trieu10162ab2011-09-09 03:59:41 +00009878 assert(E->getValueKind() == VK_RValue);
9879 assert(E->getObjectKind() == OK_Ordinary);
9880 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +00009881
9882 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +00009883 DestType = Ptr->getPointeeType();
9884 ExprResult SubResult = Visit(E->getSubExpr());
9885 if (SubResult.isInvalid()) return ExprError();
9886 E->setSubExpr(SubResult.take());
9887 return E;
John McCall2979fe02011-04-12 00:42:48 +00009888 }
9889
Richard Trieu10162ab2011-09-09 03:59:41 +00009890 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +00009891
Richard Trieu10162ab2011-09-09 03:59:41 +00009892 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +00009893
Richard Trieu10162ab2011-09-09 03:59:41 +00009894 ExprResult VisitMemberExpr(MemberExpr *E) {
9895 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +00009896 }
John McCall39439732011-04-09 22:50:59 +00009897
Richard Trieu10162ab2011-09-09 03:59:41 +00009898 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9899 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +00009900 }
9901 };
9902}
9903
John McCall2d2e8702011-04-11 07:02:50 +00009904/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +00009905ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
9906 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +00009907
9908 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +00009909 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +00009910 FK_FunctionPointer,
9911 FK_BlockPointer
9912 };
9913
Richard Trieu10162ab2011-09-09 03:59:41 +00009914 FnKind Kind;
9915 QualType CalleeType = CalleeExpr->getType();
9916 if (CalleeType == S.Context.BoundMemberTy) {
9917 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
9918 Kind = FK_MemberFunction;
9919 CalleeType = Expr::findBoundMemberType(CalleeExpr);
9920 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
9921 CalleeType = Ptr->getPointeeType();
9922 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +00009923 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +00009924 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
9925 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +00009926 }
Richard Trieu10162ab2011-09-09 03:59:41 +00009927 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +00009928
9929 // Verify that this is a legal result type of a function.
9930 if (DestType->isArrayType() || DestType->isFunctionType()) {
9931 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +00009932 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +00009933 diagID = diag::err_block_returning_array_function;
9934
Richard Trieu10162ab2011-09-09 03:59:41 +00009935 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +00009936 << DestType->isFunctionType() << DestType;
9937 return ExprError();
9938 }
9939
9940 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +00009941 E->setType(DestType.getNonLValueExprType(S.Context));
9942 E->setValueKind(Expr::getValueKindForType(DestType));
9943 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +00009944
9945 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu10162ab2011-09-09 03:59:41 +00009946 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall2d2e8702011-04-11 07:02:50 +00009947 DestType = S.Context.getFunctionType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +00009948 Proto->arg_type_begin(),
9949 Proto->getNumArgs(),
9950 Proto->getExtProtoInfo());
John McCall2d2e8702011-04-11 07:02:50 +00009951 else
9952 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +00009953 FnType->getExtInfo());
John McCall2d2e8702011-04-11 07:02:50 +00009954
9955 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +00009956 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +00009957 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +00009958 // Nothing to do.
9959 break;
9960
9961 case FK_FunctionPointer:
9962 DestType = S.Context.getPointerType(DestType);
9963 break;
9964
9965 case FK_BlockPointer:
9966 DestType = S.Context.getBlockPointerType(DestType);
9967 break;
9968 }
9969
9970 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +00009971 ExprResult CalleeResult = Visit(CalleeExpr);
9972 if (!CalleeResult.isUsable()) return ExprError();
9973 E->setCallee(CalleeResult.take());
John McCall2d2e8702011-04-11 07:02:50 +00009974
9975 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +00009976 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +00009977}
9978
Richard Trieu10162ab2011-09-09 03:59:41 +00009979ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +00009980 // Verify that this is a legal result type of a call.
9981 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +00009982 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +00009983 << DestType->isFunctionType() << DestType;
9984 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +00009985 }
9986
John McCall3f4138c2011-07-13 17:56:40 +00009987 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +00009988 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
9989 assert(Method->getResultType() == S.Context.UnknownAnyTy);
9990 Method->setResultType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +00009991 }
John McCall2979fe02011-04-12 00:42:48 +00009992
John McCall2d2e8702011-04-11 07:02:50 +00009993 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +00009994 E->setType(DestType.getNonReferenceType());
9995 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +00009996
Richard Trieu10162ab2011-09-09 03:59:41 +00009997 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +00009998}
9999
Richard Trieu10162ab2011-09-09 03:59:41 +000010000ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000010001 // The only case we should ever see here is a function-to-pointer decay.
Richard Trieu10162ab2011-09-09 03:59:41 +000010002 assert(E->getCastKind() == CK_FunctionToPointerDecay);
10003 assert(E->getValueKind() == VK_RValue);
10004 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000010005
Richard Trieu10162ab2011-09-09 03:59:41 +000010006 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +000010007
John McCall2d2e8702011-04-11 07:02:50 +000010008 // Rebuild the sub-expression as the pointee (function) type.
10009 DestType = DestType->castAs<PointerType>()->getPointeeType();
10010
Richard Trieu10162ab2011-09-09 03:59:41 +000010011 ExprResult Result = Visit(E->getSubExpr());
10012 if (!Result.isUsable()) return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010013
Richard Trieu10162ab2011-09-09 03:59:41 +000010014 E->setSubExpr(Result.take());
10015 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000010016}
10017
Richard Trieu10162ab2011-09-09 03:59:41 +000010018ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
10019 ExprValueKind ValueKind = VK_LValue;
10020 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +000010021
10022 // We know how to make this work for certain kinds of decls:
10023
10024 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +000010025 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
10026 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
10027 DestType = Ptr->getPointeeType();
10028 ExprResult Result = resolveDecl(E, VD);
10029 if (Result.isInvalid()) return ExprError();
10030 return S.ImpCastExprToType(Result.take(), Type,
John McCall9a877fe2011-08-10 04:12:23 +000010031 CK_FunctionToPointerDecay, VK_RValue);
10032 }
10033
Richard Trieu10162ab2011-09-09 03:59:41 +000010034 if (!Type->isFunctionType()) {
10035 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
10036 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000010037 return ExprError();
10038 }
John McCall2d2e8702011-04-11 07:02:50 +000010039
Richard Trieu10162ab2011-09-09 03:59:41 +000010040 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
10041 if (MD->isInstance()) {
10042 ValueKind = VK_RValue;
10043 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000010044 }
10045
John McCall2d2e8702011-04-11 07:02:50 +000010046 // Function references aren't l-values in C.
10047 if (!S.getLangOptions().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000010048 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000010049
10050 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000010051 } else if (isa<VarDecl>(VD)) {
10052 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
10053 Type = RefTy->getPointeeType();
10054 } else if (Type->isFunctionType()) {
10055 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
10056 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000010057 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010058 }
10059
10060 // - nothing else
10061 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000010062 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10063 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000010064 return ExprError();
10065 }
10066
Richard Trieu10162ab2011-09-09 03:59:41 +000010067 VD->setType(DestType);
10068 E->setType(Type);
10069 E->setValueKind(ValueKind);
10070 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000010071}
10072
John McCall31996342011-04-07 08:22:57 +000010073/// Check a cast of an unknown-any type. We intentionally only
10074/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000010075ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
10076 Expr *CastExpr, CastKind &CastKind,
10077 ExprValueKind &VK, CXXCastPath &Path) {
John McCall31996342011-04-07 08:22:57 +000010078 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000010079 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000010080 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000010081
Richard Trieuba63ce62011-09-09 01:45:06 +000010082 CastExpr = result.take();
10083 VK = CastExpr->getValueKind();
10084 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000010085
Richard Trieuba63ce62011-09-09 01:45:06 +000010086 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000010087}
10088
Richard Trieuba63ce62011-09-09 01:45:06 +000010089static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
10090 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000010091 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000010092 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000010093 E = E->IgnoreParenImpCasts();
10094 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
10095 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000010096 diagID = diag::err_uncasted_call_of_unknown_any;
10097 } else {
John McCall31996342011-04-07 08:22:57 +000010098 break;
John McCall2d2e8702011-04-11 07:02:50 +000010099 }
John McCall31996342011-04-07 08:22:57 +000010100 }
10101
John McCall2d2e8702011-04-11 07:02:50 +000010102 SourceLocation loc;
10103 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000010104 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010105 loc = ref->getLocation();
10106 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000010107 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010108 loc = mem->getMemberLoc();
10109 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000010110 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010111 diagID = diag::err_uncasted_call_of_unknown_any;
10112 loc = msg->getSelectorLoc();
10113 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000010114 if (!d) {
10115 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
10116 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
10117 << orig->getSourceRange();
10118 return ExprError();
10119 }
John McCall2d2e8702011-04-11 07:02:50 +000010120 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000010121 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10122 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000010123 return ExprError();
10124 }
10125
10126 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000010127
10128 // Never recoverable.
10129 return ExprError();
10130}
10131
John McCall36e7fe32010-10-12 00:20:44 +000010132/// Check for operands with placeholder types and complain if found.
10133/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000010134ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +000010135 // Placeholder types are always *exactly* the appropriate builtin type.
10136 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +000010137
John McCall31996342011-04-07 08:22:57 +000010138 // Overloaded expressions.
10139 if (type == Context.OverloadTy)
10140 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010141 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +000010142 QualType(),
10143 diag::err_ovl_unresolvable);
10144
John McCall0009fcc2011-04-26 20:42:42 +000010145 // Bound member functions.
10146 if (type == Context.BoundMemberTy) {
10147 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
10148 << E->getSourceRange();
10149 return ExprError();
10150 }
10151
John McCall31996342011-04-07 08:22:57 +000010152 // Expressions of unknown type.
10153 if (type == Context.UnknownAnyTy)
10154 return diagnoseUnknownAnyExpr(*this, E);
10155
10156 assert(!type->isPlaceholderType());
10157 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +000010158}
Richard Trieu2c850c02011-04-21 21:44:26 +000010159
Richard Trieuba63ce62011-09-09 01:45:06 +000010160bool Sema::CheckCaseExpression(Expr *E) {
10161 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000010162 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000010163 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
10164 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000010165 return false;
10166}