blob: f0ecb5800c0598d3b40019670d6ac7da99dc6ea7 [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"
John McCallde6836a2010-08-24 07:21:54 +000039#include "clang/Sema/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000040using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000041using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000042
David Chisnall9f57c292009-08-17 16:35:33 +000043
Douglas Gregor171c45a2009-02-18 21:56:37 +000044/// \brief Determine whether the use of this declaration is valid, and
45/// emit any corresponding diagnostics.
46///
47/// This routine diagnoses various problems with referencing
48/// declarations that can occur when using a declaration. For example,
49/// it might warn if a deprecated or unavailable declaration is being
50/// used, or produce an error (and return true) if a C++0x deleted
51/// function is being used.
52///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000053/// If IgnoreDeprecated is set to true, this should not warn about deprecated
Chris Lattnerb7df3c62009-10-25 22:31:57 +000054/// decls.
55///
Douglas Gregor171c45a2009-02-18 21:56:37 +000056/// \returns true if there was an error (this declaration cannot be
57/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000058///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +000059bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahaniandbbdd2f2011-04-23 17:27:19 +000060 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000061 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
62 // If there were any diagnostics suppressed by template argument deduction,
63 // emit them now.
64 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
65 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
66 if (Pos != SuppressedDiagnostics.end()) {
67 llvm::SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
68 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
69 Diag(Suppressed[I].first, Suppressed[I].second);
70
71 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000072 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +000073 // entry from the table, because we want to avoid ever emitting these
74 // diagnostics again.
75 Suppressed.clear();
76 }
77 }
78
Richard Smith30482bc2011-02-20 03:19:35 +000079 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +000080 if (ParsingInitForAutoVars.count(D)) {
81 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
82 << D->getDeclName();
83 return true;
Richard Smith30482bc2011-02-20 03:19:35 +000084 }
85
Douglas Gregor171c45a2009-02-18 21:56:37 +000086 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000087 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000088 if (FD->isDeleted()) {
89 Diag(Loc, diag::err_deleted_function_use);
John McCall31168b02011-06-15 23:02:42 +000090 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
Douglas Gregor171c45a2009-02-18 21:56:37 +000091 return true;
92 }
Douglas Gregorde681d42009-02-24 04:26:15 +000093 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000094
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000095 // See if this declaration is unavailable or deprecated.
96 std::string Message;
97 switch (D->getAvailability(&Message)) {
98 case AR_Available:
99 case AR_NotYetIntroduced:
100 break;
101
102 case AR_Deprecated:
103 EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
104 break;
105
106 case AR_Unavailable:
107 if (Message.empty()) {
108 if (!UnknownObjCClass)
109 Diag(Loc, diag::err_unavailable) << D->getDeclName();
110 else
111 Diag(Loc, diag::warn_unavailable_fwdclass_message)
112 << D->getDeclName();
113 }
114 else
115 Diag(Loc, diag::err_unavailable_message)
116 << D->getDeclName() << Message;
John McCall31168b02011-06-15 23:02:42 +0000117 Diag(D->getLocation(), diag::note_unavailable_here)
118 << isa<FunctionDecl>(D) << false;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000119 break;
120 }
121
Anders Carlsson73067a02010-10-22 23:37:08 +0000122 // Warn if this is used but marked unused.
123 if (D->hasAttr<UnusedAttr>())
124 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
125
Douglas Gregor171c45a2009-02-18 21:56:37 +0000126 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000127}
128
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000129/// \brief Retrieve the message suffix that should be added to a
130/// diagnostic complaining about the given function being deleted or
131/// unavailable.
132std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
133 // FIXME: C++0x implicitly-deleted special member functions could be
134 // detected here so that we could improve diagnostics to say, e.g.,
135 // "base class 'A' had a deleted copy constructor".
136 if (FD->isDeleted())
137 return std::string();
138
139 std::string Message;
140 if (FD->getAvailability(&Message))
141 return ": " + Message;
142
143 return std::string();
144}
145
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000146/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +0000147/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000148/// attribute. It warns if call does not have the sentinel argument.
149///
150void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000151 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000152 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000153 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000154 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000155
156 // FIXME: In C++0x, if any of the arguments are parameter pack
157 // expansions, we can't check for the sentinel now.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000158 int sentinelPos = attr->getSentinel();
159 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +0000160
Mike Stump87c57ac2009-05-16 07:39:55 +0000161 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
162 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000163 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000164 bool warnNotEnoughArgs = false;
165 int isMethod = 0;
166 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
167 // skip over named parameters.
168 ObjCMethodDecl::param_iterator P, E = MD->param_end();
169 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
170 if (nullPos)
171 --nullPos;
172 else
173 ++i;
174 }
175 warnNotEnoughArgs = (P != E || i >= NumArgs);
176 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000177 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000178 // skip over named parameters.
179 ObjCMethodDecl::param_iterator P, E = FD->param_end();
180 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
181 if (nullPos)
182 --nullPos;
183 else
184 ++i;
185 }
186 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000187 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000188 // block or function pointer call.
189 QualType Ty = V->getType();
190 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000191 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000192 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
193 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000194 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
195 unsigned NumArgsInProto = Proto->getNumArgs();
196 unsigned k;
197 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
198 if (nullPos)
199 --nullPos;
200 else
201 ++i;
202 }
203 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
204 }
205 if (Ty->isBlockPointerType())
206 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000207 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000208 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000209 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000210 return;
211
212 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000213 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000214 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000215 return;
216 }
217 int sentinel = i;
218 while (sentinelPos > 0 && i < NumArgs-1) {
219 --sentinelPos;
220 ++i;
221 }
222 if (sentinelPos > 0) {
223 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000224 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000225 return;
226 }
227 while (i < NumArgs-1) {
228 ++i;
229 ++sentinel;
230 }
231 Expr *sentinelExpr = Args[sentinel];
John McCall7ddbcf42010-05-06 23:53:00 +0000232 if (!sentinelExpr) return;
233 if (sentinelExpr->isTypeDependent()) return;
234 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000235
236 // nullptr_t is always treated as null.
237 if (sentinelExpr->getType()->isNullPtrType()) return;
238
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000239 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000240 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
241 Expr::NPC_ValueDependentIsNull))
242 return;
243
244 // Unfortunately, __null has type 'int'.
245 if (isa<GNUNullExpr>(sentinelExpr)) return;
246
247 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
248 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000249}
250
Douglas Gregor87f95b02009-02-26 21:00:50 +0000251SourceRange Sema::getExprRange(ExprTy *E) const {
252 Expr *Ex = (Expr *)E;
253 return Ex? Ex->getSourceRange() : SourceRange();
254}
255
Chris Lattner513165e2008-07-25 21:10:04 +0000256//===----------------------------------------------------------------------===//
257// Standard Promotions and Conversions
258//===----------------------------------------------------------------------===//
259
Chris Lattner513165e2008-07-25 21:10:04 +0000260/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000261ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattner513165e2008-07-25 21:10:04 +0000262 QualType Ty = E->getType();
263 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
264
Chris Lattner513165e2008-07-25 21:10:04 +0000265 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000266 E = ImpCastExprToType(E, Context.getPointerType(Ty),
267 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000268 else if (Ty->isArrayType()) {
269 // In C90 mode, arrays only promote to pointers if the array expression is
270 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
271 // type 'array of type' is converted to an expression that has type 'pointer
272 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
273 // that has type 'array of type' ...". The relevant change is "an lvalue"
274 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000275 //
276 // C++ 4.2p1:
277 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
278 // T" can be converted to an rvalue of type "pointer to T".
279 //
John McCall086a4642010-11-24 05:12:34 +0000280 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000281 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
282 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000283 }
John Wiegley01296292011-04-08 18:41:53 +0000284 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000285}
286
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000287static void CheckForNullPointerDereference(Sema &S, Expr *E) {
288 // Check to see if we are dereferencing a null pointer. If so,
289 // and if not volatile-qualified, this is undefined behavior that the
290 // optimizer will delete, so warn about it. People sometimes try to use this
291 // to get a deterministic trap and are surprised by clang's behavior. This
292 // only handles the pattern "*null", which is a very syntactic check.
293 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
294 if (UO->getOpcode() == UO_Deref &&
295 UO->getSubExpr()->IgnoreParenCasts()->
296 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
297 !UO->getType().isVolatileQualified()) {
298 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
299 S.PDiag(diag::warn_indirection_through_null)
300 << UO->getSubExpr()->getSourceRange());
301 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
302 S.PDiag(diag::note_indirection_through_null));
303 }
304}
305
John Wiegley01296292011-04-08 18:41:53 +0000306ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000307 // C++ [conv.lval]p1:
308 // A glvalue of a non-function, non-array type T can be
309 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000310 if (!E->isGLValue()) return Owned(E);
John McCall34376a62010-12-04 03:47:34 +0000311
John McCall27584242010-12-06 20:48:59 +0000312 QualType T = E->getType();
313 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000314
John McCall27584242010-12-06 20:48:59 +0000315 // Create a load out of an ObjCProperty l-value, if necessary.
316 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +0000317 ExprResult Res = ConvertPropertyForRValue(E);
318 if (Res.isInvalid())
319 return Owned(E);
320 E = Res.take();
John McCall27584242010-12-06 20:48:59 +0000321 if (!E->isGLValue())
John Wiegley01296292011-04-08 18:41:53 +0000322 return Owned(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000323 }
John McCall27584242010-12-06 20:48:59 +0000324
325 // We don't want to throw lvalue-to-rvalue casts on top of
326 // expressions of certain types in C++.
327 if (getLangOptions().CPlusPlus &&
328 (E->getType() == Context.OverloadTy ||
329 T->isDependentType() ||
330 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000331 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000332
333 // The C standard is actually really unclear on this point, and
334 // DR106 tells us what the result should be but not why. It's
335 // generally best to say that void types just doesn't undergo
336 // lvalue-to-rvalue at all. Note that expressions of unqualified
337 // 'void' type are never l-values, but qualified void can be.
338 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000339 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000340
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000341 CheckForNullPointerDereference(*this, E);
342
John McCall27584242010-12-06 20:48:59 +0000343 // C++ [conv.lval]p1:
344 // [...] If T is a non-class type, the type of the prvalue is the
345 // cv-unqualified version of T. Otherwise, the type of the
346 // rvalue is T.
347 //
348 // C99 6.3.2.1p2:
349 // If the lvalue has qualified type, the value has the unqualified
350 // version of the type of the lvalue; otherwise, the value has the
351 // type of the lvalue.
352 if (T.hasQualifiers())
353 T = T.getUnqualifiedType();
354
Ted Kremenekdf26df72011-03-01 18:41:00 +0000355 CheckArrayAccess(E);
Ted Kremenek64699be2011-02-16 01:57:07 +0000356
John Wiegley01296292011-04-08 18:41:53 +0000357 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
358 E, 0, VK_RValue));
John McCall27584242010-12-06 20:48:59 +0000359}
360
John Wiegley01296292011-04-08 18:41:53 +0000361ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
362 ExprResult Res = DefaultFunctionArrayConversion(E);
363 if (Res.isInvalid())
364 return ExprError();
365 Res = DefaultLvalueConversion(Res.take());
366 if (Res.isInvalid())
367 return ExprError();
368 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000369}
370
371
Chris Lattner513165e2008-07-25 21:10:04 +0000372/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000373/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000374/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000375/// apply if the array is an argument to the sizeof or address (&) operators.
376/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000377ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000378 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000379 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
380 if (Res.isInvalid())
381 return Owned(E);
382 E = Res.take();
John McCallf3735e02010-12-01 04:43:34 +0000383
384 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000385 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000386
387 // Try to perform integral promotions if the object has a theoretically
388 // promotable type.
389 if (Ty->isIntegralOrUnscopedEnumerationType()) {
390 // C99 6.3.1.1p2:
391 //
392 // The following may be used in an expression wherever an int or
393 // unsigned int may be used:
394 // - an object or expression with an integer type whose integer
395 // conversion rank is less than or equal to the rank of int
396 // and unsigned int.
397 // - A bit-field of type _Bool, int, signed int, or unsigned int.
398 //
399 // If an int can represent all values of the original type, the
400 // value is converted to an int; otherwise, it is converted to an
401 // unsigned int. These are called the integer promotions. All
402 // other types are unchanged by the integer promotions.
403
404 QualType PTy = Context.isPromotableBitField(E);
405 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000406 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
407 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000408 }
409 if (Ty->isPromotableIntegerType()) {
410 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000411 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
412 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000413 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000414 }
John Wiegley01296292011-04-08 18:41:53 +0000415 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000416}
417
Chris Lattner2ce500f2008-07-25 22:25:12 +0000418/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000419/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000420/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000421ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
422 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000423 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000424
John Wiegley01296292011-04-08 18:41:53 +0000425 ExprResult Res = UsualUnaryConversions(E);
426 if (Res.isInvalid())
427 return Owned(E);
428 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000429
Chris Lattner2ce500f2008-07-25 22:25:12 +0000430 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000431 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000432 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
433
434 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000435}
436
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000437/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
438/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000439/// interfaces passed by value.
440ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000441 FunctionDecl *FDecl) {
John Wiegley01296292011-04-08 18:41:53 +0000442 ExprResult ExprRes = DefaultArgumentPromotion(E);
443 if (ExprRes.isInvalid())
444 return ExprError();
445 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000446
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000447 // __builtin_va_start takes the second argument as a "varargs" argument, but
448 // it doesn't actually do anything with it. It doesn't need to be non-pod
449 // etc.
450 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
John Wiegley01296292011-04-08 18:41:53 +0000451 return Owned(E);
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000452
Douglas Gregor347e0f22011-05-21 19:26:31 +0000453 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000454 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000455 DiagRuntimeBehavior(E->getLocStart(), 0,
456 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
457 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000458 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000459
John McCall31168b02011-06-15 23:02:42 +0000460 if (!E->getType().isPODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000461 // C++0x [expr.call]p7:
462 // Passing a potentially-evaluated argument of class type (Clause 9)
463 // having a non-trivial copy constructor, a non-trivial move constructor,
464 // or a non-trivial destructor, with no corresponding parameter,
465 // is conditionally-supported with implementation-defined semantics.
466 bool TrivialEnough = false;
467 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
468 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
469 if (Record->hasTrivialCopyConstructor() &&
470 Record->hasTrivialMoveConstructor() &&
471 Record->hasTrivialDestructor())
472 TrivialEnough = true;
473 }
474 }
John McCall31168b02011-06-15 23:02:42 +0000475
476 if (!TrivialEnough &&
477 getLangOptions().ObjCAutoRefCount &&
478 E->getType()->isObjCLifetimeType())
479 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000480
481 if (TrivialEnough) {
482 // Nothing to diagnose. This is okay.
483 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000484 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor253cadf2011-05-21 16:27:21 +0000485 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000486 << CT)) {
487 // Turn this into a trap.
488 CXXScopeSpec SS;
489 UnqualifiedId Name;
490 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
491 E->getLocStart());
492 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
493 if (TrapFn.isInvalid())
494 return ExprError();
495
496 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
497 MultiExprArg(), E->getLocEnd());
498 if (Call.isInvalid())
499 return ExprError();
500
501 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
502 Call.get(), E);
503 if (Comma.isInvalid())
504 return ExprError();
505
506 E = Comma.get();
507 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000508 }
509
John Wiegley01296292011-04-08 18:41:53 +0000510 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000511}
512
Chris Lattner513165e2008-07-25 21:10:04 +0000513/// UsualArithmeticConversions - Performs various conversions that are common to
514/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000515/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000516/// responsible for emitting appropriate error diagnostics.
517/// FIXME: verify the conversion rules for "complex int" are consistent with
518/// GCC.
John Wiegley01296292011-04-08 18:41:53 +0000519QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr, ExprResult &rhsExpr,
Chris Lattner513165e2008-07-25 21:10:04 +0000520 bool isCompAssign) {
John Wiegley01296292011-04-08 18:41:53 +0000521 if (!isCompAssign) {
522 lhsExpr = UsualUnaryConversions(lhsExpr.take());
523 if (lhsExpr.isInvalid())
524 return QualType();
525 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000526
John Wiegley01296292011-04-08 18:41:53 +0000527 rhsExpr = UsualUnaryConversions(rhsExpr.take());
528 if (rhsExpr.isInvalid())
529 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000530
Mike Stump11289f42009-09-09 15:08:12 +0000531 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000532 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000533 QualType lhs =
John Wiegley01296292011-04-08 18:41:53 +0000534 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000535 QualType rhs =
John Wiegley01296292011-04-08 18:41:53 +0000536 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000537
538 // If both types are identical, no conversion is needed.
539 if (lhs == rhs)
540 return lhs;
541
542 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
543 // The caller can deal with this (e.g. pointer + int).
544 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
545 return lhs;
546
John McCalld005ac92010-11-13 08:17:45 +0000547 // Apply unary and bitfield promotions to the LHS's type.
548 QualType lhs_unpromoted = lhs;
549 if (lhs->isPromotableIntegerType())
550 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley01296292011-04-08 18:41:53 +0000551 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000552 if (!LHSBitfieldPromoteTy.isNull())
553 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000554 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000555 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000556
John McCalld005ac92010-11-13 08:17:45 +0000557 // If both types are identical, no conversion is needed.
558 if (lhs == rhs)
559 return lhs;
560
561 // At this point, we have two different arithmetic types.
562
563 // Handle complex types first (C99 6.3.1.8p1).
564 bool LHSComplexFloat = lhs->isComplexType();
565 bool RHSComplexFloat = rhs->isComplexType();
566 if (LHSComplexFloat || RHSComplexFloat) {
567 // if we have an integer operand, the result is the complex type.
568
John McCallc5e62b42010-11-13 09:02:35 +0000569 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
570 if (rhs->isIntegerType()) {
571 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000572 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
573 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000574 } else {
575 assert(rhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000576 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000577 }
John McCalld005ac92010-11-13 08:17:45 +0000578 return lhs;
579 }
580
John McCallc5e62b42010-11-13 09:02:35 +0000581 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
582 if (!isCompAssign) {
583 // int -> float -> _Complex float
584 if (lhs->isIntegerType()) {
585 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000586 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_IntegralToFloating);
587 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000588 } else {
589 assert(lhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000590 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000591 }
592 }
John McCalld005ac92010-11-13 08:17:45 +0000593 return rhs;
594 }
595
596 // This handles complex/complex, complex/float, or float/complex.
597 // When both operands are complex, the shorter operand is converted to the
598 // type of the longer, and that is the type of the result. This corresponds
599 // to what is done when combining two real floating-point operands.
600 // The fun begins when size promotion occur across type domains.
601 // From H&S 6.3.4: When one operand is complex and the other is a real
602 // floating-point type, the less precise type is converted, within it's
603 // real or complex domain, to the precision of the other type. For example,
604 // when combining a "long double" with a "double _Complex", the
605 // "double _Complex" is promoted to "long double _Complex".
606 int order = Context.getFloatingTypeOrder(lhs, rhs);
607
608 // If both are complex, just cast to the more precise type.
609 if (LHSComplexFloat && RHSComplexFloat) {
610 if (order > 0) {
611 // _Complex float -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000612 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000613 return lhs;
614
615 } else if (order < 0) {
616 // _Complex float -> _Complex double
617 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000618 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000619 return rhs;
620 }
621 return lhs;
622 }
623
624 // If just the LHS is complex, the RHS needs to be converted,
625 // and the LHS might need to be promoted.
626 if (LHSComplexFloat) {
627 if (order > 0) { // LHS is wider
628 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000629 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000630 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
631 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000632 return lhs;
633 }
634
635 // RHS is at least as wide. Find its corresponding complex type.
636 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
637
638 // double -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000639 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000640
641 // _Complex float -> _Complex double
642 if (!isCompAssign && order < 0)
John Wiegley01296292011-04-08 18:41:53 +0000643 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000644
645 return result;
646 }
647
648 // Just the RHS is complex, so the LHS needs to be converted
649 // and the RHS might need to be promoted.
650 assert(RHSComplexFloat);
651
652 if (order < 0) { // RHS is wider
653 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000654 if (!isCompAssign) {
Argyrios Kyrtzidise84389b2011-01-18 18:49:33 +0000655 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000656 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
657 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000658 }
John McCalld005ac92010-11-13 08:17:45 +0000659 return rhs;
660 }
661
662 // LHS is at least as wide. Find its corresponding complex type.
663 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
664
665 // double -> _Complex double
666 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000667 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000668
669 // _Complex float -> _Complex double
670 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +0000671 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000672
673 return result;
674 }
675
676 // Now handle "real" floating types (i.e. float, double, long double).
677 bool LHSFloat = lhs->isRealFloatingType();
678 bool RHSFloat = rhs->isRealFloatingType();
679 if (LHSFloat || RHSFloat) {
680 // If we have two real floating types, convert the smaller operand
681 // to the bigger result.
682 if (LHSFloat && RHSFloat) {
683 int order = Context.getFloatingTypeOrder(lhs, rhs);
684 if (order > 0) {
John Wiegley01296292011-04-08 18:41:53 +0000685 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000686 return lhs;
687 }
688
689 assert(order < 0 && "illegal float comparison");
690 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000691 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000692 return rhs;
693 }
694
695 // If we have an integer operand, the result is the real floating type.
696 if (LHSFloat) {
697 if (rhs->isIntegerType()) {
698 // Convert rhs to the lhs floating point type.
John Wiegley01296292011-04-08 18:41:53 +0000699 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000700 return lhs;
701 }
702
703 // Convert both sides to the appropriate complex float.
704 assert(rhs->isComplexIntegerType());
705 QualType result = Context.getComplexType(lhs);
706
707 // _Complex int -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000708 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000709
710 // float -> _Complex float
711 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000712 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000713
714 return result;
715 }
716
717 assert(RHSFloat);
718 if (lhs->isIntegerType()) {
719 // Convert lhs to the rhs floating point type.
720 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000721 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000722 return rhs;
723 }
724
725 // Convert both sides to the appropriate complex float.
726 assert(lhs->isComplexIntegerType());
727 QualType result = Context.getComplexType(rhs);
728
729 // _Complex int -> _Complex float
730 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000731 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000732
733 // float -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000734 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000735
736 return result;
737 }
738
739 // Handle GCC complex int extension.
740 // FIXME: if the operands are (int, _Complex long), we currently
741 // don't promote the complex. Also, signedness?
742 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
743 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
744 if (lhsComplexInt && rhsComplexInt) {
745 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
746 rhsComplexInt->getElementType());
747 assert(order && "inequal types with equal element ordering");
748 if (order > 0) {
749 // _Complex int -> _Complex long
John Wiegley01296292011-04-08 18:41:53 +0000750 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000751 return lhs;
752 }
753
754 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000755 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000756 return rhs;
757 } else if (lhsComplexInt) {
758 // int -> _Complex int
John Wiegley01296292011-04-08 18:41:53 +0000759 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000760 return lhs;
761 } else if (rhsComplexInt) {
762 // int -> _Complex int
763 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000764 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000765 return rhs;
766 }
767
768 // Finally, we have two differing integer types.
769 // The rules for this case are in C99 6.3.1.8
770 int compare = Context.getIntegerTypeOrder(lhs, rhs);
771 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
772 rhsSigned = rhs->hasSignedIntegerRepresentation();
773 if (lhsSigned == rhsSigned) {
774 // Same signedness; use the higher-ranked type
775 if (compare >= 0) {
John Wiegley01296292011-04-08 18:41:53 +0000776 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000777 return lhs;
778 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000779 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000780 return rhs;
781 } else if (compare != (lhsSigned ? 1 : -1)) {
782 // The unsigned type has greater than or equal rank to the
783 // signed type, so use the unsigned type
784 if (rhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000785 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000786 return lhs;
787 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000788 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000789 return rhs;
790 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
791 // The two types are different widths; if we are here, that
792 // means the signed type is larger than the unsigned type, so
793 // use the signed type.
794 if (lhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000795 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000796 return lhs;
797 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000798 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000799 return rhs;
800 } else {
801 // The signed type is higher-ranked than the unsigned type,
802 // but isn't actually any bigger (like unsigned int and long
803 // on most 32-bit systems). Use the unsigned type corresponding
804 // to the signed type.
805 QualType result =
806 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley01296292011-04-08 18:41:53 +0000807 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000808 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000809 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000810 return result;
811 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000812}
813
Chris Lattner513165e2008-07-25 21:10:04 +0000814//===----------------------------------------------------------------------===//
815// Semantic Analysis for various Expression Types
816//===----------------------------------------------------------------------===//
817
818
Peter Collingbourne91147592011-04-15 00:35:48 +0000819ExprResult
820Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
821 SourceLocation DefaultLoc,
822 SourceLocation RParenLoc,
823 Expr *ControllingExpr,
824 MultiTypeArg types,
825 MultiExprArg exprs) {
826 unsigned NumAssocs = types.size();
827 assert(NumAssocs == exprs.size());
828
829 ParsedType *ParsedTypes = types.release();
830 Expr **Exprs = exprs.release();
831
832 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
833 for (unsigned i = 0; i < NumAssocs; ++i) {
834 if (ParsedTypes[i])
835 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
836 else
837 Types[i] = 0;
838 }
839
840 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
841 ControllingExpr, Types, Exprs,
842 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000843 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000844 return ER;
845}
846
847ExprResult
848Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
849 SourceLocation DefaultLoc,
850 SourceLocation RParenLoc,
851 Expr *ControllingExpr,
852 TypeSourceInfo **Types,
853 Expr **Exprs,
854 unsigned NumAssocs) {
855 bool TypeErrorFound = false,
856 IsResultDependent = ControllingExpr->isTypeDependent(),
857 ContainsUnexpandedParameterPack
858 = ControllingExpr->containsUnexpandedParameterPack();
859
860 for (unsigned i = 0; i < NumAssocs; ++i) {
861 if (Exprs[i]->containsUnexpandedParameterPack())
862 ContainsUnexpandedParameterPack = true;
863
864 if (Types[i]) {
865 if (Types[i]->getType()->containsUnexpandedParameterPack())
866 ContainsUnexpandedParameterPack = true;
867
868 if (Types[i]->getType()->isDependentType()) {
869 IsResultDependent = true;
870 } else {
871 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
872 // complete object type other than a variably modified type."
873 unsigned D = 0;
874 if (Types[i]->getType()->isIncompleteType())
875 D = diag::err_assoc_type_incomplete;
876 else if (!Types[i]->getType()->isObjectType())
877 D = diag::err_assoc_type_nonobject;
878 else if (Types[i]->getType()->isVariablyModifiedType())
879 D = diag::err_assoc_type_variably_modified;
880
881 if (D != 0) {
882 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
883 << Types[i]->getTypeLoc().getSourceRange()
884 << Types[i]->getType();
885 TypeErrorFound = true;
886 }
887
888 // C1X 6.5.1.1p2 "No two generic associations in the same generic
889 // selection shall specify compatible types."
890 for (unsigned j = i+1; j < NumAssocs; ++j)
891 if (Types[j] && !Types[j]->getType()->isDependentType() &&
892 Context.typesAreCompatible(Types[i]->getType(),
893 Types[j]->getType())) {
894 Diag(Types[j]->getTypeLoc().getBeginLoc(),
895 diag::err_assoc_compatible_types)
896 << Types[j]->getTypeLoc().getSourceRange()
897 << Types[j]->getType()
898 << Types[i]->getType();
899 Diag(Types[i]->getTypeLoc().getBeginLoc(),
900 diag::note_compat_assoc)
901 << Types[i]->getTypeLoc().getSourceRange()
902 << Types[i]->getType();
903 TypeErrorFound = true;
904 }
905 }
906 }
907 }
908 if (TypeErrorFound)
909 return ExprError();
910
911 // If we determined that the generic selection is result-dependent, don't
912 // try to compute the result expression.
913 if (IsResultDependent)
914 return Owned(new (Context) GenericSelectionExpr(
915 Context, KeyLoc, ControllingExpr,
916 Types, Exprs, NumAssocs, DefaultLoc,
917 RParenLoc, ContainsUnexpandedParameterPack));
918
919 llvm::SmallVector<unsigned, 1> CompatIndices;
920 unsigned DefaultIndex = -1U;
921 for (unsigned i = 0; i < NumAssocs; ++i) {
922 if (!Types[i])
923 DefaultIndex = i;
924 else if (Context.typesAreCompatible(ControllingExpr->getType(),
925 Types[i]->getType()))
926 CompatIndices.push_back(i);
927 }
928
929 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
930 // type compatible with at most one of the types named in its generic
931 // association list."
932 if (CompatIndices.size() > 1) {
933 // We strip parens here because the controlling expression is typically
934 // parenthesized in macro definitions.
935 ControllingExpr = ControllingExpr->IgnoreParens();
936 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
937 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
938 << (unsigned) CompatIndices.size();
939 for (llvm::SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
940 E = CompatIndices.end(); I != E; ++I) {
941 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
942 diag::note_compat_assoc)
943 << Types[*I]->getTypeLoc().getSourceRange()
944 << Types[*I]->getType();
945 }
946 return ExprError();
947 }
948
949 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
950 // its controlling expression shall have type compatible with exactly one of
951 // the types named in its generic association list."
952 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
953 // We strip parens here because the controlling expression is typically
954 // parenthesized in macro definitions.
955 ControllingExpr = ControllingExpr->IgnoreParens();
956 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
957 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
958 return ExprError();
959 }
960
961 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
962 // type name that is compatible with the type of the controlling expression,
963 // then the result expression of the generic selection is the expression
964 // in that generic association. Otherwise, the result expression of the
965 // generic selection is the expression in the default generic association."
966 unsigned ResultIndex =
967 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
968
969 return Owned(new (Context) GenericSelectionExpr(
970 Context, KeyLoc, ControllingExpr,
971 Types, Exprs, NumAssocs, DefaultLoc,
972 RParenLoc, ContainsUnexpandedParameterPack,
973 ResultIndex));
974}
975
Steve Naroff83895f72007-09-16 03:34:24 +0000976/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000977/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
978/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
979/// multiple tokens. However, the common case is that StringToks points to one
980/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000981///
John McCalldadc5752010-08-24 06:29:42 +0000982ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +0000983Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000984 assert(NumStringToks && "Must have at least one string!");
985
Chris Lattner8a24e582009-01-16 18:51:42 +0000986 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000987 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000988 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000989
Chris Lattner23b7eb62007-06-15 23:05:46 +0000990 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000991 for (unsigned i = 0; i != NumStringToks; ++i)
992 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000993
Chris Lattner36fc8792008-02-11 00:02:17 +0000994 QualType StrTy = Context.CharTy;
Anders Carlsson6b06e182011-04-06 18:42:48 +0000995 if (Literal.AnyWide)
996 StrTy = Context.getWCharType();
997 else if (Literal.Pascal)
998 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000999
1000 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +00001001 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001002 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001003
Chris Lattner36fc8792008-02-11 00:02:17 +00001004 // Get an array type for the string, according to C99 6.4.5. This includes
1005 // the nul terminator character as well as the string length for pascal
1006 // strings.
1007 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001008 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001009 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001010
Chris Lattner5b183d82006-11-10 05:03:26 +00001011 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +00001012 return Owned(StringLiteral::Create(Context, Literal.GetString(),
1013 Literal.GetStringLength(),
Anders Carlsson75245402011-04-14 00:40:03 +00001014 Literal.AnyWide, Literal.Pascal, StrTy,
Alexis Hunt3b791862010-08-30 17:47:05 +00001015 &StringTokLocs[0],
1016 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +00001017}
1018
John McCallc63de662011-02-02 13:00:07 +00001019enum CaptureResult {
1020 /// No capture is required.
1021 CR_NoCapture,
1022
1023 /// A capture is required.
1024 CR_Capture,
1025
John McCall351762c2011-02-07 10:33:21 +00001026 /// A by-ref capture is required.
1027 CR_CaptureByRef,
1028
John McCallc63de662011-02-02 13:00:07 +00001029 /// An error occurred when trying to capture the given variable.
1030 CR_Error
1031};
1032
1033/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +00001034///
John McCallc63de662011-02-02 13:00:07 +00001035/// \param var - the variable referenced
1036/// \param DC - the context which we couldn't capture through
1037static CaptureResult
John McCall351762c2011-02-07 10:33:21 +00001038diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001039 VarDecl *var, DeclContext *DC) {
1040 switch (S.ExprEvalContexts.back().Context) {
1041 case Sema::Unevaluated:
1042 // The argument will never be evaluated, so don't complain.
1043 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +00001044
John McCallc63de662011-02-02 13:00:07 +00001045 case Sema::PotentiallyEvaluated:
1046 case Sema::PotentiallyEvaluatedIfUsed:
1047 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +00001048
John McCallc63de662011-02-02 13:00:07 +00001049 case Sema::PotentiallyPotentiallyEvaluated:
1050 // FIXME: delay these!
1051 break;
Chris Lattner497d7b02009-04-21 22:26:47 +00001052 }
Mike Stump11289f42009-09-09 15:08:12 +00001053
John McCallc63de662011-02-02 13:00:07 +00001054 // Don't diagnose about capture if we're not actually in code right
1055 // now; in general, there are more appropriate places that will
1056 // diagnose this.
1057 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1058
John McCall92d627e2011-03-22 23:15:50 +00001059 // Certain madnesses can happen with parameter declarations, which
1060 // we want to ignore.
1061 if (isa<ParmVarDecl>(var)) {
1062 // - If the parameter still belongs to the translation unit, then
1063 // we're actually just using one parameter in the declaration of
1064 // the next. This is useful in e.g. VLAs.
1065 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1066 return CR_NoCapture;
1067
1068 // - This particular madness can happen in ill-formed default
1069 // arguments; claim it's okay and let downstream code handle it.
1070 if (S.CurContext == var->getDeclContext()->getParent())
1071 return CR_NoCapture;
1072 }
John McCallc63de662011-02-02 13:00:07 +00001073
1074 DeclarationName functionName;
1075 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1076 functionName = fn->getDeclName();
1077 // FIXME: variable from enclosing block that we couldn't capture from!
1078
1079 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1080 << var->getIdentifier() << functionName;
1081 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1082 << var->getIdentifier();
1083
1084 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +00001085}
1086
John McCall351762c2011-02-07 10:33:21 +00001087/// There is a well-formed capture at a particular scope level;
1088/// propagate it through all the nested blocks.
1089static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1090 const BlockDecl::Capture &capture) {
1091 VarDecl *var = capture.getVariable();
1092
1093 // Update all the inner blocks with the capture information.
1094 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1095 i != e; ++i) {
1096 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1097 innerBlock->Captures.push_back(
1098 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1099 /*nested*/ true, capture.getCopyExpr()));
1100 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1101 }
1102
1103 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1104}
1105
1106/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +00001107/// given value in the current context requires a variable capture.
1108///
1109/// This also keeps the captures set in the BlockScopeInfo records
1110/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +00001111static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001112 ValueDecl *value) {
1113 // Only variables ever require capture.
1114 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +00001115 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +00001116
1117 // Fast path: variables from the current context never require capture.
1118 DeclContext *DC = S.CurContext;
1119 if (var->getDeclContext() == DC) return CR_NoCapture;
1120
1121 // Only variables with local storage require capture.
1122 // FIXME: What about 'const' variables in C++?
1123 if (!var->hasLocalStorage()) return CR_NoCapture;
1124
1125 // Otherwise, we need to capture.
1126
1127 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +00001128 do {
1129 // Only blocks (and eventually C++0x closures) can capture; other
1130 // scopes don't work.
1131 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +00001132 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +00001133
1134 BlockScopeInfo *blockScope =
1135 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1136 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1137
John McCall351762c2011-02-07 10:33:21 +00001138 // Check whether we've already captured it in this block. If so,
1139 // we're done.
1140 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1141 return propagateCapture(S, functionScopesIndex,
1142 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +00001143
1144 functionScopesIndex--;
1145 DC = cast<BlockDecl>(DC)->getDeclContext();
1146 } while (var->getDeclContext() != DC);
1147
John McCall351762c2011-02-07 10:33:21 +00001148 // Okay, we descended all the way to the block that defines the variable.
1149 // Actually try to capture it.
1150 QualType type = var->getType();
1151
1152 // Prohibit variably-modified types.
1153 if (type->isVariablyModifiedType()) {
1154 S.Diag(loc, diag::err_ref_vm_type);
1155 S.Diag(var->getLocation(), diag::note_declared_at);
1156 return CR_Error;
1157 }
1158
1159 // Prohibit arrays, even in __block variables, but not references to
1160 // them.
1161 if (type->isArrayType()) {
1162 S.Diag(loc, diag::err_ref_array_type);
1163 S.Diag(var->getLocation(), diag::note_declared_at);
1164 return CR_Error;
1165 }
1166
1167 S.MarkDeclarationReferenced(loc, var);
1168
1169 // The BlocksAttr indicates the variable is bound by-reference.
1170 bool byRef = var->hasAttr<BlocksAttr>();
1171
1172 // Build a copy expression.
1173 Expr *copyExpr = 0;
John McCalla85af562011-04-28 02:15:35 +00001174 const RecordType *rtype;
1175 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1176 (rtype = type->getAs<RecordType>())) {
1177
1178 // The capture logic needs the destructor, so make sure we mark it.
1179 // Usually this is unnecessary because most local variables have
1180 // their destructors marked at declaration time, but parameters are
1181 // an exception because it's technically only the call site that
1182 // actually requires the destructor.
1183 if (isa<ParmVarDecl>(var))
1184 S.FinalizeVarWithDestructor(var, rtype);
1185
John McCall351762c2011-02-07 10:33:21 +00001186 // According to the blocks spec, the capture of a variable from
1187 // the stack requires a const copy constructor. This is not true
1188 // of the copy/move done to move a __block variable to the heap.
1189 type.addConst();
1190
1191 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1192 ExprResult result =
1193 S.PerformCopyInitialization(
1194 InitializedEntity::InitializeBlock(var->getLocation(),
1195 type, false),
1196 loc, S.Owned(declRef));
1197
1198 // Build a full-expression copy expression if initialization
1199 // succeeded and used a non-trivial constructor. Recover from
1200 // errors by pretending that the copy isn't necessary.
1201 if (!result.isInvalid() &&
1202 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1203 result = S.MaybeCreateExprWithCleanups(result);
1204 copyExpr = result.take();
1205 }
1206 }
1207
1208 // We're currently at the declarer; go back to the closure.
1209 functionScopesIndex++;
1210 BlockScopeInfo *blockScope =
1211 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1212
1213 // Build a valid capture in this scope.
1214 blockScope->Captures.push_back(
1215 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1216 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1217
1218 // Propagate that to inner captures if necessary.
1219 return propagateCapture(S, functionScopesIndex,
1220 blockScope->Captures.back());
1221}
1222
1223static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1224 const DeclarationNameInfo &NameInfo,
1225 bool byRef) {
1226 assert(isa<VarDecl>(vd) && "capturing non-variable");
1227
1228 VarDecl *var = cast<VarDecl>(vd);
1229 assert(var->hasLocalStorage() && "capturing non-local");
1230 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1231
1232 QualType exprType = var->getType().getNonReferenceType();
1233
1234 BlockDeclRefExpr *BDRE;
1235 if (!byRef) {
1236 // The variable will be bound by copy; make it const within the
1237 // closure, but record that this was done in the expression.
1238 bool constAdded = !exprType.isConstQualified();
1239 exprType.addConst();
1240
1241 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1242 NameInfo.getLoc(), false,
1243 constAdded);
1244 } else {
1245 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1246 NameInfo.getLoc(), true);
1247 }
1248
1249 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001250}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001251
John McCalldadc5752010-08-24 06:29:42 +00001252ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001253Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001254 SourceLocation Loc,
1255 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001256 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001257 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001258}
1259
John McCallf4cd4f92011-02-09 01:13:10 +00001260/// BuildDeclRefExpr - Build an expression that references a
1261/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001262ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001263Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001264 const DeclarationNameInfo &NameInfo,
1265 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001266 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001267
John McCall086a4642010-11-24 05:12:34 +00001268 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001269 SS? SS->getWithLocInContext(Context)
1270 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001271 D, NameInfo, Ty, VK);
1272
1273 // Just in case we're building an illegal pointer-to-member.
1274 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1275 E->setObjectKind(OK_BitField);
1276
1277 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001278}
1279
John McCallfeb624a2010-11-23 20:48:44 +00001280static ExprResult
1281BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1282 const CXXScopeSpec &SS, FieldDecl *Field,
1283 DeclAccessPair FoundDecl,
1284 const DeclarationNameInfo &MemberNameInfo);
1285
John McCalldadc5752010-08-24 06:29:42 +00001286ExprResult
John McCallf3a88602011-02-03 08:15:49 +00001287Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
1288 SourceLocation loc,
1289 IndirectFieldDecl *indirectField,
1290 Expr *baseObjectExpr,
1291 SourceLocation opLoc) {
1292 // First, build the expression that refers to the base object.
1293
1294 bool baseObjectIsPointer = false;
1295 Qualifiers baseQuals;
1296
1297 // Case 1: the base of the indirect field is not a field.
1298 VarDecl *baseVariable = indirectField->getVarDecl();
Douglas Gregore10f36d2011-02-18 02:44:58 +00001299 CXXScopeSpec EmptySS;
John McCallf3a88602011-02-03 08:15:49 +00001300 if (baseVariable) {
1301 assert(baseVariable->getType()->isRecordType());
1302
1303 // In principle we could have a member access expression that
1304 // accesses an anonymous struct/union that's a static member of
1305 // the base object's class. However, under the current standard,
1306 // static data members cannot be anonymous structs or unions.
1307 // Supporting this is as easy as building a MemberExpr here.
1308 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1309
1310 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1311
1312 ExprResult result =
Douglas Gregore10f36d2011-02-18 02:44:58 +00001313 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
John McCallf3a88602011-02-03 08:15:49 +00001314 if (result.isInvalid()) return ExprError();
1315
1316 baseObjectExpr = result.take();
1317 baseObjectIsPointer = false;
1318 baseQuals = baseObjectExpr->getType().getQualifiers();
1319
1320 // Case 2: the base of the indirect field is a field and the user
1321 // wrote a member expression.
1322 } else if (baseObjectExpr) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001323 // The caller provided the base object expression. Determine
1324 // whether its a pointer and whether it adds any qualifiers to the
1325 // anonymous struct/union fields we're looking into.
John McCallf3a88602011-02-03 08:15:49 +00001326 QualType objectType = baseObjectExpr->getType();
1327
1328 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1329 baseObjectIsPointer = true;
1330 objectType = ptr->getPointeeType();
1331 } else {
1332 baseObjectIsPointer = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001333 }
John McCallf3a88602011-02-03 08:15:49 +00001334 baseQuals = objectType.getQualifiers();
1335
1336 // Case 3: the base of the indirect field is a field and we should
1337 // build an implicit member access.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001338 } else {
1339 // We've found a member of an anonymous struct/union that is
1340 // inside a non-anonymous struct/union, so in a well-formed
1341 // program our base object expression is "this".
Richard Smith938f40b2011-06-11 17:19:42 +00001342 QualType ThisTy = getAndCaptureCurrentThisType();
1343 if (ThisTy.isNull()) {
John McCallf3a88602011-02-03 08:15:49 +00001344 Diag(loc, diag::err_invalid_member_use_in_static_method)
1345 << indirectField->getDeclName();
1346 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001347 }
1348
John McCallf3a88602011-02-03 08:15:49 +00001349 // Our base object expression is "this".
1350 baseObjectExpr =
Richard Smith938f40b2011-06-11 17:19:42 +00001351 new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
John McCallf3a88602011-02-03 08:15:49 +00001352 baseObjectIsPointer = true;
Richard Smith938f40b2011-06-11 17:19:42 +00001353 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001354 }
1355
1356 // Build the implicit member references to the field of the
1357 // anonymous struct/union.
John McCallf3a88602011-02-03 08:15:49 +00001358 Expr *result = baseObjectExpr;
1359 IndirectFieldDecl::chain_iterator
1360 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCallfeb624a2010-11-23 20:48:44 +00001361
John McCallf3a88602011-02-03 08:15:49 +00001362 // Build the first member access in the chain with full information.
1363 if (!baseVariable) {
1364 FieldDecl *field = cast<FieldDecl>(*FI);
John McCallfeb624a2010-11-23 20:48:44 +00001365
John McCallf3a88602011-02-03 08:15:49 +00001366 // FIXME: use the real found-decl info!
1367 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall8ccfcb52009-09-24 19:53:00 +00001368
John McCallf3a88602011-02-03 08:15:49 +00001369 // Make a nameInfo that properly uses the anonymous name.
1370 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall8ccfcb52009-09-24 19:53:00 +00001371
John McCallf3a88602011-02-03 08:15:49 +00001372 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001373 EmptySS, field, foundDecl,
John McCallf3a88602011-02-03 08:15:49 +00001374 memberNameInfo).take();
1375 baseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +00001376
John McCallf3a88602011-02-03 08:15:49 +00001377 // FIXME: check qualified member access
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001378 }
1379
John McCallf3a88602011-02-03 08:15:49 +00001380 // In all cases, we should now skip the first declaration in the chain.
1381 ++FI;
1382
Douglas Gregore10f36d2011-02-18 02:44:58 +00001383 while (FI != FEnd) {
1384 FieldDecl *field = cast<FieldDecl>(*FI++);
John McCallf3a88602011-02-03 08:15:49 +00001385
1386 // FIXME: these are somewhat meaningless
1387 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1388 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCallf3a88602011-02-03 08:15:49 +00001389
1390 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001391 (FI == FEnd? SS : EmptySS), field,
1392 foundDecl, memberNameInfo)
John McCallf3a88602011-02-03 08:15:49 +00001393 .take();
1394 }
1395
1396 return Owned(result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001397}
1398
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001399/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001400/// possibly a list of template arguments.
1401///
1402/// If this produces template arguments, it is permitted to call
1403/// DecomposeTemplateName.
1404///
1405/// This actually loses a lot of source location information for
1406/// non-standard name kinds; we should consider preserving that in
1407/// some way.
1408static void DecomposeUnqualifiedId(Sema &SemaRef,
1409 const UnqualifiedId &Id,
1410 TemplateArgumentListInfo &Buffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001411 DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00001412 const TemplateArgumentListInfo *&TemplateArgs) {
1413 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1414 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1415 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1416
1417 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1418 Id.TemplateId->getTemplateArgs(),
1419 Id.TemplateId->NumArgs);
1420 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1421 TemplateArgsPtr.release();
1422
John McCall3e56fd42010-08-23 07:28:44 +00001423 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001424 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1425 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001426 TemplateArgs = &Buffer;
1427 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001428 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001429 TemplateArgs = 0;
1430 }
1431}
1432
John McCall2d74de92009-12-01 22:10:20 +00001433/// Determines if the given class is provably not derived from all of
1434/// the prospective base classes.
1435static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1436 CXXRecordDecl *Record,
1437 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +00001438 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +00001439 return false;
1440
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001441 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +00001442 if (!RD) return false;
1443 Record = cast<CXXRecordDecl>(RD);
1444
John McCall2d74de92009-12-01 22:10:20 +00001445 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1446 E = Record->bases_end(); I != E; ++I) {
1447 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1448 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1449 if (!BaseRT) return false;
1450
1451 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +00001452 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1453 return false;
1454 }
1455
1456 return true;
1457}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001458
John McCall2d74de92009-12-01 22:10:20 +00001459enum IMAKind {
1460 /// The reference is definitely not an instance member access.
1461 IMA_Static,
1462
1463 /// The reference may be an implicit instance member access.
1464 IMA_Mixed,
1465
1466 /// The reference may be to an instance member, but it is invalid if
1467 /// so, because the context is not an instance method.
1468 IMA_Mixed_StaticContext,
1469
1470 /// The reference may be to an instance member, but it is invalid if
1471 /// so, because the context is from an unrelated class.
1472 IMA_Mixed_Unrelated,
1473
1474 /// The reference is definitely an implicit instance member access.
1475 IMA_Instance,
1476
1477 /// The reference may be to an unresolved using declaration.
1478 IMA_Unresolved,
1479
1480 /// The reference may be to an unresolved using declaration and the
1481 /// context is not an instance method.
1482 IMA_Unresolved_StaticContext,
1483
John McCall2d74de92009-12-01 22:10:20 +00001484 /// All possible referrents are instance members and the current
1485 /// context is not an instance method.
1486 IMA_Error_StaticContext,
1487
1488 /// All possible referrents are instance members of an unrelated
1489 /// class.
1490 IMA_Error_Unrelated
1491};
1492
1493/// The given lookup names class member(s) and is not being used for
1494/// an address-of-member expression. Classify the type of access
1495/// according to whether it's possible that this reference names an
1496/// instance member. This is best-effort; it is okay to
1497/// conservatively answer "yes", in which case some errors will simply
1498/// not be caught until template-instantiation.
1499static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
Richard Smith938f40b2011-06-11 17:19:42 +00001500 Scope *CurScope,
John McCall2d74de92009-12-01 22:10:20 +00001501 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +00001502 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +00001503
John McCall87fe5d52010-05-20 01:18:31 +00001504 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
Richard Smith938f40b2011-06-11 17:19:42 +00001505
John McCall2d74de92009-12-01 22:10:20 +00001506 bool isStaticContext =
John McCall87fe5d52010-05-20 01:18:31 +00001507 (!isa<CXXMethodDecl>(DC) ||
1508 cast<CXXMethodDecl>(DC)->isStatic());
John McCall2d74de92009-12-01 22:10:20 +00001509
Richard Smith938f40b2011-06-11 17:19:42 +00001510 // C++0x [expr.prim]p4:
1511 // Otherwise, if a member-declarator declares a non-static data member
1512 // of a class X, the expression this is a prvalue of type "pointer to X"
1513 // within the optional brace-or-equal-initializer.
1514 if (CurScope->getFlags() & Scope::ThisScope)
1515 isStaticContext = false;
1516
John McCall2d74de92009-12-01 22:10:20 +00001517 if (R.isUnresolvableResult())
1518 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1519
1520 // Collect all the declaring classes of instance members we find.
1521 bool hasNonInstance = false;
Sebastian Redl34620312010-11-26 16:28:07 +00001522 bool hasField = false;
John McCall2d74de92009-12-01 22:10:20 +00001523 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1524 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCalla8ae2222010-04-06 21:38:20 +00001525 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00001526
John McCalla8ae2222010-04-06 21:38:20 +00001527 if (D->isCXXInstanceMember()) {
Sebastian Redl34620312010-11-26 16:28:07 +00001528 if (dyn_cast<FieldDecl>(D))
1529 hasField = true;
1530
John McCall2d74de92009-12-01 22:10:20 +00001531 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCall2d74de92009-12-01 22:10:20 +00001532 Classes.insert(R->getCanonicalDecl());
1533 }
1534 else
1535 hasNonInstance = true;
1536 }
1537
1538 // If we didn't find any instance members, it can't be an implicit
1539 // member reference.
1540 if (Classes.empty())
1541 return IMA_Static;
1542
1543 // If the current context is not an instance method, it can't be
1544 // an implicit member reference.
Sebastian Redl34620312010-11-26 16:28:07 +00001545 if (isStaticContext) {
1546 if (hasNonInstance)
1547 return IMA_Mixed_StaticContext;
1548
1549 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1550 // C++0x [expr.prim.general]p10:
1551 // An id-expression that denotes a non-static data member or non-static
1552 // member function of a class can only be used:
1553 // (...)
John McCall31168b02011-06-15 23:02:42 +00001554 // - if that id-expression denotes a non-static data member and it
1555 // appears in an unevaluated operand.
1556 const Sema::ExpressionEvaluationContextRecord& record
1557 = SemaRef.ExprEvalContexts.back();
1558 bool isUnevaluatedExpression = (record.Context == Sema::Unevaluated);
Sebastian Redl34620312010-11-26 16:28:07 +00001559 if (isUnevaluatedExpression)
1560 return IMA_Mixed_StaticContext;
1561 }
1562
1563 return IMA_Error_StaticContext;
1564 }
John McCall2d74de92009-12-01 22:10:20 +00001565
Richard Smith938f40b2011-06-11 17:19:42 +00001566 CXXRecordDecl *contextClass;
1567 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
1568 contextClass = MD->getParent()->getCanonicalDecl();
1569 else
1570 contextClass = cast<CXXRecordDecl>(DC);
Argyrios Kyrtzidis36e4ae32011-04-14 00:46:47 +00001571
1572 // [class.mfct.non-static]p3:
1573 // ...is used in the body of a non-static member function of class X,
1574 // if name lookup (3.4.1) resolves the name in the id-expression to a
1575 // non-static non-type member of some class C [...]
1576 // ...if C is not X or a base class of X, the class member access expression
1577 // is ill-formed.
1578 if (R.getNamingClass() &&
1579 contextClass != R.getNamingClass()->getCanonicalDecl() &&
1580 contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
1581 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1582
John McCall2d74de92009-12-01 22:10:20 +00001583 // If we can prove that the current context is unrelated to all the
1584 // declaring classes, it can't be an implicit member reference (in
1585 // which case it's an error if any of those members are selected).
Argyrios Kyrtzidis36e4ae32011-04-14 00:46:47 +00001586 if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
John McCall2d74de92009-12-01 22:10:20 +00001587 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1588
1589 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1590}
1591
1592/// Diagnose a reference to a field with no object available.
1593static void DiagnoseInstanceReference(Sema &SemaRef,
1594 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00001595 NamedDecl *rep,
1596 const DeclarationNameInfo &nameInfo) {
1597 SourceLocation Loc = nameInfo.getLoc();
John McCall2d74de92009-12-01 22:10:20 +00001598 SourceRange Range(Loc);
1599 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1600
John McCallf3a88602011-02-03 08:15:49 +00001601 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCall2d74de92009-12-01 22:10:20 +00001602 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1603 if (MD->isStatic()) {
1604 // "invalid use of member 'x' in static member function"
1605 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCallf3a88602011-02-03 08:15:49 +00001606 << Range << nameInfo.getName();
John McCall2d74de92009-12-01 22:10:20 +00001607 return;
1608 }
1609 }
1610
1611 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCallf3a88602011-02-03 08:15:49 +00001612 << nameInfo.getName() << Range;
John McCall2d74de92009-12-01 22:10:20 +00001613 return;
1614 }
1615
1616 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +00001617}
1618
John McCalld681c392009-12-16 08:11:27 +00001619/// Diagnose an empty lookup.
1620///
1621/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001622bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1623 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001624 DeclarationName Name = R.getLookupName();
1625
John McCalld681c392009-12-16 08:11:27 +00001626 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001627 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001628 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1629 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001630 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001631 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001632 diagnostic_suggest = diag::err_undeclared_use_suggest;
1633 }
John McCalld681c392009-12-16 08:11:27 +00001634
Douglas Gregor598b08f2009-12-31 05:20:13 +00001635 // If the original lookup was an unqualified lookup, fake an
1636 // unqualified lookup. This is useful when (for example) the
1637 // original lookup would not have found something because it was a
1638 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001639 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001640 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001641 if (isa<CXXRecordDecl>(DC)) {
1642 LookupQualifiedName(R, DC);
1643
1644 if (!R.empty()) {
1645 // Don't give errors about ambiguities in this lookup.
1646 R.suppressDiagnostics();
1647
1648 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1649 bool isInstance = CurMethod &&
1650 CurMethod->isInstance() &&
1651 DC == CurMethod->getParent();
1652
1653 // Give a code modification hint to insert 'this->'.
1654 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1655 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001656 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001657 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1658 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001659 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001660 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001661 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001662 Diag(R.getNameLoc(), diagnostic) << Name
1663 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1664 QualType DepThisType = DepMethod->getThisType(Context);
1665 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1666 R.getNameLoc(), DepThisType, false);
1667 TemplateArgumentListInfo TList;
1668 if (ULE->hasExplicitTemplateArgs())
1669 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001670
Douglas Gregore16af532011-02-28 18:50:33 +00001671 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001672 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001673 CXXDependentScopeMemberExpr *DepExpr =
1674 CXXDependentScopeMemberExpr::Create(
1675 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001676 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyfe712382010-08-20 20:54:15 +00001677 R.getLookupNameInfo(), &TList);
1678 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001679 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001680 // FIXME: we should be able to handle this case too. It is correct
1681 // to add this-> here. This is a workaround for PR7947.
1682 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001683 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001684 } else {
John McCalld681c392009-12-16 08:11:27 +00001685 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001686 }
John McCalld681c392009-12-16 08:11:27 +00001687
1688 // Do we really want to note all of these?
1689 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1690 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1691
1692 // Tell the callee to try to recover.
1693 return false;
1694 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001695
1696 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001697 }
1698 }
1699
Douglas Gregor598b08f2009-12-31 05:20:13 +00001700 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001701 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +00001702 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001703 if (!R.empty()) {
1704 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1705 if (SS.isEmpty())
1706 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1707 << FixItHint::CreateReplacement(R.getNameLoc(),
1708 R.getLookupName().getAsString());
1709 else
1710 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1711 << Name << computeDeclContext(SS, false) << R.getLookupName()
1712 << SS.getRange()
1713 << FixItHint::CreateReplacement(R.getNameLoc(),
1714 R.getLookupName().getAsString());
1715 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1716 Diag(ND->getLocation(), diag::note_previous_decl)
1717 << ND->getDeclName();
1718
1719 // Tell the callee to try to recover.
1720 return false;
1721 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001722
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001723 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1724 // FIXME: If we ended up with a typo for a type name or
1725 // Objective-C class name, we're in trouble because the parser
1726 // is in the wrong place to recover. Suggest the typo
1727 // correction, but don't make it a fix-it since we're not going
1728 // to recover well anyway.
1729 if (SS.isEmpty())
1730 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1731 else
1732 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1733 << Name << computeDeclContext(SS, false) << R.getLookupName()
1734 << SS.getRange();
1735
1736 // Don't try to recover; it won't work.
1737 return true;
1738 }
1739 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001740 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001741 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001742 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001743 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001744 else
Douglas Gregor25363982010-01-01 00:15:04 +00001745 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001746 << Name << computeDeclContext(SS, false) << Corrected
1747 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001748 return true;
1749 }
Douglas Gregor25363982010-01-01 00:15:04 +00001750 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001751 }
1752
1753 // Emit a special diagnostic for failed member lookups.
1754 // FIXME: computing the declaration context might fail here (?)
1755 if (!SS.isEmpty()) {
1756 Diag(R.getNameLoc(), diag::err_no_member)
1757 << Name << computeDeclContext(SS, false)
1758 << SS.getRange();
1759 return true;
1760 }
1761
John McCalld681c392009-12-16 08:11:27 +00001762 // Give up, we can't recover.
1763 Diag(R.getNameLoc(), diagnostic) << Name;
1764 return true;
1765}
1766
Douglas Gregor05fcf842010-11-02 20:36:02 +00001767ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1768 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001769 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1770 if (!IDecl)
1771 return 0;
1772 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1773 if (!ClassImpDecl)
1774 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001775 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001776 if (!property)
1777 return 0;
1778 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001779 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1780 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001781 return 0;
1782 return property;
1783}
1784
Douglas Gregor05fcf842010-11-02 20:36:02 +00001785bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1786 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1787 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1788 if (!IDecl)
1789 return false;
1790 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1791 if (!ClassImpDecl)
1792 return false;
1793 if (ObjCPropertyImplDecl *PIDecl
1794 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1795 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1796 PIDecl->getPropertyIvarDecl())
1797 return false;
1798
1799 return true;
1800}
1801
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001802ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1803 IdentifierInfo *II,
1804 SourceLocation NameLoc) {
1805 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001806 bool LookForIvars;
1807 if (Lookup.empty())
1808 LookForIvars = true;
1809 else if (CurMeth->isClassMethod())
1810 LookForIvars = false;
1811 else
1812 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001813 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1814 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001815 if (!LookForIvars)
1816 return 0;
1817
Fariborz Jahanian18722982010-07-17 00:59:30 +00001818 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1819 if (!IDecl)
1820 return 0;
1821 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001822 if (!ClassImpDecl)
1823 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001824 bool DynamicImplSeen = false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001825 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian18722982010-07-17 00:59:30 +00001826 if (!property)
1827 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001828 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001829 DynamicImplSeen =
1830 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001831 // property implementation has a designated ivar. No need to assume a new
1832 // one.
1833 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1834 return 0;
1835 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001836 if (!DynamicImplSeen) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001837 QualType PropType = Context.getCanonicalType(property->getType());
1838 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001839 NameLoc, NameLoc,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001840 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001841 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001842 (Expr *)0, true);
1843 ClassImpDecl->addDecl(Ivar);
1844 IDecl->makeDeclVisibleInContext(Ivar, false);
1845 property->setPropertyIvarDecl(Ivar);
1846 return Ivar;
1847 }
1848 return 0;
1849}
1850
John McCalldadc5752010-08-24 06:29:42 +00001851ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001852 CXXScopeSpec &SS,
1853 UnqualifiedId &Id,
1854 bool HasTrailingLParen,
1855 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001856 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1857 "cannot be direct & operand and have a trailing lparen");
1858
1859 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001860 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001861
John McCall10eae182009-11-30 22:42:35 +00001862 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001863
1864 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001865 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001866 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001867 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001868
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001869 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001870 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001871 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001872
John McCalle66edc12009-11-24 19:00:30 +00001873 // C++ [temp.dep.expr]p3:
1874 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001875 // -- an identifier that was declared with a dependent type,
1876 // (note: handled after lookup)
1877 // -- a template-id that is dependent,
1878 // (note: handled in BuildTemplateIdExpr)
1879 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001880 // -- a nested-name-specifier that contains a class-name that
1881 // names a dependent type.
1882 // Determine whether this is a member of an unknown specialization;
1883 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001884 bool DependentID = false;
1885 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1886 Name.getCXXNameType()->isDependentType()) {
1887 DependentID = true;
1888 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001889 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001890 if (RequireCompleteDeclContext(SS, DC))
1891 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001892 } else {
1893 DependentID = true;
1894 }
1895 }
1896
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001897 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001898 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001899 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001900
Fariborz Jahanian86151342010-07-22 23:33:21 +00001901 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001902 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001903 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001904 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001905 // Lookup the template name again to correctly establish the context in
1906 // which it was found. This is really unfortunate as we already did the
1907 // lookup to determine that it was a template name in the first place. If
1908 // this becomes a performance hit, we can work harder to preserve those
1909 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001910 bool MemberOfUnknownSpecialization;
1911 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1912 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001913
1914 if (MemberOfUnknownSpecialization ||
1915 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1916 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1917 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001918 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001919 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001920 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001921
Douglas Gregora5226932011-02-04 13:35:07 +00001922 // If the result might be in a dependent base class, this is a dependent
1923 // id-expression.
1924 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1925 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1926 TemplateArgs);
1927
John McCalle66edc12009-11-24 19:00:30 +00001928 // If this reference is in an Objective-C method, then we need to do
1929 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001930 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001931 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001932 if (E.isInvalid())
1933 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001934
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001935 if (Expr *Ex = E.takeAs<Expr>())
1936 return Owned(Ex);
1937
1938 // Synthesize ivars lazily.
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001939 if (getLangOptions().ObjCDefaultSynthProperties &&
1940 getLangOptions().ObjCNonFragileABI2) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001941 if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001942 if (const ObjCPropertyDecl *Property =
1943 canSynthesizeProvisionalIvar(II)) {
1944 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1945 Diag(Property->getLocation(), diag::note_property_declare);
1946 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001947 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1948 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001949 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001950 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001951 // for further use, this must be set to false if in class method.
1952 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001953 }
Chris Lattner59a25942008-03-31 00:36:02 +00001954 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001955
John McCalle66edc12009-11-24 19:00:30 +00001956 if (R.isAmbiguous())
1957 return ExprError();
1958
Douglas Gregor171c45a2009-02-18 21:56:37 +00001959 // Determine whether this name might be a candidate for
1960 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001961 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001962
John McCalle66edc12009-11-24 19:00:30 +00001963 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001964 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001965 // in C90, extension in C99, forbidden in C++).
1966 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1967 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1968 if (D) R.addDecl(D);
1969 }
1970
1971 // If this name wasn't predeclared and if this is not a function
1972 // call, diagnose the problem.
1973 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001974 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001975 return ExprError();
1976
1977 assert(!R.empty() &&
1978 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001979
1980 // If we found an Objective-C instance variable, let
1981 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001982 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001983 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1984 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001985 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001986 assert(E.isInvalid() || E.get());
1987 return move(E);
1988 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001989 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001990 }
Mike Stump11289f42009-09-09 15:08:12 +00001991
John McCalle66edc12009-11-24 19:00:30 +00001992 // This is guaranteed from this point on.
1993 assert(!R.empty() || ADL);
1994
John McCall2d74de92009-12-01 22:10:20 +00001995 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001996 // C++ [class.mfct.non-static]p3:
1997 // When an id-expression that is not part of a class member access
1998 // syntax and not used to form a pointer to member is used in the
1999 // body of a non-static member function of class X, if name lookup
2000 // resolves the name in the id-expression to a non-static non-type
2001 // member of some class C, the id-expression is transformed into a
2002 // class member access expression using (*this) as the
2003 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00002004 //
2005 // But we don't actually need to do this for '&' operands if R
2006 // resolved to a function or overloaded function set, because the
2007 // expression is ill-formed if it actually works out to be a
2008 // non-static member function:
2009 //
2010 // C++ [expr.ref]p4:
2011 // Otherwise, if E1.E2 refers to a non-static member function. . .
2012 // [t]he expression can be used only as the left-hand operand of a
2013 // member function call.
2014 //
2015 // There are other safeguards against such uses, but it's important
2016 // to get this right here so that we don't end up making a
2017 // spuriously dependent expression if we're inside a dependent
2018 // instance method.
John McCall57500772009-12-16 12:17:52 +00002019 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00002020 bool MightBeImplicitMember;
2021 if (!isAddressOfOperand)
2022 MightBeImplicitMember = true;
2023 else if (!SS.isEmpty())
2024 MightBeImplicitMember = false;
2025 else if (R.isOverloadedResult())
2026 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00002027 else if (R.isUnresolvableResult())
2028 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00002029 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00002030 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2031 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00002032
2033 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00002034 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00002035 }
2036
John McCalle66edc12009-11-24 19:00:30 +00002037 if (TemplateArgs)
2038 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00002039
John McCalle66edc12009-11-24 19:00:30 +00002040 return BuildDeclarationNameExpr(SS, R, ADL);
2041}
2042
John McCall57500772009-12-16 12:17:52 +00002043/// Builds an expression which might be an implicit member expression.
John McCalldadc5752010-08-24 06:29:42 +00002044ExprResult
John McCall57500772009-12-16 12:17:52 +00002045Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
2046 LookupResult &R,
2047 const TemplateArgumentListInfo *TemplateArgs) {
Richard Smith938f40b2011-06-11 17:19:42 +00002048 switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
John McCall57500772009-12-16 12:17:52 +00002049 case IMA_Instance:
2050 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
2051
John McCall57500772009-12-16 12:17:52 +00002052 case IMA_Mixed:
2053 case IMA_Mixed_Unrelated:
2054 case IMA_Unresolved:
2055 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
2056
2057 case IMA_Static:
2058 case IMA_Mixed_StaticContext:
2059 case IMA_Unresolved_StaticContext:
2060 if (TemplateArgs)
2061 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
2062 return BuildDeclarationNameExpr(SS, R, false);
2063
2064 case IMA_Error_StaticContext:
2065 case IMA_Error_Unrelated:
John McCallf3a88602011-02-03 08:15:49 +00002066 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
2067 R.getLookupNameInfo());
John McCall57500772009-12-16 12:17:52 +00002068 return ExprError();
2069 }
2070
2071 llvm_unreachable("unexpected instance member access kind");
2072 return ExprError();
2073}
2074
John McCall10eae182009-11-30 22:42:35 +00002075/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2076/// declaration name, generally during template instantiation.
2077/// There's a large number of things which don't need to be done along
2078/// this path.
John McCalldadc5752010-08-24 06:29:42 +00002079ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002080Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002081 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00002082 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00002083 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002084 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00002085
John McCall0b66eb32010-05-01 00:40:08 +00002086 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00002087 return ExprError();
2088
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002089 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00002090 LookupQualifiedName(R, DC);
2091
2092 if (R.isAmbiguous())
2093 return ExprError();
2094
2095 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002096 Diag(NameInfo.getLoc(), diag::err_no_member)
2097 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002098 return ExprError();
2099 }
2100
2101 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
2102}
2103
2104/// LookupInObjCMethod - The parser has read a name in, and Sema has
2105/// detected that we're currently inside an ObjC method. Perform some
2106/// additional lookup.
2107///
2108/// Ideally, most of this would be done by lookup, but there's
2109/// actually quite a lot of extra work involved.
2110///
2111/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00002112ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002113Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00002114 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00002115 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00002116 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00002117
John McCalle66edc12009-11-24 19:00:30 +00002118 // There are two cases to handle here. 1) scoped lookup could have failed,
2119 // in which case we should look for an ivar. 2) scoped lookup could have
2120 // found a decl, but that decl is outside the current instance method (i.e.
2121 // a global variable). In these two cases, we do a lookup for an ivar with
2122 // this name, if the lookup sucedes, we replace it our current decl.
2123
2124 // If we're in a class method, we don't normally want to look for
2125 // ivars. But if we don't find anything else, and there's an
2126 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00002127 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00002128
2129 bool LookForIvars;
2130 if (Lookup.empty())
2131 LookForIvars = true;
2132 else if (IsClassMethod)
2133 LookForIvars = false;
2134 else
2135 LookForIvars = (Lookup.isSingleResult() &&
2136 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00002137 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00002138 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00002139 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00002140 ObjCInterfaceDecl *ClassDeclared;
2141 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2142 // Diagnose using an ivar in a class method.
2143 if (IsClassMethod)
2144 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2145 << IV->getDeclName());
2146
2147 // If we're referencing an invalid decl, just return this as a silent
2148 // error node. The error diagnostic was already emitted on the decl.
2149 if (IV->isInvalidDecl())
2150 return ExprError();
2151
2152 // Check if referencing a field with __attribute__((deprecated)).
2153 if (DiagnoseUseOfDecl(IV, Loc))
2154 return ExprError();
2155
2156 // Diagnose the use of an ivar outside of the declaring class.
2157 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2158 ClassDeclared != IFace)
2159 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2160
2161 // FIXME: This should use a new expr for a direct reference, don't
2162 // turn this into Self->ivar, just return a BareIVarExpr or something.
2163 IdentifierInfo &II = Context.Idents.get("self");
2164 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002165 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00002166 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00002167 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00002168 SelfName, false, false);
2169 if (SelfExpr.isInvalid())
2170 return ExprError();
2171
John Wiegley01296292011-04-08 18:41:53 +00002172 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2173 if (SelfExpr.isInvalid())
2174 return ExprError();
John McCall27584242010-12-06 20:48:59 +00002175
John McCalle66edc12009-11-24 19:00:30 +00002176 MarkDeclarationReferenced(Loc, IV);
Fariborz Jahanian82bc4362011-04-12 23:39:33 +00002177 Expr *base = SelfExpr.take();
2178 base = base->IgnoreParenImpCasts();
2179 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(base)) {
2180 const NamedDecl *ND = DE->getDecl();
2181 if (!isa<ImplicitParamDecl>(ND)) {
Fariborz Jahanian66a6c062011-04-15 17:04:42 +00002182 // relax the rule such that it is allowed to have a shadow 'self'
2183 // where stand-alone ivar can be found in this 'self' object.
2184 // This is to match gcc's behavior.
2185 ObjCInterfaceDecl *selfIFace = 0;
2186 if (const ObjCObjectPointerType *OPT =
2187 base->getType()->getAsObjCInterfacePointerType())
2188 selfIFace = OPT->getInterfaceDecl();
2189 if (!selfIFace ||
2190 !selfIFace->lookupInstanceVariable(IV->getIdentifier())) {
Fariborz Jahanian82bc4362011-04-12 23:39:33 +00002191 Diag(Loc, diag::error_implicit_ivar_access)
2192 << IV->getDeclName();
2193 Diag(ND->getLocation(), diag::note_declared_at);
2194 return ExprError();
2195 }
Fariborz Jahanian66a6c062011-04-15 17:04:42 +00002196 }
Fariborz Jahanian82bc4362011-04-12 23:39:33 +00002197 }
John McCalle66edc12009-11-24 19:00:30 +00002198 return Owned(new (Context)
2199 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00002200 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00002201 }
Chris Lattner87313662010-04-12 05:10:17 +00002202 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00002203 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00002204 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00002205 ObjCInterfaceDecl *ClassDeclared;
2206 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2207 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2208 IFace == ClassDeclared)
2209 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2210 }
2211 }
2212
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002213 if (Lookup.empty() && II && AllowBuiltinCreation) {
2214 // FIXME. Consolidate this with similar code in LookupName.
2215 if (unsigned BuiltinID = II->getBuiltinID()) {
2216 if (!(getLangOptions().CPlusPlus &&
2217 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2218 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2219 S, Lookup.isForRedeclaration(),
2220 Lookup.getNameLoc());
2221 if (D) Lookup.addDecl(D);
2222 }
2223 }
2224 }
John McCalle66edc12009-11-24 19:00:30 +00002225 // Sentinel value saying that we didn't do anything special.
2226 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00002227}
John McCalld14a8642009-11-21 08:51:07 +00002228
John McCall16df1e52010-03-30 21:47:33 +00002229/// \brief Cast a base object to a member's actual type.
2230///
2231/// Logically this happens in three phases:
2232///
2233/// * First we cast from the base type to the naming class.
2234/// The naming class is the class into which we were looking
2235/// when we found the member; it's the qualifier type if a
2236/// qualifier was provided, and otherwise it's the base type.
2237///
2238/// * Next we cast from the naming class to the declaring class.
2239/// If the member we found was brought into a class's scope by
2240/// a using declaration, this is that class; otherwise it's
2241/// the class declaring the member.
2242///
2243/// * Finally we cast from the declaring class to the "true"
2244/// declaring class of the member. This conversion does not
2245/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00002246ExprResult
2247Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002248 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002249 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002250 NamedDecl *Member) {
2251 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2252 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00002253 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002254
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002255 QualType DestRecordType;
2256 QualType DestType;
2257 QualType FromRecordType;
2258 QualType FromType = From->getType();
2259 bool PointerConversions = false;
2260 if (isa<FieldDecl>(Member)) {
2261 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002262
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002263 if (FromType->getAs<PointerType>()) {
2264 DestType = Context.getPointerType(DestRecordType);
2265 FromRecordType = FromType->getPointeeType();
2266 PointerConversions = true;
2267 } else {
2268 DestType = DestRecordType;
2269 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002270 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002271 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2272 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00002273 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002274
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002275 DestType = Method->getThisType(Context);
2276 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002277
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002278 if (FromType->getAs<PointerType>()) {
2279 FromRecordType = FromType->getPointeeType();
2280 PointerConversions = true;
2281 } else {
2282 FromRecordType = FromType;
2283 DestType = DestRecordType;
2284 }
2285 } else {
2286 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00002287 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002288 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002289
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002290 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002291 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002292
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002293 // If the unqualified types are the same, no conversion is necessary.
2294 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002295 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002296
John McCall16df1e52010-03-30 21:47:33 +00002297 SourceRange FromRange = From->getSourceRange();
2298 SourceLocation FromLoc = FromRange.getBegin();
2299
John McCall2536c6d2010-08-25 10:28:54 +00002300 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002301
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002302 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002303 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002304 // class name.
2305 //
2306 // If the member was a qualified name and the qualified referred to a
2307 // specific base subobject type, we'll cast to that intermediate type
2308 // first and then to the object in which the member is declared. That allows
2309 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2310 //
2311 // class Base { public: int x; };
2312 // class Derived1 : public Base { };
2313 // class Derived2 : public Base { };
2314 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2315 //
2316 // void VeryDerived::f() {
2317 // x = 17; // error: ambiguous base subobjects
2318 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2319 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002320 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002321 QualType QType = QualType(Qualifier->getAsType(), 0);
2322 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2323 assert(QType->isRecordType() && "lookup done with non-record type");
2324
2325 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2326
2327 // In C++98, the qualifier type doesn't actually have to be a base
2328 // type of the object type, in which case we just ignore it.
2329 // Otherwise build the appropriate casts.
2330 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002331 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002332 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002333 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002334 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002335
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002336 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002337 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002338 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2339 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002340
2341 FromType = QType;
2342 FromRecordType = QRecordType;
2343
2344 // If the qualifier type was the same as the destination type,
2345 // we're done.
2346 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002347 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002348 }
2349 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002350
John McCall16df1e52010-03-30 21:47:33 +00002351 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002352
John McCall16df1e52010-03-30 21:47:33 +00002353 // If we actually found the member through a using declaration, cast
2354 // down to the using declaration's type.
2355 //
2356 // Pointer equality is fine here because only one declaration of a
2357 // class ever has member declarations.
2358 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2359 assert(isa<UsingShadowDecl>(FoundDecl));
2360 QualType URecordType = Context.getTypeDeclType(
2361 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2362
2363 // We only need to do this if the naming-class to declaring-class
2364 // conversion is non-trivial.
2365 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2366 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002367 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002368 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002369 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002370 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002371
John McCall16df1e52010-03-30 21:47:33 +00002372 QualType UType = URecordType;
2373 if (PointerConversions)
2374 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002375 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2376 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002377 FromType = UType;
2378 FromRecordType = URecordType;
2379 }
2380
2381 // We don't do access control for the conversion from the
2382 // declaring class to the true declaring class.
2383 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002384 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002385
John McCallcf142162010-08-07 06:22:56 +00002386 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002387 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2388 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002389 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002390 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002391
John Wiegley01296292011-04-08 18:41:53 +00002392 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2393 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002394}
Douglas Gregor3256d042009-06-30 15:47:41 +00002395
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002396/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00002397static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00002398 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00002399 DeclAccessPair FoundDecl,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002400 const DeclarationNameInfo &MemberNameInfo,
2401 QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +00002402 ExprValueKind VK, ExprObjectKind OK,
John McCalle66edc12009-11-24 19:00:30 +00002403 const TemplateArgumentListInfo *TemplateArgs = 0) {
Douglas Gregorea972d32011-02-28 21:54:11 +00002404 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002405 Member, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002406 TemplateArgs, Ty, VK, OK);
Douglas Gregorc1905232009-08-26 22:36:53 +00002407}
2408
John McCallfeb624a2010-11-23 20:48:44 +00002409static ExprResult
2410BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2411 const CXXScopeSpec &SS, FieldDecl *Field,
2412 DeclAccessPair FoundDecl,
2413 const DeclarationNameInfo &MemberNameInfo) {
2414 // x.a is an l-value if 'a' has a reference type. Otherwise:
2415 // x.a is an l-value/x-value/pr-value if the base is (and note
2416 // that *x is always an l-value), except that if the base isn't
2417 // an ordinary object then we must have an rvalue.
2418 ExprValueKind VK = VK_LValue;
2419 ExprObjectKind OK = OK_Ordinary;
2420 if (!IsArrow) {
2421 if (BaseExpr->getObjectKind() == OK_Ordinary)
2422 VK = BaseExpr->getValueKind();
2423 else
2424 VK = VK_RValue;
2425 }
2426 if (VK != VK_RValue && Field->isBitField())
2427 OK = OK_BitField;
2428
2429 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2430 QualType MemberType = Field->getType();
2431 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2432 MemberType = Ref->getPointeeType();
2433 VK = VK_LValue;
2434 } else {
2435 QualType BaseType = BaseExpr->getType();
2436 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2437
2438 Qualifiers BaseQuals = BaseType.getQualifiers();
2439
2440 // GC attributes are never picked up by members.
2441 BaseQuals.removeObjCGCAttr();
2442
2443 // CVR attributes from the base are picked up by members,
2444 // except that 'mutable' members don't pick up 'const'.
2445 if (Field->isMutable()) BaseQuals.removeConst();
2446
2447 Qualifiers MemberQuals
2448 = S.Context.getCanonicalType(MemberType).getQualifiers();
2449
2450 // TR 18037 does not allow fields to be declared with address spaces.
2451 assert(!MemberQuals.hasAddressSpace());
2452
2453 Qualifiers Combined = BaseQuals + MemberQuals;
2454 if (Combined != MemberQuals)
2455 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2456 }
2457
2458 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
John Wiegley01296292011-04-08 18:41:53 +00002459 ExprResult Base =
2460 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2461 FoundDecl, Field);
2462 if (Base.isInvalid())
John McCallfeb624a2010-11-23 20:48:44 +00002463 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00002464 return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
John McCallfeb624a2010-11-23 20:48:44 +00002465 Field, FoundDecl, MemberNameInfo,
2466 MemberType, VK, OK));
2467}
2468
John McCall2d74de92009-12-01 22:10:20 +00002469/// Builds an implicit member access expression. The current context
2470/// is known to be an instance method, and the given unqualified lookup
2471/// set is known to contain only instance members, at least one of which
2472/// is from an appropriate type.
John McCalldadc5752010-08-24 06:29:42 +00002473ExprResult
John McCall2d74de92009-12-01 22:10:20 +00002474Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2475 LookupResult &R,
2476 const TemplateArgumentListInfo *TemplateArgs,
2477 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00002478 assert(!R.empty() && !R.isAmbiguous());
2479
John McCallf3a88602011-02-03 08:15:49 +00002480 SourceLocation loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00002481
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002482 // We may have found a field within an anonymous union or struct
2483 // (C++ [class.union]).
John McCalle66edc12009-11-24 19:00:30 +00002484 // FIXME: template-ids inside anonymous structs?
Francois Pichet783dd6e2010-11-21 06:08:52 +00002485 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCallf3a88602011-02-03 08:15:49 +00002486 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002487
John McCallf3a88602011-02-03 08:15:49 +00002488 // If this is known to be an instance access, go ahead and build an
2489 // implicit 'this' expression now.
John McCall2d74de92009-12-01 22:10:20 +00002490 // 'this' expression now.
Richard Smith938f40b2011-06-11 17:19:42 +00002491 QualType ThisTy = getAndCaptureCurrentThisType();
2492 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
John McCallf3a88602011-02-03 08:15:49 +00002493
John McCallf3a88602011-02-03 08:15:49 +00002494 Expr *baseExpr = 0; // null signifies implicit access
John McCall2d74de92009-12-01 22:10:20 +00002495 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00002496 SourceLocation Loc = R.getNameLoc();
2497 if (SS.getRange().isValid())
2498 Loc = SS.getRange().getBegin();
Richard Smith938f40b2011-06-11 17:19:42 +00002499 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002500 }
2501
Richard Smith938f40b2011-06-11 17:19:42 +00002502 return BuildMemberReferenceExpr(baseExpr, ThisTy,
John McCall2d74de92009-12-01 22:10:20 +00002503 /*OpLoc*/ SourceLocation(),
2504 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00002505 SS,
2506 /*FirstQualifierInScope*/ 0,
2507 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00002508}
2509
John McCalle66edc12009-11-24 19:00:30 +00002510bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002511 const LookupResult &R,
2512 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002513 // Only when used directly as the postfix-expression of a call.
2514 if (!HasTrailingLParen)
2515 return false;
2516
2517 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002518 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002519 return false;
2520
2521 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002522 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002523 return false;
2524
2525 // Turn off ADL when we find certain kinds of declarations during
2526 // normal lookup:
2527 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2528 NamedDecl *D = *I;
2529
2530 // C++0x [basic.lookup.argdep]p3:
2531 // -- a declaration of a class member
2532 // Since using decls preserve this property, we check this on the
2533 // original decl.
John McCall57500772009-12-16 12:17:52 +00002534 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002535 return false;
2536
2537 // C++0x [basic.lookup.argdep]p3:
2538 // -- a block-scope function declaration that is not a
2539 // using-declaration
2540 // NOTE: we also trigger this for function templates (in fact, we
2541 // don't check the decl type at all, since all other decl types
2542 // turn off ADL anyway).
2543 if (isa<UsingShadowDecl>(D))
2544 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2545 else if (D->getDeclContext()->isFunctionOrMethod())
2546 return false;
2547
2548 // C++0x [basic.lookup.argdep]p3:
2549 // -- a declaration that is neither a function or a function
2550 // template
2551 // And also for builtin functions.
2552 if (isa<FunctionDecl>(D)) {
2553 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2554
2555 // But also builtin functions.
2556 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2557 return false;
2558 } else if (!isa<FunctionTemplateDecl>(D))
2559 return false;
2560 }
2561
2562 return true;
2563}
2564
2565
John McCalld14a8642009-11-21 08:51:07 +00002566/// Diagnoses obvious problems with the use of the given declaration
2567/// as an expression. This is only actually called for lookups that
2568/// were not overloaded, and it doesn't promise that the declaration
2569/// will in fact be used.
2570static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002571 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002572 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2573 return true;
2574 }
2575
2576 if (isa<ObjCInterfaceDecl>(D)) {
2577 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2578 return true;
2579 }
2580
2581 if (isa<NamespaceDecl>(D)) {
2582 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2583 return true;
2584 }
2585
2586 return false;
2587}
2588
John McCalldadc5752010-08-24 06:29:42 +00002589ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002590Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002591 LookupResult &R,
2592 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002593 // If this is a single, fully-resolved result and we don't need ADL,
2594 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002595 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002596 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2597 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002598
2599 // We only need to check the declaration if there's exactly one
2600 // result, because in the overloaded case the results can only be
2601 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002602 if (R.isSingleResult() &&
2603 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002604 return ExprError();
2605
John McCall58cc69d2010-01-27 01:50:18 +00002606 // Otherwise, just build an unresolved lookup expression. Suppress
2607 // any lookup-related diagnostics; we'll hash these out later, when
2608 // we've picked a target.
2609 R.suppressDiagnostics();
2610
John McCalld14a8642009-11-21 08:51:07 +00002611 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002612 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002613 SS.getWithLocInContext(Context),
2614 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002615 NeedsADL, R.isOverloadedResult(),
2616 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002617
2618 return Owned(ULE);
2619}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002620
John McCalld14a8642009-11-21 08:51:07 +00002621/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002622ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002623Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002624 const DeclarationNameInfo &NameInfo,
2625 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002626 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002627 assert(!isa<FunctionTemplateDecl>(D) &&
2628 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002629
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002630 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002631 if (CheckDeclInExpr(*this, Loc, D))
2632 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002633
Douglas Gregore7488b92009-12-01 16:58:18 +00002634 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2635 // Specifically diagnose references to class templates that are missing
2636 // a template argument list.
2637 Diag(Loc, diag::err_template_decl_ref)
2638 << Template << SS.getRange();
2639 Diag(Template->getLocation(), diag::note_template_decl_here);
2640 return ExprError();
2641 }
2642
2643 // Make sure that we're referring to a value.
2644 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2645 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002646 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002647 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002648 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002649 return ExprError();
2650 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002651
Douglas Gregor171c45a2009-02-18 21:56:37 +00002652 // Check whether this declaration can be used. Note that we suppress
2653 // this check when we're going to perform argument-dependent lookup
2654 // on this function name, because this might not be the function
2655 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002656 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002657 return ExprError();
2658
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002659 // Only create DeclRefExpr's for valid Decl's.
2660 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002661 return ExprError();
2662
John McCallf3a88602011-02-03 08:15:49 +00002663 // Handle members of anonymous structs and unions. If we got here,
2664 // and the reference is to a class member indirect field, then this
2665 // must be the subject of a pointer-to-member expression.
2666 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2667 if (!indirectField->isCXXClassMember())
2668 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2669 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002670
Chris Lattner2a9d9892008-10-20 05:16:36 +00002671 // If the identifier reference is inside a block, and it refers to a value
2672 // that is outside the block, create a BlockDeclRefExpr instead of a
2673 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2674 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002675 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002676 // We do not do this for things like enum constants, global variables, etc,
2677 // as they do not get snapshotted.
2678 //
John McCall351762c2011-02-07 10:33:21 +00002679 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002680 case CR_Error:
2681 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002682
John McCallc63de662011-02-02 13:00:07 +00002683 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002684 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2685 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2686
2687 case CR_CaptureByRef:
2688 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2689 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002690
2691 case CR_NoCapture: {
2692 // If this reference is not in a block or if the referenced
2693 // variable is within the block, create a normal DeclRefExpr.
2694
2695 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002696 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002697
2698 switch (D->getKind()) {
2699 // Ignore all the non-ValueDecl kinds.
2700#define ABSTRACT_DECL(kind)
2701#define VALUE(type, base)
2702#define DECL(type, base) \
2703 case Decl::type:
2704#include "clang/AST/DeclNodes.inc"
2705 llvm_unreachable("invalid value decl kind");
2706 return ExprError();
2707
2708 // These shouldn't make it here.
2709 case Decl::ObjCAtDefsField:
2710 case Decl::ObjCIvar:
2711 llvm_unreachable("forming non-member reference to ivar?");
2712 return ExprError();
2713
2714 // Enum constants are always r-values and never references.
2715 // Unresolved using declarations are dependent.
2716 case Decl::EnumConstant:
2717 case Decl::UnresolvedUsingValue:
2718 valueKind = VK_RValue;
2719 break;
2720
2721 // Fields and indirect fields that got here must be for
2722 // pointer-to-member expressions; we just call them l-values for
2723 // internal consistency, because this subexpression doesn't really
2724 // exist in the high-level semantics.
2725 case Decl::Field:
2726 case Decl::IndirectField:
2727 assert(getLangOptions().CPlusPlus &&
2728 "building reference to field in C?");
2729
2730 // These can't have reference type in well-formed programs, but
2731 // for internal consistency we do this anyway.
2732 type = type.getNonReferenceType();
2733 valueKind = VK_LValue;
2734 break;
2735
2736 // Non-type template parameters are either l-values or r-values
2737 // depending on the type.
2738 case Decl::NonTypeTemplateParm: {
2739 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2740 type = reftype->getPointeeType();
2741 valueKind = VK_LValue; // even if the parameter is an r-value reference
2742 break;
2743 }
2744
2745 // For non-references, we need to strip qualifiers just in case
2746 // the template parameter was declared as 'const int' or whatever.
2747 valueKind = VK_RValue;
2748 type = type.getUnqualifiedType();
2749 break;
2750 }
2751
2752 case Decl::Var:
2753 // In C, "extern void blah;" is valid and is an r-value.
2754 if (!getLangOptions().CPlusPlus &&
2755 !type.hasQualifiers() &&
2756 type->isVoidType()) {
2757 valueKind = VK_RValue;
2758 break;
2759 }
2760 // fallthrough
2761
2762 case Decl::ImplicitParam:
2763 case Decl::ParmVar:
2764 // These are always l-values.
2765 valueKind = VK_LValue;
2766 type = type.getNonReferenceType();
2767 break;
2768
2769 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002770 const FunctionType *fty = type->castAs<FunctionType>();
2771
2772 // If we're referring to a function with an __unknown_anytype
2773 // result type, make the entire expression __unknown_anytype.
2774 if (fty->getResultType() == Context.UnknownAnyTy) {
2775 type = Context.UnknownAnyTy;
2776 valueKind = VK_RValue;
2777 break;
2778 }
2779
John McCallf4cd4f92011-02-09 01:13:10 +00002780 // Functions are l-values in C++.
2781 if (getLangOptions().CPlusPlus) {
2782 valueKind = VK_LValue;
2783 break;
2784 }
2785
2786 // C99 DR 316 says that, if a function type comes from a
2787 // function definition (without a prototype), that type is only
2788 // used for checking compatibility. Therefore, when referencing
2789 // the function, we pretend that we don't have the full function
2790 // type.
John McCall2979fe02011-04-12 00:42:48 +00002791 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2792 isa<FunctionProtoType>(fty))
2793 type = Context.getFunctionNoProtoType(fty->getResultType(),
2794 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002795
2796 // Functions are r-values in C.
2797 valueKind = VK_RValue;
2798 break;
2799 }
2800
2801 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002802 // If we're referring to a method with an __unknown_anytype
2803 // result type, make the entire expression __unknown_anytype.
2804 // This should only be possible with a type written directly.
2805 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(VD->getType()))
2806 if (proto->getResultType() == Context.UnknownAnyTy) {
2807 type = Context.UnknownAnyTy;
2808 valueKind = VK_RValue;
2809 break;
2810 }
2811
John McCallf4cd4f92011-02-09 01:13:10 +00002812 // C++ methods are l-values if static, r-values if non-static.
2813 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2814 valueKind = VK_LValue;
2815 break;
2816 }
2817 // fallthrough
2818
2819 case Decl::CXXConversion:
2820 case Decl::CXXDestructor:
2821 case Decl::CXXConstructor:
2822 valueKind = VK_RValue;
2823 break;
2824 }
2825
2826 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2827 }
2828
John McCallc63de662011-02-02 13:00:07 +00002829 }
John McCall7decc9e2010-11-18 06:31:45 +00002830
John McCall351762c2011-02-07 10:33:21 +00002831 llvm_unreachable("unknown capture result");
2832 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002833}
Chris Lattnere168f762006-11-10 05:29:30 +00002834
John McCall2979fe02011-04-12 00:42:48 +00002835ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002836 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002837
Chris Lattnere168f762006-11-10 05:29:30 +00002838 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002839 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002840 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2841 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2842 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002843 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002844
Chris Lattnera81a0272008-01-12 08:14:25 +00002845 // Pre-defined identifiers are of type char[x], where x is the length of the
2846 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002847
Anders Carlsson2fb08242009-09-08 18:24:21 +00002848 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002849 if (!currentDecl && getCurBlock())
2850 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002851 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002852 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002853 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002854 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002855
Anders Carlsson0b209a82009-09-11 01:22:35 +00002856 QualType ResTy;
2857 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2858 ResTy = Context.DependentTy;
2859 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002860 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002861
Anders Carlsson0b209a82009-09-11 01:22:35 +00002862 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002863 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002864 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2865 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002866 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002867}
2868
John McCalldadc5752010-08-24 06:29:42 +00002869ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002870 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002871 bool Invalid = false;
2872 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2873 if (Invalid)
2874 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002875
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002876 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2877 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002878 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002879 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002880
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002881 QualType Ty;
2882 if (!getLangOptions().CPlusPlus)
2883 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2884 else if (Literal.isWide())
2885 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002886 else if (Literal.isMultiChar())
2887 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002888 else
2889 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002890
Sebastian Redl20614a72009-01-20 22:23:13 +00002891 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2892 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002893 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002894}
2895
John McCalldadc5752010-08-24 06:29:42 +00002896ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002897 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002898 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2899 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002900 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002901 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002902 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002903 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002904 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002905
Chris Lattner23b7eb62007-06-15 23:05:46 +00002906 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002907 // Add padding so that NumericLiteralParser can overread by one character.
2908 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002909 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002910
Chris Lattner67ca9252007-05-21 01:08:44 +00002911 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002912 bool Invalid = false;
2913 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2914 if (Invalid)
2915 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002916
Mike Stump11289f42009-09-09 15:08:12 +00002917 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002918 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002919 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002920 return ExprError();
2921
Chris Lattner1c20a172007-08-26 03:42:43 +00002922 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002923
Chris Lattner1c20a172007-08-26 03:42:43 +00002924 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002925 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002926 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002927 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002928 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002929 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002930 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002931 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002932
2933 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2934
John McCall53b93a02009-12-24 09:08:04 +00002935 using llvm::APFloat;
2936 APFloat Val(Format);
2937
2938 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002939
2940 // Overflow is always an error, but underflow is only an error if
2941 // we underflowed to zero (APFloat reports denormals as underflow).
2942 if ((result & APFloat::opOverflow) ||
2943 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002944 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002945 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002946 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002947 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002948 APFloat::getLargest(Format).toString(buffer);
2949 } else {
John McCall62abc942010-02-26 23:35:57 +00002950 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002951 APFloat::getSmallest(Format).toString(buffer);
2952 }
2953
2954 Diag(Tok.getLocation(), diagnostic)
2955 << Ty
2956 << llvm::StringRef(buffer.data(), buffer.size());
2957 }
2958
2959 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002960 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002961
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002962 if (Ty == Context.DoubleTy) {
2963 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002964 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002965 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2966 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002967 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002968 }
2969 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002970 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002971 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002972 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002973 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002974
Neil Boothac582c52007-08-29 22:00:19 +00002975 // long long is a C99 feature.
2976 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002977 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002978 Diag(Tok.getLocation(), diag::ext_longlong);
2979
Chris Lattner67ca9252007-05-21 01:08:44 +00002980 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002981 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002982
Chris Lattner67ca9252007-05-21 01:08:44 +00002983 if (Literal.GetIntegerValue(ResultVal)) {
2984 // If this value didn't fit into uintmax_t, warn and force to ull.
2985 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002986 Ty = Context.UnsignedLongLongTy;
2987 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002988 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002989 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002990 // If this value fits into a ULL, try to figure out what else it fits into
2991 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002992
Chris Lattner67ca9252007-05-21 01:08:44 +00002993 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2994 // be an unsigned int.
2995 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2996
2997 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002998 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002999 if (!Literal.isLong && !Literal.isLongLong) {
3000 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00003001 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003002
Chris Lattner67ca9252007-05-21 01:08:44 +00003003 // Does it fit in a unsigned int?
3004 if (ResultVal.isIntN(IntSize)) {
3005 // Does it fit in a signed int?
3006 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003007 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00003008 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003009 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00003010 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00003011 }
Chris Lattner67ca9252007-05-21 01:08:44 +00003012 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003013
Chris Lattner67ca9252007-05-21 01:08:44 +00003014 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003015 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00003016 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003017
Chris Lattner67ca9252007-05-21 01:08:44 +00003018 // Does it fit in a unsigned long?
3019 if (ResultVal.isIntN(LongSize)) {
3020 // Does it fit in a signed long?
3021 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003022 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00003023 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003024 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00003025 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00003026 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003027 }
3028
Chris Lattner67ca9252007-05-21 01:08:44 +00003029 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003030 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00003031 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003032
Chris Lattner67ca9252007-05-21 01:08:44 +00003033 // Does it fit in a unsigned long long?
3034 if (ResultVal.isIntN(LongLongSize)) {
3035 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00003036 // To be compatible with MSVC, hex integer literals ending with the
3037 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00003038 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3039 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003040 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00003041 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003042 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00003043 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00003044 }
3045 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003046
Chris Lattner67ca9252007-05-21 01:08:44 +00003047 // If we still couldn't decide a type, we probably have something that
3048 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003049 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00003050 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003051 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00003052 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00003053 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003054
Chris Lattner55258cf2008-05-09 05:59:00 +00003055 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00003056 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00003057 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003058 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00003059 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003060
Chris Lattner1c20a172007-08-26 03:42:43 +00003061 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3062 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00003063 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00003064 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00003065
3066 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00003067}
3068
John McCalldadc5752010-08-24 06:29:42 +00003069ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00003070 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003071 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00003072 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00003073}
3074
Chandler Carruth62da79c2011-05-26 08:53:12 +00003075static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3076 SourceLocation Loc,
3077 SourceRange ArgRange) {
3078 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3079 // scalar or vector data type argument..."
3080 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3081 // type (C99 6.2.5p18) or void.
3082 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3083 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3084 << T << ArgRange;
3085 return true;
3086 }
3087
3088 assert((T->isVoidType() || !T->isIncompleteType()) &&
3089 "Scalar types should always be complete");
3090 return false;
3091}
3092
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003093static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3094 SourceLocation Loc,
3095 SourceRange ArgRange,
3096 UnaryExprOrTypeTrait TraitKind) {
3097 // C99 6.5.3.4p1:
3098 if (T->isFunctionType()) {
3099 // alignof(function) is allowed as an extension.
3100 if (TraitKind == UETT_SizeOf)
3101 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
3102 return false;
3103 }
3104
3105 // Allow sizeof(void)/alignof(void) as an extension.
3106 if (T->isVoidType()) {
3107 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
3108 return false;
3109 }
3110
3111 return true;
3112}
3113
3114static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3115 SourceLocation Loc,
3116 SourceRange ArgRange,
3117 UnaryExprOrTypeTrait TraitKind) {
3118 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
3119 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
3120 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3121 << T << (TraitKind == UETT_SizeOf)
3122 << ArgRange;
3123 return true;
3124 }
3125
3126 return false;
3127}
3128
Chandler Carruth14502c22011-05-26 08:53:10 +00003129/// \brief Check the constrains on expression operands to unary type expression
3130/// and type traits.
3131///
Chandler Carruth7c430c02011-05-27 01:33:31 +00003132/// Completes any types necessary and validates the constraints on the operand
3133/// expression. The logic mostly mirrors the type-based overload, but may modify
3134/// the expression as it completes the type for that expression through template
3135/// instantiation, etc.
Chandler Carruth14502c22011-05-26 08:53:10 +00003136bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op,
3137 UnaryExprOrTypeTrait ExprKind) {
Chandler Carruth7c430c02011-05-27 01:33:31 +00003138 QualType ExprTy = Op->getType();
3139
3140 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3141 // the result is the size of the referenced type."
3142 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3143 // result shall be the alignment of the referenced type."
3144 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3145 ExprTy = Ref->getPointeeType();
3146
3147 if (ExprKind == UETT_VecStep)
3148 return CheckVecStepTraitOperandType(*this, ExprTy, Op->getExprLoc(),
3149 Op->getSourceRange());
3150
3151 // Whitelist some types as extensions
3152 if (!CheckExtensionTraitOperandType(*this, ExprTy, Op->getExprLoc(),
3153 Op->getSourceRange(), ExprKind))
3154 return false;
3155
3156 if (RequireCompleteExprType(Op,
3157 PDiag(diag::err_sizeof_alignof_incomplete_type)
3158 << ExprKind << Op->getSourceRange(),
3159 std::make_pair(SourceLocation(), PDiag(0))))
3160 return true;
3161
3162 // Completeing the expression's type may have changed it.
3163 ExprTy = Op->getType();
3164 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3165 ExprTy = Ref->getPointeeType();
3166
3167 if (CheckObjCTraitOperandConstraints(*this, ExprTy, Op->getExprLoc(),
3168 Op->getSourceRange(), ExprKind))
3169 return true;
3170
Nico Weber0870deb2011-06-15 02:47:03 +00003171 if (ExprKind == UETT_SizeOf) {
3172 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Op->IgnoreParens())) {
3173 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3174 QualType OType = PVD->getOriginalType();
3175 QualType Type = PVD->getType();
3176 if (Type->isPointerType() && OType->isArrayType()) {
3177 Diag(Op->getExprLoc(), diag::warn_sizeof_array_param)
3178 << Type << OType;
3179 Diag(PVD->getLocation(), diag::note_declared_at);
3180 }
3181 }
3182 }
3183 }
3184
Chandler Carruth7c430c02011-05-27 01:33:31 +00003185 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00003186}
3187
3188/// \brief Check the constraints on operands to unary expression and type
3189/// traits.
3190///
3191/// This will complete any types necessary, and validate the various constraints
3192/// on those operands.
3193///
Steve Naroff71b59a92007-06-04 22:22:31 +00003194/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00003195/// C99 6.3.2.1p[2-4] all state:
3196/// Except when it is the operand of the sizeof operator ...
3197///
3198/// C++ [expr.sizeof]p4
3199/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3200/// standard conversions are not applied to the operand of sizeof.
3201///
3202/// This policy is followed for all of the unary trait expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003203bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
3204 SourceLocation OpLoc,
3205 SourceRange ExprRange,
3206 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003207 if (exprType->isDependentType())
3208 return false;
3209
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003210 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3211 // the result is the size of the referenced type."
3212 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3213 // result shall be the alignment of the referenced type."
3214 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
3215 exprType = Ref->getPointeeType();
3216
Chandler Carruth62da79c2011-05-26 08:53:12 +00003217 if (ExprKind == UETT_VecStep)
3218 return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003219
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003220 // Whitelist some types as extensions
3221 if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange,
3222 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00003223 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003224
Chris Lattner62975a72009-04-24 00:30:45 +00003225 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00003226 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00003227 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00003228 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003229
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003230 if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange,
3231 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00003232 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003233
Chris Lattner62975a72009-04-24 00:30:45 +00003234 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00003235}
3236
Chandler Carruth14502c22011-05-26 08:53:10 +00003237static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00003238 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003239
Mike Stump11289f42009-09-09 15:08:12 +00003240 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00003241 if (isa<DeclRefExpr>(E))
3242 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003243
3244 // Cannot know anything else if the expression is dependent.
3245 if (E->isTypeDependent())
3246 return false;
3247
Douglas Gregor71235ec2009-05-02 02:18:30 +00003248 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003249 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3250 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003251 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00003252 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00003253
3254 // Alignment of a field access is always okay, so long as it isn't a
3255 // bit-field.
3256 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00003257 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003258 return false;
3259
Chandler Carruth14502c22011-05-26 08:53:10 +00003260 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003261}
3262
Chandler Carruth14502c22011-05-26 08:53:10 +00003263bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00003264 E = E->IgnoreParens();
3265
3266 // Cannot know anything else if the expression is dependent.
3267 if (E->isTypeDependent())
3268 return false;
3269
Chandler Carruth14502c22011-05-26 08:53:10 +00003270 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00003271}
3272
Douglas Gregor0950e412009-03-13 21:01:28 +00003273/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00003274ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003275Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3276 SourceLocation OpLoc,
3277 UnaryExprOrTypeTrait ExprKind,
3278 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00003279 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00003280 return ExprError();
3281
John McCallbcd03502009-12-07 02:54:59 +00003282 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00003283
Douglas Gregor0950e412009-03-13 21:01:28 +00003284 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00003285 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00003286 return ExprError();
3287
3288 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003289 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3290 Context.getSizeType(),
3291 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003292}
3293
3294/// \brief Build a sizeof or alignof expression given an expression
3295/// operand.
John McCalldadc5752010-08-24 06:29:42 +00003296ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00003297Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3298 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor0950e412009-03-13 21:01:28 +00003299 // Verify that the operand is valid.
3300 bool isInvalid = false;
3301 if (E->isTypeDependent()) {
3302 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003303 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003304 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003305 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003306 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00003307 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00003308 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00003309 isInvalid = true;
John McCall36226622010-10-12 02:09:17 +00003310 } else if (E->getType()->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00003311 ExprResult PE = CheckPlaceholderExpr(E);
John McCall36226622010-10-12 02:09:17 +00003312 if (PE.isInvalid()) return ExprError();
Chandler Carrutha923fb22011-05-29 07:32:14 +00003313 return CreateUnaryExprOrTypeTraitExpr(PE.take(), OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00003314 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00003315 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00003316 }
3317
3318 if (isInvalid)
3319 return ExprError();
3320
3321 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00003322 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00003323 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00003324 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003325}
3326
Peter Collingbournee190dee2011-03-11 19:24:49 +00003327/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3328/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00003329/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00003330ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003331Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3332 UnaryExprOrTypeTrait ExprKind, bool isType,
3333 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00003334 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003335 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00003336
Sebastian Redl6f282892008-11-11 17:56:53 +00003337 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00003338 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00003339 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003340 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00003341 }
Sebastian Redl6f282892008-11-11 17:56:53 +00003342
Douglas Gregor0950e412009-03-13 21:01:28 +00003343 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00003344 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00003345 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00003346}
3347
John Wiegley01296292011-04-08 18:41:53 +00003348static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall4bc41ae2010-11-18 19:01:18 +00003349 bool isReal) {
John Wiegley01296292011-04-08 18:41:53 +00003350 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00003351 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00003352
John McCall34376a62010-12-04 03:47:34 +00003353 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00003354 if (V.get()->getObjectKind() != OK_Ordinary) {
3355 V = S.DefaultLvalueConversion(V.take());
3356 if (V.isInvalid())
3357 return QualType();
3358 }
John McCall34376a62010-12-04 03:47:34 +00003359
Chris Lattnere267f5d2007-08-26 05:39:26 +00003360 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00003361 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00003362 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00003363
Chris Lattnere267f5d2007-08-26 05:39:26 +00003364 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00003365 if (V.get()->getType()->isArithmeticType())
3366 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003367
John McCall36226622010-10-12 02:09:17 +00003368 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00003369 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00003370 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003371 if (PR.get() != V.get()) {
3372 V = move(PR);
John McCall4bc41ae2010-11-18 19:01:18 +00003373 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00003374 }
3375
Chris Lattnere267f5d2007-08-26 05:39:26 +00003376 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003377 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00003378 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003379 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003380}
3381
3382
Chris Lattnere168f762006-11-10 05:29:30 +00003383
John McCalldadc5752010-08-24 06:29:42 +00003384ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003385Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003386 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003387 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003388 switch (Kind) {
3389 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003390 case tok::plusplus: Opc = UO_PostInc; break;
3391 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003392 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003393
John McCallb268a282010-08-23 23:25:46 +00003394 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003395}
3396
John McCall4bc41ae2010-11-18 19:01:18 +00003397/// Expressions of certain arbitrary types are forbidden by C from
3398/// having l-value type. These are:
3399/// - 'void', but not qualified void
3400/// - function types
3401///
3402/// The exact rule here is C99 6.3.2.1:
3403/// An lvalue is an expression with an object type or an incomplete
3404/// type other than void.
3405static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
3406 return ((T->isVoidType() && !T.hasQualifiers()) ||
3407 T->isFunctionType());
3408}
3409
John McCalldadc5752010-08-24 06:29:42 +00003410ExprResult
John McCallb268a282010-08-23 23:25:46 +00003411Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3412 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003413 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003414 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003415 if (Result.isInvalid()) return ExprError();
3416 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003417
John McCallb268a282010-08-23 23:25:46 +00003418 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003419
Douglas Gregor40412ac2008-11-19 17:17:41 +00003420 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003421 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003422 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003423 Context.DependentTy,
3424 VK_LValue, OK_Ordinary,
3425 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003426 }
3427
Mike Stump11289f42009-09-09 15:08:12 +00003428 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003429 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003430 LHSExp->getType()->isEnumeralType() ||
3431 RHSExp->getType()->isRecordType() ||
3432 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00003433 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003434 }
3435
John McCallb268a282010-08-23 23:25:46 +00003436 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003437}
3438
3439
John McCalldadc5752010-08-24 06:29:42 +00003440ExprResult
John McCallb268a282010-08-23 23:25:46 +00003441Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3442 Expr *Idx, SourceLocation RLoc) {
3443 Expr *LHSExp = Base;
3444 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003445
Chris Lattner36d572b2007-07-16 00:14:47 +00003446 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003447 if (!LHSExp->getType()->getAs<VectorType>()) {
3448 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3449 if (Result.isInvalid())
3450 return ExprError();
3451 LHSExp = Result.take();
3452 }
3453 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3454 if (Result.isInvalid())
3455 return ExprError();
3456 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003457
Chris Lattner36d572b2007-07-16 00:14:47 +00003458 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003459 ExprValueKind VK = VK_LValue;
3460 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003461
Steve Naroffc1aadb12007-03-28 21:49:40 +00003462 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003463 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003464 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003465 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003466 Expr *BaseExpr, *IndexExpr;
3467 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003468 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3469 BaseExpr = LHSExp;
3470 IndexExpr = RHSExp;
3471 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003472 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003473 BaseExpr = LHSExp;
3474 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003475 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003476 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003477 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003478 BaseExpr = RHSExp;
3479 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003480 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003481 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003482 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003483 BaseExpr = LHSExp;
3484 IndexExpr = RHSExp;
3485 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003486 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003487 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003488 // Handle the uncommon case of "123[Ptr]".
3489 BaseExpr = RHSExp;
3490 IndexExpr = LHSExp;
3491 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003492 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003493 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003494 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003495 VK = LHSExp->getValueKind();
3496 if (VK != VK_RValue)
3497 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003498
Chris Lattner36d572b2007-07-16 00:14:47 +00003499 // FIXME: need to deal with const...
3500 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003501 } else if (LHSTy->isArrayType()) {
3502 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003503 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003504 // wasn't promoted because of the C90 rule that doesn't
3505 // allow promoting non-lvalue arrays. Warn, then
3506 // force the promotion here.
3507 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3508 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003509 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3510 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003511 LHSTy = LHSExp->getType();
3512
3513 BaseExpr = LHSExp;
3514 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003515 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003516 } else if (RHSTy->isArrayType()) {
3517 // Same as previous, except for 123[f().a] case
3518 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3519 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003520 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3521 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003522 RHSTy = RHSExp->getType();
3523
3524 BaseExpr = RHSExp;
3525 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003526 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003527 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003528 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3529 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003530 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003531 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003532 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003533 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3534 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003535
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003536 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003537 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3538 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003539 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3540
Douglas Gregorac1fb652009-03-24 19:52:54 +00003541 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003542 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3543 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003544 // incomplete types are not object types.
3545 if (ResultType->isFunctionType()) {
3546 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3547 << ResultType << BaseExpr->getSourceRange();
3548 return ExprError();
3549 }
Mike Stump11289f42009-09-09 15:08:12 +00003550
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003551 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3552 // GNU extension: subscripting on pointer to void
3553 Diag(LLoc, diag::ext_gnu_void_ptr)
3554 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003555
3556 // C forbids expressions of unqualified void type from being l-values.
3557 // See IsCForbiddenLValueType.
3558 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003559 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003560 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003561 PDiag(diag::err_subscript_incomplete_type)
3562 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003563 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003564
Chris Lattner62975a72009-04-24 00:30:45 +00003565 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003566 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003567 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3568 << ResultType << BaseExpr->getSourceRange();
3569 return ExprError();
3570 }
Mike Stump11289f42009-09-09 15:08:12 +00003571
John McCall4bc41ae2010-11-18 19:01:18 +00003572 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3573 !IsCForbiddenLValueType(Context, ResultType));
3574
Mike Stump4e1f26a2009-02-19 03:04:26 +00003575 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003576 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003577}
3578
John McCall4bc41ae2010-11-18 19:01:18 +00003579/// Check an ext-vector component access expression.
3580///
3581/// VK should be set in advance to the value kind of the base
3582/// expression.
3583static QualType
3584CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3585 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00003586 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00003587 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3588 // see FIXME there.
3589 //
3590 // FIXME: This logic can be greatly simplified by splitting it along
3591 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00003592 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00003593
Steve Narofff8fd09e2007-07-27 22:15:19 +00003594 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003595 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003596
Mike Stump4e1f26a2009-02-19 03:04:26 +00003597 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00003598 // special names that indicate a subset of exactly half the elements are
3599 // to be selected.
3600 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003601
Nate Begemanbb70bf62009-01-18 01:47:54 +00003602 // This flag determines whether or not CompName has an 's' char prefix,
3603 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00003604 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00003605
John McCall4bc41ae2010-11-18 19:01:18 +00003606 bool HasRepeated = false;
3607 bool HasIndex[16] = {};
3608
3609 int Idx;
3610
Nate Begemanf322eab2008-05-09 06:41:27 +00003611 // Check that we've found one of the special components, or that the component
3612 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003613 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00003614 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3615 HalvingSwizzle = true;
John McCall4bc41ae2010-11-18 19:01:18 +00003616 } else if (!HexSwizzle &&
3617 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3618 do {
3619 if (HasIndex[Idx]) HasRepeated = true;
3620 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003621 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003622 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3623 } else {
3624 if (HexSwizzle) compStr++;
3625 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3626 if (HasIndex[Idx]) HasRepeated = true;
3627 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003628 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003629 }
Chris Lattner7e152db2007-08-02 22:33:49 +00003630 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00003631
Mike Stump4e1f26a2009-02-19 03:04:26 +00003632 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00003633 // We didn't get to the end of the string. This means the component names
3634 // didn't come from the same set *or* we encountered an illegal name.
John McCall4bc41ae2010-11-18 19:01:18 +00003635 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramere8394df2010-08-11 14:47:12 +00003636 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00003637 return QualType();
3638 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003639
Nate Begemanbb70bf62009-01-18 01:47:54 +00003640 // Ensure no component accessor exceeds the width of the vector type it
3641 // operates on.
3642 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003643 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003644
3645 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00003646 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00003647
3648 while (*compStr) {
3649 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall4bc41ae2010-11-18 19:01:18 +00003650 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begemanbb70bf62009-01-18 01:47:54 +00003651 << baseType << SourceRange(CompLoc);
3652 return QualType();
3653 }
3654 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00003655 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003656
Steve Narofff8fd09e2007-07-27 22:15:19 +00003657 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003658 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00003659 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00003660 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00003661 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00003662 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00003663 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003664 if (HexSwizzle)
3665 CompSize--;
3666
Steve Narofff8fd09e2007-07-27 22:15:19 +00003667 if (CompSize == 1)
3668 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003669
John McCall4bc41ae2010-11-18 19:01:18 +00003670 if (HasRepeated) VK = VK_RValue;
3671
3672 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003673 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00003674 // diagostics look bad. We want extended vector types to appear built-in.
John McCall4bc41ae2010-11-18 19:01:18 +00003675 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3676 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3677 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00003678 }
3679 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00003680}
3681
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003682static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00003683 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003684 const Selector &Sel,
3685 ASTContext &Context) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003686 if (Member)
3687 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3688 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003689 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003690 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00003691
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003692 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3693 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003694 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3695 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003696 return D;
3697 }
3698 return 0;
3699}
3700
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003701static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3702 IdentifierInfo *Member,
3703 const Selector &Sel,
3704 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003705 // Check protocols on qualified interfaces.
3706 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00003707 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003708 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003709 if (Member)
3710 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3711 GDecl = PD;
3712 break;
3713 }
3714 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003715 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003716 GDecl = OMD;
3717 break;
3718 }
3719 }
3720 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00003721 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003722 E = QIdTy->qual_end(); I != E; ++I) {
3723 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003724 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3725 Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003726 if (GDecl)
3727 return GDecl;
3728 }
3729 }
3730 return GDecl;
3731}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00003732
John McCalldadc5752010-08-24 06:29:42 +00003733ExprResult
John McCallb268a282010-08-23 23:25:46 +00003734Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCall2d74de92009-12-01 22:10:20 +00003735 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003736 const CXXScopeSpec &SS,
3737 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003738 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003739 const TemplateArgumentListInfo *TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00003740 // Even in dependent contexts, try to diagnose base expressions with
3741 // obviously wrong types, e.g.:
3742 //
3743 // T* t;
3744 // t.f;
3745 //
3746 // In Obj-C++, however, the above expression is valid, since it could be
3747 // accessing the 'f' property if T is an Obj-C interface. The extra check
3748 // allows this, while still reporting an error if T is a struct pointer.
3749 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00003750 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00003751 if (PT && (!getLangOptions().ObjC1 ||
3752 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00003753 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003754 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00003755 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00003756 return ExprError();
3757 }
3758 }
3759
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003760 assert(BaseType->isDependentType() ||
3761 NameInfo.getName().isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00003762 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00003763
3764 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3765 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00003766 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003767 IsArrow, OpLoc,
Douglas Gregore16af532011-02-28 18:50:33 +00003768 SS.getWithLocInContext(Context),
John McCall10eae182009-11-30 22:42:35 +00003769 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003770 NameInfo, TemplateArgs));
John McCall10eae182009-11-30 22:42:35 +00003771}
3772
3773/// We know that the given qualified member reference points only to
3774/// declarations which do not belong to the static type of the base
3775/// expression. Diagnose the problem.
3776static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3777 Expr *BaseExpr,
3778 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003779 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00003780 NamedDecl *rep,
3781 const DeclarationNameInfo &nameInfo) {
John McCallcd4b4772009-12-02 03:53:29 +00003782 // If this is an implicit member access, use a different set of
3783 // diagnostics.
3784 if (!BaseExpr)
John McCallf3a88602011-02-03 08:15:49 +00003785 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall10eae182009-11-30 22:42:35 +00003786
John McCallf3a88602011-02-03 08:15:49 +00003787 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3788 << SS.getRange() << rep << BaseType;
John McCall10eae182009-11-30 22:42:35 +00003789}
3790
3791// Check whether the declarations we found through a nested-name
3792// specifier in a member expression are actually members of the base
3793// type. The restriction here is:
3794//
3795// C++ [expr.ref]p2:
3796// ... In these cases, the id-expression shall name a
3797// member of the class or of one of its base classes.
3798//
3799// So it's perfectly legitimate for the nested-name specifier to name
3800// an unrelated class, and for us to find an overload set including
3801// decls from classes which are not superclasses, as long as the decl
3802// we actually pick through overload resolution is from a superclass.
3803bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3804 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003805 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003806 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00003807 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3808 if (!BaseRT) {
3809 // We can't check this yet because the base type is still
3810 // dependent.
3811 assert(BaseType->isDependentType());
3812 return false;
3813 }
3814 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00003815
3816 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00003817 // If this is an implicit member reference and we find a
3818 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00003819 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00003820 return false;
John McCall10eae182009-11-30 22:42:35 +00003821
John McCall2d74de92009-12-01 22:10:20 +00003822 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman75300492010-07-27 20:51:02 +00003823 DeclContext *DC = (*I)->getDeclContext();
3824 while (DC->isTransparentContext())
3825 DC = DC->getParent();
John McCall2d74de92009-12-01 22:10:20 +00003826
Douglas Gregora9c3e822010-07-28 22:27:52 +00003827 if (!DC->isRecord())
3828 continue;
3829
John McCall2d74de92009-12-01 22:10:20 +00003830 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman75300492010-07-27 20:51:02 +00003831 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCall2d74de92009-12-01 22:10:20 +00003832
3833 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3834 return false;
3835 }
3836
John McCallf3a88602011-02-03 08:15:49 +00003837 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3838 R.getRepresentativeDecl(),
3839 R.getLookupNameInfo());
John McCall2d74de92009-12-01 22:10:20 +00003840 return true;
3841}
3842
3843static bool
3844LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3845 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00003846 SourceLocation OpLoc, CXXScopeSpec &SS,
3847 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00003848 RecordDecl *RDecl = RTy->getDecl();
3849 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00003850 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00003851 << BaseRange))
3852 return true;
3853
John McCalle9cccd82010-06-16 08:42:20 +00003854 if (HasTemplateArgs) {
3855 // LookupTemplateName doesn't expect these both to exist simultaneously.
3856 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3857
3858 bool MOUS;
3859 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3860 return false;
3861 }
3862
John McCall2d74de92009-12-01 22:10:20 +00003863 DeclContext *DC = RDecl;
3864 if (SS.isSet()) {
3865 // If the member name was a qualified-id, look into the
3866 // nested-name-specifier.
3867 DC = SemaRef.computeDeclContext(SS, false);
3868
John McCall0b66eb32010-05-01 00:40:08 +00003869 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00003870 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3871 << SS.getRange() << DC;
3872 return true;
3873 }
3874
John McCall2d74de92009-12-01 22:10:20 +00003875 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003876
John McCall2d74de92009-12-01 22:10:20 +00003877 if (!isa<TypeDecl>(DC)) {
3878 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3879 << DC << SS.getRange();
3880 return true;
John McCall10eae182009-11-30 22:42:35 +00003881 }
3882 }
3883
John McCall2d74de92009-12-01 22:10:20 +00003884 // The record definition is complete, now look up the member.
3885 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00003886
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003887 if (!R.empty())
3888 return false;
3889
3890 // We didn't find anything with the given name, so try to correct
3891 // for typos.
3892 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00003893 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003894 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003895 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3896 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3897 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003898 << FixItHint::CreateReplacement(R.getNameLoc(),
3899 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003900 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3901 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3902 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003903 return false;
3904 } else {
3905 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003906 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003907 }
3908
John McCall10eae182009-11-30 22:42:35 +00003909 return false;
3910}
3911
John McCalldadc5752010-08-24 06:29:42 +00003912ExprResult
John McCallb268a282010-08-23 23:25:46 +00003913Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00003914 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003915 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003916 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003917 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003918 const TemplateArgumentListInfo *TemplateArgs) {
John McCallcd4b4772009-12-02 03:53:29 +00003919 if (BaseType->isDependentType() ||
3920 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallb268a282010-08-23 23:25:46 +00003921 return ActOnDependentMemberExpr(Base, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003922 IsArrow, OpLoc,
3923 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003924 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003925
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003926 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00003927
John McCall2d74de92009-12-01 22:10:20 +00003928 // Implicit member accesses.
3929 if (!Base) {
3930 QualType RecordTy = BaseType;
3931 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3932 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3933 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00003934 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00003935 return ExprError();
3936
3937 // Explicit member accesses.
3938 } else {
John Wiegley01296292011-04-08 18:41:53 +00003939 ExprResult BaseResult = Owned(Base);
John McCalldadc5752010-08-24 06:29:42 +00003940 ExprResult Result =
John Wiegley01296292011-04-08 18:41:53 +00003941 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCall48871652010-08-21 09:40:31 +00003942 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00003943
John Wiegley01296292011-04-08 18:41:53 +00003944 if (BaseResult.isInvalid())
3945 return ExprError();
3946 Base = BaseResult.take();
3947
John McCall2d74de92009-12-01 22:10:20 +00003948 if (Result.isInvalid()) {
3949 Owned(Base);
3950 return ExprError();
3951 }
3952
3953 if (Result.get())
3954 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00003955
3956 // LookupMemberExpr can modify Base, and thus change BaseType
3957 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00003958 }
3959
John McCallb268a282010-08-23 23:25:46 +00003960 return BuildMemberReferenceExpr(Base, BaseType,
John McCall38836f02010-01-15 08:34:02 +00003961 OpLoc, IsArrow, SS, FirstQualifierInScope,
3962 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003963}
3964
John McCalldadc5752010-08-24 06:29:42 +00003965ExprResult
John McCallb268a282010-08-23 23:25:46 +00003966Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCall2d74de92009-12-01 22:10:20 +00003967 SourceLocation OpLoc, bool IsArrow,
3968 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00003969 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00003970 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00003971 const TemplateArgumentListInfo *TemplateArgs,
3972 bool SuppressQualifierCheck) {
John McCall2d74de92009-12-01 22:10:20 +00003973 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00003974 if (IsArrow) {
3975 assert(BaseType->isPointerType());
3976 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3977 }
John McCalla8ae2222010-04-06 21:38:20 +00003978 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00003979
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003980 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3981 DeclarationName MemberName = MemberNameInfo.getName();
3982 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall10eae182009-11-30 22:42:35 +00003983
3984 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00003985 return ExprError();
3986
John McCall10eae182009-11-30 22:42:35 +00003987 if (R.empty()) {
3988 // Rederive where we looked up.
3989 DeclContext *DC = (SS.isSet()
3990 ? computeDeclContext(SS, false)
3991 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00003992
John McCall10eae182009-11-30 22:42:35 +00003993 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00003994 << MemberName << DC
3995 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00003996 return ExprError();
3997 }
3998
John McCall38836f02010-01-15 08:34:02 +00003999 // Diagnose lookups that find only declarations from a non-base
4000 // type. This is possible for either qualified lookups (which may
4001 // have been qualified with an unrelated type) or implicit member
4002 // expressions (which were found with unqualified lookup and thus
4003 // may have come from an enclosing scope). Note that it's okay for
4004 // lookup to find declarations from a non-base type as long as those
4005 // aren't the ones picked by overload resolution.
4006 if ((SS.isSet() || !BaseExpr ||
4007 (isa<CXXThisExpr>(BaseExpr) &&
4008 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00004009 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00004010 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00004011 return ExprError();
4012
4013 // Construct an unresolved result if we in fact got an unresolved
4014 // result.
4015 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall58cc69d2010-01-27 01:50:18 +00004016 // Suppress any lookup-related diagnostics; we'll do these when we
4017 // pick a member.
4018 R.suppressDiagnostics();
4019
John McCall10eae182009-11-30 22:42:35 +00004020 UnresolvedMemberExpr *MemExpr
Douglas Gregora6e053e2010-12-15 01:34:56 +00004021 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00004022 BaseExpr, BaseExprType,
4023 IsArrow, OpLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00004024 SS.getWithLocInContext(Context),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004025 MemberNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00004026 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00004027
4028 return Owned(MemExpr);
4029 }
4030
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004031 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00004032 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00004033 NamedDecl *MemberDecl = R.getFoundDecl();
4034
4035 // FIXME: diagnose the presence of template arguments now.
4036
4037 // If the decl being referenced had an error, return an error for this
4038 // sub-expr without emitting another error, in order to avoid cascading
4039 // error cases.
4040 if (MemberDecl->isInvalidDecl())
4041 return ExprError();
4042
John McCall2d74de92009-12-01 22:10:20 +00004043 // Handle the implicit-member-access case.
4044 if (!BaseExpr) {
4045 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00004046 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004047 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCall2d74de92009-12-01 22:10:20 +00004048
Douglas Gregorb15af892010-01-07 23:12:05 +00004049 SourceLocation Loc = R.getNameLoc();
4050 if (SS.getRange().isValid())
4051 Loc = SS.getRange().getBegin();
4052 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00004053 }
4054
John McCall10eae182009-11-30 22:42:35 +00004055 bool ShouldCheckUse = true;
4056 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
4057 // Don't diagnose the use of a virtual member function unless it's
4058 // explicitly qualified.
4059 if (MD->isVirtual() && !SS.isSet())
4060 ShouldCheckUse = false;
4061 }
4062
4063 // Check the use of this member.
4064 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
4065 Owned(BaseExpr);
4066 return ExprError();
4067 }
4068
John McCall34376a62010-12-04 03:47:34 +00004069 // Perform a property load on the base regardless of whether we
4070 // actually need it for the declaration.
John Wiegley01296292011-04-08 18:41:53 +00004071 if (BaseExpr->getObjectKind() == OK_ObjCProperty) {
4072 ExprResult Result = ConvertPropertyForRValue(BaseExpr);
4073 if (Result.isInvalid())
4074 return ExprError();
4075 BaseExpr = Result.take();
4076 }
John McCall34376a62010-12-04 03:47:34 +00004077
John McCallfeb624a2010-11-23 20:48:44 +00004078 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
4079 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
4080 SS, FD, FoundDecl, MemberNameInfo);
John McCall10eae182009-11-30 22:42:35 +00004081
Francois Pichet783dd6e2010-11-21 06:08:52 +00004082 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
4083 // We may have found a field within an anonymous union or struct
4084 // (C++ [class.union]).
John McCallf3a88602011-02-03 08:15:49 +00004085 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCall34376a62010-12-04 03:47:34 +00004086 BaseExpr, OpLoc);
Francois Pichet783dd6e2010-11-21 06:08:52 +00004087
John McCall10eae182009-11-30 22:42:35 +00004088 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
4089 MarkDeclarationReferenced(MemberLoc, Var);
4090 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004091 Var, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00004092 Var->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00004093 VK_LValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00004094 }
4095
John McCall7decc9e2010-11-18 06:31:45 +00004096 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall0009fcc2011-04-26 20:42:42 +00004097 ExprValueKind valueKind;
4098 QualType type;
4099 if (MemberFn->isInstance()) {
4100 valueKind = VK_RValue;
4101 type = Context.BoundMemberTy;
4102 } else {
4103 valueKind = VK_LValue;
4104 type = MemberFn->getType();
4105 }
4106
John McCall10eae182009-11-30 22:42:35 +00004107 MarkDeclarationReferenced(MemberLoc, MemberDecl);
4108 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004109 MemberFn, FoundDecl, MemberNameInfo,
John McCall0009fcc2011-04-26 20:42:42 +00004110 type, valueKind, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00004111 }
John McCall7decc9e2010-11-18 06:31:45 +00004112 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall10eae182009-11-30 22:42:35 +00004113
4114 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
4115 MarkDeclarationReferenced(MemberLoc, MemberDecl);
4116 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004117 Enum, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00004118 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00004119 }
4120
4121 Owned(BaseExpr);
4122
Douglas Gregor861eb802010-04-25 20:55:08 +00004123 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00004124 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004125 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregor861eb802010-04-25 20:55:08 +00004126 << MemberName << BaseType << int(IsArrow);
4127 else
4128 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
4129 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00004130
Douglas Gregor861eb802010-04-25 20:55:08 +00004131 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
4132 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00004133 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00004134 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00004135}
4136
John McCall68fc88ec2010-12-15 16:46:44 +00004137/// Given that normal member access failed on the given expression,
4138/// and given that the expression's type involves builtin-id or
4139/// builtin-Class, decide whether substituting in the redefinition
4140/// types would be profitable. The redefinition type is whatever
4141/// this translation unit tried to typedef to id/Class; we store
4142/// it to the side and then re-use it in places like this.
John Wiegley01296292011-04-08 18:41:53 +00004143static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
John McCall68fc88ec2010-12-15 16:46:44 +00004144 const ObjCObjectPointerType *opty
John Wiegley01296292011-04-08 18:41:53 +00004145 = base.get()->getType()->getAs<ObjCObjectPointerType>();
John McCall68fc88ec2010-12-15 16:46:44 +00004146 if (!opty) return false;
4147
4148 const ObjCObjectType *ty = opty->getObjectType();
4149
4150 QualType redef;
4151 if (ty->isObjCId()) {
4152 redef = S.Context.ObjCIdRedefinitionType;
4153 } else if (ty->isObjCClass()) {
4154 redef = S.Context.ObjCClassRedefinitionType;
4155 } else {
4156 return false;
4157 }
4158
4159 // Do the substitution as long as the redefinition type isn't just a
4160 // possibly-qualified pointer to builtin-id or builtin-Class again.
4161 opty = redef->getAs<ObjCObjectPointerType>();
4162 if (opty && !opty->getObjectType()->getInterface() != 0)
4163 return false;
4164
John Wiegley01296292011-04-08 18:41:53 +00004165 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
John McCall68fc88ec2010-12-15 16:46:44 +00004166 return true;
4167}
4168
John McCall10eae182009-11-30 22:42:35 +00004169/// Look up the given member of the given non-type-dependent
4170/// expression. This can return in one of two ways:
4171/// * If it returns a sentinel null-but-valid result, the caller will
4172/// assume that lookup was performed and the results written into
4173/// the provided structure. It will take over from there.
4174/// * Otherwise, the returned expression will be produced in place of
4175/// an ordinary member expression.
4176///
4177/// The ObjCImpDecl bit is a gross hack that will need to be properly
4178/// fixed for ObjC++.
John McCalldadc5752010-08-24 06:29:42 +00004179ExprResult
John Wiegley01296292011-04-08 18:41:53 +00004180Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00004181 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004182 CXXScopeSpec &SS,
John McCall48871652010-08-21 09:40:31 +00004183 Decl *ObjCImpDecl, bool HasTemplateArgs) {
John Wiegley01296292011-04-08 18:41:53 +00004184 assert(BaseExpr.get() && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00004185
Steve Naroffeaaae462007-12-16 21:42:28 +00004186 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00004187 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004188
John Wiegley01296292011-04-08 18:41:53 +00004189 if (IsArrow) {
4190 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4191 if (BaseExpr.isInvalid())
4192 return ExprError();
4193 }
4194
4195 QualType BaseType = BaseExpr.get()->getType();
John McCall10eae182009-11-30 22:42:35 +00004196 assert(!BaseType->isDependentType());
4197
4198 DeclarationName MemberName = R.getLookupName();
4199 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00004200
John McCall68fc88ec2010-12-15 16:46:44 +00004201 // For later type-checking purposes, turn arrow accesses into dot
4202 // accesses. The only access type we support that doesn't follow
4203 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
4204 // and those never use arrows, so this is unaffected.
4205 if (IsArrow) {
4206 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4207 BaseType = Ptr->getPointeeType();
4208 else if (const ObjCObjectPointerType *Ptr
4209 = BaseType->getAs<ObjCObjectPointerType>())
4210 BaseType = Ptr->getPointeeType();
4211 else if (BaseType->isRecordType()) {
4212 // Recover from arrow accesses to records, e.g.:
4213 // struct MyRecord foo;
4214 // foo->bar
4215 // This is actually well-formed in C++ if MyRecord has an
4216 // overloaded operator->, but that should have been dealt with
4217 // by now.
4218 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley01296292011-04-08 18:41:53 +00004219 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
John McCall68fc88ec2010-12-15 16:46:44 +00004220 << FixItHint::CreateReplacement(OpLoc, ".");
4221 IsArrow = false;
John McCall0009fcc2011-04-26 20:42:42 +00004222 } else if (BaseType == Context.BoundMemberTy) {
4223 goto fail;
John McCall68fc88ec2010-12-15 16:46:44 +00004224 } else {
4225 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
John Wiegley01296292011-04-08 18:41:53 +00004226 << BaseType << BaseExpr.get()->getSourceRange();
John McCall68fc88ec2010-12-15 16:46:44 +00004227 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00004228 }
4229 }
4230
John McCall68fc88ec2010-12-15 16:46:44 +00004231 // Handle field access to simple records.
4232 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John Wiegley01296292011-04-08 18:41:53 +00004233 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
John McCall68fc88ec2010-12-15 16:46:44 +00004234 RTy, OpLoc, SS, HasTemplateArgs))
4235 return ExprError();
4236
4237 // Returning valid-but-null is how we indicate to the caller that
4238 // the lookup result was filled in.
4239 return Owned((Expr*) 0);
David Chisnall9f57c292009-08-17 16:35:33 +00004240 }
John McCall10eae182009-11-30 22:42:35 +00004241
John McCall68fc88ec2010-12-15 16:46:44 +00004242 // Handle ivar access to Objective-C objects.
4243 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004244 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall68fc88ec2010-12-15 16:46:44 +00004245
4246 // There are three cases for the base type:
4247 // - builtin id (qualified or unqualified)
4248 // - builtin Class (qualified or unqualified)
4249 // - an interface
4250 ObjCInterfaceDecl *IDecl = OTy->getInterface();
4251 if (!IDecl) {
John McCall31168b02011-06-15 23:02:42 +00004252 if (getLangOptions().ObjCAutoRefCount &&
4253 (OTy->isObjCId() || OTy->isObjCClass()))
4254 goto fail;
John McCall68fc88ec2010-12-15 16:46:44 +00004255 // There's an implicit 'isa' ivar on all objects.
4256 // But we only actually find it this way on objects of type 'id',
4257 // apparently.
4258 if (OTy->isObjCId() && Member->isStr("isa"))
John Wiegley01296292011-04-08 18:41:53 +00004259 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
John McCall68fc88ec2010-12-15 16:46:44 +00004260 Context.getObjCClassType()));
4261
4262 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4263 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4264 ObjCImpDecl, HasTemplateArgs);
4265 goto fail;
4266 }
4267
4268 ObjCInterfaceDecl *ClassDeclared;
4269 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
4270
4271 if (!IV) {
4272 // Attempt to correct for typos in ivar names.
4273 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
4274 LookupMemberName);
4275 if (CorrectTypo(Res, 0, 0, IDecl, false,
4276 IsArrow ? CTC_ObjCIvarLookup
4277 : CTC_ObjCPropertyLookup) &&
4278 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
4279 Diag(R.getNameLoc(),
4280 diag::err_typecheck_member_reference_ivar_suggest)
4281 << IDecl->getDeclName() << MemberName << IV->getDeclName()
4282 << FixItHint::CreateReplacement(R.getNameLoc(),
4283 IV->getNameAsString());
4284 Diag(IV->getLocation(), diag::note_previous_decl)
4285 << IV->getDeclName();
4286 } else {
4287 Res.clear();
4288 Res.setLookupName(Member);
4289
4290 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
4291 << IDecl->getDeclName() << MemberName
John Wiegley01296292011-04-08 18:41:53 +00004292 << BaseExpr.get()->getSourceRange();
John McCall68fc88ec2010-12-15 16:46:44 +00004293 return ExprError();
4294 }
4295 }
4296
4297 // If the decl being referenced had an error, return an error for this
4298 // sub-expr without emitting another error, in order to avoid cascading
4299 // error cases.
4300 if (IV->isInvalidDecl())
4301 return ExprError();
4302
4303 // Check whether we can reference this field.
4304 if (DiagnoseUseOfDecl(IV, MemberLoc))
4305 return ExprError();
4306 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
4307 IV->getAccessControl() != ObjCIvarDecl::Package) {
4308 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
4309 if (ObjCMethodDecl *MD = getCurMethodDecl())
4310 ClassOfMethodDecl = MD->getClassInterface();
4311 else if (ObjCImpDecl && getCurFunctionDecl()) {
4312 // Case of a c-function declared inside an objc implementation.
4313 // FIXME: For a c-style function nested inside an objc implementation
4314 // class, there is no implementation context available, so we pass
4315 // down the context as argument to this routine. Ideally, this context
4316 // need be passed down in the AST node and somehow calculated from the
4317 // AST for a function decl.
4318 if (ObjCImplementationDecl *IMPD =
4319 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
4320 ClassOfMethodDecl = IMPD->getClassInterface();
4321 else if (ObjCCategoryImplDecl* CatImplClass =
4322 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
4323 ClassOfMethodDecl = CatImplClass->getClassInterface();
4324 }
4325
4326 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
4327 if (ClassDeclared != IDecl ||
4328 ClassOfMethodDecl != ClassDeclared)
4329 Diag(MemberLoc, diag::error_private_ivar_access)
4330 << IV->getDeclName();
4331 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
4332 // @protected
4333 Diag(MemberLoc, diag::error_protected_ivar_access)
4334 << IV->getDeclName();
4335 }
4336
4337 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
John Wiegley01296292011-04-08 18:41:53 +00004338 MemberLoc, BaseExpr.take(),
John McCall68fc88ec2010-12-15 16:46:44 +00004339 IsArrow));
4340 }
4341
4342 // Objective-C property access.
4343 const ObjCObjectPointerType *OPT;
4344 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
4345 // This actually uses the base as an r-value.
John Wiegley01296292011-04-08 18:41:53 +00004346 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4347 if (BaseExpr.isInvalid())
4348 return ExprError();
4349
4350 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
John McCall68fc88ec2010-12-15 16:46:44 +00004351
4352 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
4353
4354 const ObjCObjectType *OT = OPT->getObjectType();
4355
4356 // id, with and without qualifiers.
4357 if (OT->isObjCId()) {
4358 // Check protocols on qualified interfaces.
4359 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
4360 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
4361 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
4362 // Check the use of this declaration
4363 if (DiagnoseUseOfDecl(PD, MemberLoc))
4364 return ExprError();
4365
Douglas Gregor33823722011-06-11 01:09:30 +00004366 QualType T = PD->getType();
4367 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
4368 T = getMessageSendResultType(BaseType, Getter, false, false);
4369
4370 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCall68fc88ec2010-12-15 16:46:44 +00004371 VK_LValue,
4372 OK_ObjCProperty,
4373 MemberLoc,
John Wiegley01296292011-04-08 18:41:53 +00004374 BaseExpr.take()));
John McCall68fc88ec2010-12-15 16:46:44 +00004375 }
4376
4377 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
4378 // Check the use of this method.
4379 if (DiagnoseUseOfDecl(OMD, MemberLoc))
4380 return ExprError();
4381 Selector SetterSel =
4382 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4383 PP.getSelectorTable(), Member);
4384 ObjCMethodDecl *SMD = 0;
4385 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
4386 SetterSel, Context))
4387 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Douglas Gregor33823722011-06-11 01:09:30 +00004388 QualType PType = getMessageSendResultType(BaseType, OMD, false,
4389 false);
John McCall68fc88ec2010-12-15 16:46:44 +00004390
4391 ExprValueKind VK = VK_LValue;
4392 if (!getLangOptions().CPlusPlus &&
4393 IsCForbiddenLValueType(Context, PType))
4394 VK = VK_RValue;
4395 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4396
4397 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
4398 VK, OK,
John Wiegley01296292011-04-08 18:41:53 +00004399 MemberLoc, BaseExpr.take()));
John McCall68fc88ec2010-12-15 16:46:44 +00004400 }
4401 }
Fariborz Jahanianb03a4c22011-03-15 17:27:48 +00004402 // Use of id.member can only be for a property reference. Do not
4403 // use the 'id' redefinition in this case.
4404 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
John McCall68fc88ec2010-12-15 16:46:44 +00004405 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4406 ObjCImpDecl, HasTemplateArgs);
4407
4408 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
4409 << MemberName << BaseType);
4410 }
4411
4412 // 'Class', unqualified only.
4413 if (OT->isObjCClass()) {
4414 // Only works in a method declaration (??!).
4415 ObjCMethodDecl *MD = getCurMethodDecl();
4416 if (!MD) {
4417 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4418 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4419 ObjCImpDecl, HasTemplateArgs);
4420
4421 goto fail;
4422 }
4423
4424 // Also must look for a getter name which uses property syntax.
4425 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004426 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4427 ObjCMethodDecl *Getter;
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004428 if ((Getter = IFace->lookupClassMethod(Sel))) {
4429 // Check the use of this method.
4430 if (DiagnoseUseOfDecl(Getter, MemberLoc))
4431 return ExprError();
John McCall68fc88ec2010-12-15 16:46:44 +00004432 } else
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00004433 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004434 // If we found a getter then this may be a valid dot-reference, we
4435 // will look for the matching setter, in case it is needed.
4436 Selector SetterSel =
John McCall68fc88ec2010-12-15 16:46:44 +00004437 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4438 PP.getSelectorTable(), Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004439 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
4440 if (!Setter) {
4441 // If this reference is in an @implementation, also check for 'private'
4442 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00004443 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004444 }
4445 // Look through local category implementations associated with the class.
4446 if (!Setter)
4447 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004448
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004449 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
4450 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004451
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004452 if (Getter || Setter) {
4453 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004454
John McCall4bc41ae2010-11-18 19:01:18 +00004455 ExprValueKind VK = VK_LValue;
4456 if (Getter) {
Douglas Gregor33823722011-06-11 01:09:30 +00004457 PType = getMessageSendResultType(QualType(OT, 0), Getter, true,
4458 false);
John McCall4bc41ae2010-11-18 19:01:18 +00004459 if (!getLangOptions().CPlusPlus &&
4460 IsCForbiddenLValueType(Context, PType))
4461 VK = VK_RValue;
4462 } else {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004463 // Get the expression type from Setter's incoming parameter.
4464 PType = (*(Setter->param_end() -1))->getType();
John McCall4bc41ae2010-11-18 19:01:18 +00004465 }
4466 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4467
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004468 // FIXME: we must check that the setter has property type.
John McCallb7bd14f2010-12-02 01:19:52 +00004469 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
4470 PType, VK, OK,
John Wiegley01296292011-04-08 18:41:53 +00004471 MemberLoc, BaseExpr.take()));
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004472 }
John McCall68fc88ec2010-12-15 16:46:44 +00004473
4474 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4475 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4476 ObjCImpDecl, HasTemplateArgs);
4477
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004478 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall68fc88ec2010-12-15 16:46:44 +00004479 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004480 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004481
John McCall68fc88ec2010-12-15 16:46:44 +00004482 // Normal property access.
John Wiegley01296292011-04-08 18:41:53 +00004483 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), MemberName, MemberLoc,
John McCall68fc88ec2010-12-15 16:46:44 +00004484 SourceLocation(), QualType(), false);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004485 }
Alexis Huntc46382e2010-04-28 23:02:27 +00004486
Chris Lattnerb63a7452008-07-21 04:28:12 +00004487 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00004488 if (BaseType->isExtVectorType()) {
John McCall15317a22010-12-15 04:42:30 +00004489 // FIXME: this expr should store IsArrow.
Anders Carlssonf571c112009-08-26 18:25:21 +00004490 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John Wiegley01296292011-04-08 18:41:53 +00004491 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
John McCall4bc41ae2010-11-18 19:01:18 +00004492 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
4493 Member, MemberLoc);
Chris Lattnerb63a7452008-07-21 04:28:12 +00004494 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004495 return ExprError();
John McCall4bc41ae2010-11-18 19:01:18 +00004496
John Wiegley01296292011-04-08 18:41:53 +00004497 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
John McCall4bc41ae2010-11-18 19:01:18 +00004498 *Member, MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00004499 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004500
John McCall68fc88ec2010-12-15 16:46:44 +00004501 // Adjust builtin-sel to the appropriate redefinition type if that's
4502 // not just a pointer to builtin-sel again.
4503 if (IsArrow &&
4504 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
4505 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
John Wiegley01296292011-04-08 18:41:53 +00004506 BaseExpr = ImpCastExprToType(BaseExpr.take(), Context.ObjCSelRedefinitionType,
4507 CK_BitCast);
John McCall68fc88ec2010-12-15 16:46:44 +00004508 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4509 ObjCImpDecl, HasTemplateArgs);
4510 }
4511
4512 // Failure cases.
4513 fail:
4514
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004515 // Recover from dot accesses to pointers, e.g.:
4516 // type *foo;
4517 // foo.bar
4518 // This is actually well-formed in two cases:
4519 // - 'type' is an Objective C type
4520 // - 'bar' is a pseudo-destructor name which happens to refer to
4521 // the appropriate pointer type
John McCall68fc88ec2010-12-15 16:46:44 +00004522 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004523 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
4524 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
John McCall68fc88ec2010-12-15 16:46:44 +00004525 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley01296292011-04-08 18:41:53 +00004526 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004527 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall68fc88ec2010-12-15 16:46:44 +00004528
4529 // Recurse as an -> access.
4530 IsArrow = true;
4531 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4532 ObjCImpDecl, HasTemplateArgs);
4533 }
John McCall68fc88ec2010-12-15 16:46:44 +00004534 }
4535
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004536 // If the user is trying to apply -> or . to a function name, it's probably
4537 // because they forgot parentheses to call that function.
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00004538 QualType ZeroArgCallTy;
4539 UnresolvedSet<4> Overloads;
4540 if (isExprCallable(*BaseExpr.get(), ZeroArgCallTy, Overloads)) {
4541 if (ZeroArgCallTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +00004542 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00004543 << (Overloads.size() > 1) << 0 << BaseExpr.get()->getSourceRange();
4544 UnresolvedSet<2> PlausibleOverloads;
4545 for (OverloadExpr::decls_iterator It = Overloads.begin(),
4546 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
4547 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
4548 QualType OverloadResultTy = OverloadDecl->getResultType();
4549 if ((!IsArrow && OverloadResultTy->isRecordType()) ||
4550 (IsArrow && OverloadResultTy->isPointerType() &&
4551 OverloadResultTy->getPointeeType()->isRecordType()))
4552 PlausibleOverloads.addDecl(It.getDecl());
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004553 }
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00004554 NoteOverloads(PlausibleOverloads, BaseExpr.get()->getExprLoc());
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004555 return ExprError();
4556 }
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00004557 if ((!IsArrow && ZeroArgCallTy->isRecordType()) ||
4558 (IsArrow && ZeroArgCallTy->isPointerType() &&
4559 ZeroArgCallTy->getPointeeType()->isRecordType())) {
4560 // At this point, we know BaseExpr looks like it's potentially callable
4561 // with 0 arguments, and that it returns something of a reasonable type,
4562 // so we can emit a fixit and carry on pretending that BaseExpr was
4563 // actually a CallExpr.
4564 SourceLocation ParenInsertionLoc =
4565 PP.getLocForEndOfToken(BaseExpr.get()->getLocEnd());
4566 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
4567 << (Overloads.size() > 1) << 1 << BaseExpr.get()->getSourceRange()
4568 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4569 // FIXME: Try this before emitting the fixit, and suppress diagnostics
4570 // while doing so.
4571 ExprResult NewBase =
4572 ActOnCallExpr(0, BaseExpr.take(), ParenInsertionLoc,
4573 MultiExprArg(*this, 0, 0),
4574 ParenInsertionLoc.getFileLocWithOffset(1));
4575 if (NewBase.isInvalid())
4576 return ExprError();
4577 BaseExpr = NewBase;
4578 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
4579 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4580 ObjCImpDecl, HasTemplateArgs);
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004581 }
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004582 }
4583
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004584 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
John Wiegley01296292011-04-08 18:41:53 +00004585 << BaseType << BaseExpr.get()->getSourceRange();
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004586
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004587 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00004588}
4589
John McCall10eae182009-11-30 22:42:35 +00004590/// The main callback when the parser finds something like
4591/// expression . [nested-name-specifier] identifier
4592/// expression -> [nested-name-specifier] identifier
4593/// where 'identifier' encompasses a fairly broad spectrum of
4594/// possibilities, including destructor and operator references.
4595///
4596/// \param OpKind either tok::arrow or tok::period
4597/// \param HasTrailingLParen whether the next token is '(', which
4598/// is used to diagnose mis-uses of special members that can
4599/// only be called
4600/// \param ObjCImpDecl the current ObjC @implementation decl;
4601/// this is an ugly hack around the fact that ObjC @implementations
4602/// aren't properly put in the context chain
John McCalldadc5752010-08-24 06:29:42 +00004603ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall15317a22010-12-15 04:42:30 +00004604 SourceLocation OpLoc,
4605 tok::TokenKind OpKind,
4606 CXXScopeSpec &SS,
4607 UnqualifiedId &Id,
4608 Decl *ObjCImpDecl,
4609 bool HasTrailingLParen) {
John McCall10eae182009-11-30 22:42:35 +00004610 if (SS.isSet() && SS.isInvalid())
4611 return ExprError();
4612
Francois Pichet64225792011-01-18 05:04:39 +00004613 // Warn about the explicit constructor calls Microsoft extension.
4614 if (getLangOptions().Microsoft &&
4615 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4616 Diag(Id.getSourceRange().getBegin(),
4617 diag::ext_ms_explicit_constructor_call);
4618
John McCall10eae182009-11-30 22:42:35 +00004619 TemplateArgumentListInfo TemplateArgsBuffer;
4620
4621 // Decompose the name into its component parts.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004622 DeclarationNameInfo NameInfo;
John McCall10eae182009-11-30 22:42:35 +00004623 const TemplateArgumentListInfo *TemplateArgs;
4624 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004625 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004626
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004627 DeclarationName Name = NameInfo.getName();
John McCall10eae182009-11-30 22:42:35 +00004628 bool IsArrow = (OpKind == tok::arrow);
4629
4630 NamedDecl *FirstQualifierInScope
4631 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4632 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4633
4634 // This is a postfix expression, so get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004635 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00004636 if (Result.isInvalid()) return ExprError();
4637 Base = Result.take();
John McCall10eae182009-11-30 22:42:35 +00004638
Douglas Gregor41f90302010-04-12 20:54:26 +00004639 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4640 isDependentScopeSpecifier(SS)) {
John McCallb268a282010-08-23 23:25:46 +00004641 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00004642 IsArrow, OpLoc,
4643 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004644 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004645 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004646 LookupResult R(*this, NameInfo, LookupMemberName);
John Wiegley01296292011-04-08 18:41:53 +00004647 ExprResult BaseResult = Owned(Base);
4648 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCalle9cccd82010-06-16 08:42:20 +00004649 SS, ObjCImpDecl, TemplateArgs != 0);
John Wiegley01296292011-04-08 18:41:53 +00004650 if (BaseResult.isInvalid())
4651 return ExprError();
4652 Base = BaseResult.take();
Alexis Huntc46382e2010-04-28 23:02:27 +00004653
John McCalle9cccd82010-06-16 08:42:20 +00004654 if (Result.isInvalid()) {
4655 Owned(Base);
4656 return ExprError();
4657 }
John McCall10eae182009-11-30 22:42:35 +00004658
John McCalle9cccd82010-06-16 08:42:20 +00004659 if (Result.get()) {
4660 // The only way a reference to a destructor can be used is to
4661 // immediately call it, which falls into this case. If the
4662 // next token is not a '(', produce a diagnostic and build the
4663 // call now.
4664 if (!HasTrailingLParen &&
4665 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCallb268a282010-08-23 23:25:46 +00004666 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall10eae182009-11-30 22:42:35 +00004667
John McCalle9cccd82010-06-16 08:42:20 +00004668 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00004669 }
4670
John McCallb268a282010-08-23 23:25:46 +00004671 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00004672 OpLoc, IsArrow, SS, FirstQualifierInScope,
4673 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004674 }
4675
4676 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00004677}
4678
John McCalldadc5752010-08-24 06:29:42 +00004679ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00004680 FunctionDecl *FD,
4681 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00004682 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004683 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00004684 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00004685 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004686 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00004687 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004688 return ExprError();
4689 }
4690
4691 if (Param->hasUninstantiatedDefaultArg()) {
4692 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00004693
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004694 // Instantiate the expression.
4695 MultiLevelTemplateArgumentList ArgList
4696 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00004697
Nico Weber44887f62010-11-29 18:19:25 +00004698 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004699 = ArgList.getInnermost();
4700 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4701 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00004702
Nico Weber44887f62010-11-29 18:19:25 +00004703 ExprResult Result;
4704 {
4705 // C++ [dcl.fct.default]p5:
4706 // The names in the [default argument] expression are bound, and
4707 // the semantic constraints are checked, at the point where the
4708 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00004709 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00004710 Result = SubstExpr(UninstExpr, ArgList);
4711 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004712 if (Result.isInvalid())
4713 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004714
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004715 // Check the expression as an initializer for the parameter.
4716 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004717 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004718 InitializationKind Kind
4719 = InitializationKind::CreateCopy(Param->getLocation(),
4720 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4721 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00004722
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004723 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4724 Result = InitSeq.Perform(*this, Entity, Kind,
4725 MultiExprArg(*this, &ResultE, 1));
4726 if (Result.isInvalid())
4727 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004728
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004729 // Build the default argument expression.
4730 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4731 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00004732 }
4733
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004734 // If the default expression creates temporaries, we need to
4735 // push them to the current stack of expression temporaries so they'll
4736 // be properly destroyed.
4737 // FIXME: We should really be rebuilding the default argument with new
4738 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00004739 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4740 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4741 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4742 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4743 ExprTemporaries.push_back(Temporary);
John McCall31168b02011-06-15 23:02:42 +00004744 ExprNeedsCleanups = true;
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00004745 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004746
4747 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00004748 // Just mark all of the declarations in this potentially-evaluated expression
4749 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004750 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00004751 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00004752}
4753
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004754/// ConvertArgumentsForCall - Converts the arguments specified in
4755/// Args/NumArgs to the parameter types of the function FDecl with
4756/// function prototype Proto. Call is the call expression itself, and
4757/// Fn is the function expression. For a C++ member function, this
4758/// routine does not attempt to convert the object argument. Returns
4759/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004760bool
4761Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004762 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004763 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004764 Expr **Args, unsigned NumArgs,
4765 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00004766 // Bail out early if calling a builtin with custom typechecking.
4767 // We don't need to do this in the
4768 if (FDecl)
4769 if (unsigned ID = FDecl->getBuiltinID())
4770 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4771 return false;
4772
Mike Stump4e1f26a2009-02-19 03:04:26 +00004773 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004774 // assignment, to the types of the corresponding parameter, ...
4775 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00004776 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004777
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004778 // If too few arguments are available (and we don't have default
4779 // arguments for the remaining parameters), don't make the call.
4780 if (NumArgs < NumArgsInProto) {
4781 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4782 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004783 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00004784 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00004785 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004786 }
4787
4788 // If too many are passed and not variadic, error on the extras and drop
4789 // them.
4790 if (NumArgs > NumArgsInProto) {
4791 if (!Proto->isVariadic()) {
4792 Diag(Args[NumArgsInProto]->getLocStart(),
4793 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004794 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004795 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004796 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4797 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00004798
4799 // Emit the location of the prototype.
4800 if (FDecl && !FDecl->getBuiltinID())
4801 Diag(FDecl->getLocStart(),
4802 diag::note_typecheck_call_too_many_args)
4803 << FDecl;
4804
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004805 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00004806 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004807 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004808 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004809 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004810 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004811 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004812 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4813 if (Fn->getType()->isBlockPointerType())
4814 CallType = VariadicBlock; // Block
4815 else if (isa<MemberExpr>(Fn))
4816 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004817 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004818 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004819 if (Invalid)
4820 return true;
4821 unsigned TotalNumArgs = AllArgs.size();
4822 for (unsigned i = 0; i < TotalNumArgs; ++i)
4823 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004824
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004825 return false;
4826}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004827
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004828bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4829 FunctionDecl *FDecl,
4830 const FunctionProtoType *Proto,
4831 unsigned FirstProtoArg,
4832 Expr **Args, unsigned NumArgs,
4833 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004834 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004835 unsigned NumArgsInProto = Proto->getNumArgs();
4836 unsigned NumArgsToCheck = NumArgs;
4837 bool Invalid = false;
4838 if (NumArgs != NumArgsInProto)
4839 // Use default arguments for missing arguments
4840 NumArgsToCheck = NumArgsInProto;
4841 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004842 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004843 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004844 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004845
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004846 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004847 if (ArgIx < NumArgs) {
4848 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004849
Eli Friedman3164fb12009-03-22 22:00:50 +00004850 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4851 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00004852 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004853 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00004854 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004855
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004856 // Pass the argument
4857 ParmVarDecl *Param = 0;
4858 if (FDecl && i < FDecl->getNumParams())
4859 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00004860
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004861 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004862 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00004863 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
4864 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00004865 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00004866 SourceLocation(),
4867 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004868 if (ArgE.isInvalid())
4869 return true;
4870
4871 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004872 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00004873 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004874
John McCalldadc5752010-08-24 06:29:42 +00004875 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004876 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004877 if (ArgExpr.isInvalid())
4878 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004879
Anders Carlsson355933d2009-08-25 03:49:14 +00004880 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004881 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004882 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004883 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004884
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004885 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004886 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00004887
4888 // Assume that extern "C" functions with variadic arguments that
4889 // return __unknown_anytype aren't *really* variadic.
4890 if (Proto->getResultType() == Context.UnknownAnyTy &&
4891 FDecl && FDecl->isExternC()) {
4892 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4893 ExprResult arg;
4894 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
4895 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
4896 else
4897 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4898 Invalid |= arg.isInvalid();
4899 AllArgs.push_back(arg.take());
4900 }
4901
4902 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4903 } else {
4904 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4905 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4906 Invalid |= Arg.isInvalid();
4907 AllArgs.push_back(Arg.take());
4908 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004909 }
4910 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004911 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004912}
4913
John McCall2979fe02011-04-12 00:42:48 +00004914/// Given a function expression of unknown-any type, try to rebuild it
4915/// to have a function type.
4916static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4917
Steve Naroff83895f72007-09-16 03:34:24 +00004918/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00004919/// This provides the location of the left/right parens and a list of comma
4920/// locations.
John McCalldadc5752010-08-24 06:29:42 +00004921ExprResult
John McCallb268a282010-08-23 23:25:46 +00004922Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004923 MultiExprArg args, SourceLocation RParenLoc,
4924 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004925 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00004926
4927 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004928 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00004929 if (Result.isInvalid()) return ExprError();
4930 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00004931
John McCallb268a282010-08-23 23:25:46 +00004932 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00004933
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004934 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004935 // If this is a pseudo-destructor expression, build the call immediately.
4936 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4937 if (NumArgs > 0) {
4938 // Pseudo-destructor calls should not have any arguments.
4939 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00004940 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00004941 SourceRange(Args[0]->getLocStart(),
4942 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00004943
Douglas Gregorad8a3362009-09-04 17:36:40 +00004944 NumArgs = 0;
4945 }
Mike Stump11289f42009-09-09 15:08:12 +00004946
Douglas Gregorad8a3362009-09-04 17:36:40 +00004947 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00004948 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004949 }
Mike Stump11289f42009-09-09 15:08:12 +00004950
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004951 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00004952 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00004953 // FIXME: Will need to cache the results of name lookup (including ADL) in
4954 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004955 bool Dependent = false;
4956 if (Fn->isTypeDependent())
4957 Dependent = true;
4958 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4959 Dependent = true;
4960
Peter Collingbourne41f85462011-02-09 21:07:24 +00004961 if (Dependent) {
4962 if (ExecConfig) {
4963 return Owned(new (Context) CUDAKernelCallExpr(
4964 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4965 Context.DependentTy, VK_RValue, RParenLoc));
4966 } else {
4967 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4968 Context.DependentTy, VK_RValue,
4969 RParenLoc));
4970 }
4971 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004972
4973 // Determine whether this is a call to an object (C++ [over.call.object]).
4974 if (Fn->getType()->isRecordType())
4975 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004976 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004977
John McCall2979fe02011-04-12 00:42:48 +00004978 if (Fn->getType() == Context.UnknownAnyTy) {
4979 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4980 if (result.isInvalid()) return ExprError();
4981 Fn = result.take();
4982 }
4983
John McCall0009fcc2011-04-26 20:42:42 +00004984 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00004985 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004986 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00004987 }
John McCall0009fcc2011-04-26 20:42:42 +00004988 }
John McCall10eae182009-11-30 22:42:35 +00004989
John McCall0009fcc2011-04-26 20:42:42 +00004990 // Check for overloaded calls. This can happen even in C due to extensions.
4991 if (Fn->getType() == Context.OverloadTy) {
4992 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4993
4994 // We aren't supposed to apply this logic if there's an '&' involved.
4995 if (!find.IsAddressOfOperand) {
4996 OverloadExpr *ovl = find.Expression;
4997 if (isa<UnresolvedLookupExpr>(ovl)) {
4998 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4999 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
5000 RParenLoc, ExecConfig);
5001 } else {
John McCall2d74de92009-12-01 22:10:20 +00005002 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00005003 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00005004 }
5005 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005006 }
5007
Douglas Gregore254f902009-02-04 00:32:51 +00005008 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005009
Eli Friedmane14b1992009-12-26 03:35:45 +00005010 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00005011
John McCall57500772009-12-16 12:17:52 +00005012 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00005013 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
5014 if (UnOp->getOpcode() == UO_AddrOf)
5015 NakedFn = UnOp->getSubExpr()->IgnoreParens();
5016
John McCall57500772009-12-16 12:17:52 +00005017 if (isa<DeclRefExpr>(NakedFn))
5018 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00005019 else if (isa<MemberExpr>(NakedFn))
5020 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00005021
Peter Collingbourne41f85462011-02-09 21:07:24 +00005022 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
5023 ExecConfig);
5024}
5025
5026ExprResult
5027Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
5028 MultiExprArg execConfig, SourceLocation GGGLoc) {
5029 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
5030 if (!ConfigDecl)
5031 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
5032 << "cudaConfigureCall");
5033 QualType ConfigQTy = ConfigDecl->getType();
5034
5035 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
5036 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
5037
5038 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00005039}
5040
Tanya Lattner55808c12011-06-04 00:47:47 +00005041/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5042///
5043/// __builtin_astype( value, dst type )
5044///
5045ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty,
5046 SourceLocation BuiltinLoc,
5047 SourceLocation RParenLoc) {
5048 ExprValueKind VK = VK_RValue;
5049 ExprObjectKind OK = OK_Ordinary;
5050 QualType DstTy = GetTypeFromParser(destty);
5051 QualType SrcTy = expr->getType();
5052 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5053 return ExprError(Diag(BuiltinLoc,
5054 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00005055 << DstTy
5056 << SrcTy
Tanya Lattner55808c12011-06-04 00:47:47 +00005057 << expr->getSourceRange());
5058 return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc, RParenLoc));
5059}
5060
John McCall57500772009-12-16 12:17:52 +00005061/// BuildResolvedCallExpr - Build a call to a resolved expression,
5062/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00005063/// unary-convert to an expression of function-pointer or
5064/// block-pointer type.
5065///
5066/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00005067ExprResult
John McCall2d74de92009-12-01 22:10:20 +00005068Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5069 SourceLocation LParenLoc,
5070 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00005071 SourceLocation RParenLoc,
5072 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00005073 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5074
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005075 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00005076 ExprResult Result = UsualUnaryConversions(Fn);
5077 if (Result.isInvalid())
5078 return ExprError();
5079 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005080
Chris Lattner08464942007-12-28 05:29:59 +00005081 // Make the call expr early, before semantic checks. This guarantees cleanup
5082 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00005083 CallExpr *TheCall;
5084 if (Config) {
5085 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5086 cast<CallExpr>(Config),
5087 Args, NumArgs,
5088 Context.BoolTy,
5089 VK_RValue,
5090 RParenLoc);
5091 } else {
5092 TheCall = new (Context) CallExpr(Context, Fn,
5093 Args, NumArgs,
5094 Context.BoolTy,
5095 VK_RValue,
5096 RParenLoc);
5097 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005098
John McCallbebede42011-02-26 05:39:39 +00005099 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5100
5101 // Bail out early if calling a builtin with custom typechecking.
5102 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5103 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
5104
John McCall31996342011-04-07 08:22:57 +00005105 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005106 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00005107 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005108 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5109 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00005110 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00005111 if (FuncT == 0)
5112 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5113 << Fn->getType() << Fn->getSourceRange());
5114 } else if (const BlockPointerType *BPT =
5115 Fn->getType()->getAs<BlockPointerType>()) {
5116 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5117 } else {
John McCall31996342011-04-07 08:22:57 +00005118 // Handle calls to expressions of unknown-any type.
5119 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00005120 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00005121 if (rewrite.isInvalid()) return ExprError();
5122 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00005123 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00005124 goto retry;
5125 }
5126
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005127 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5128 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00005129 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005130
Peter Collingbourne4b66c472011-02-23 01:53:29 +00005131 if (getLangOptions().CUDA) {
5132 if (Config) {
5133 // CUDA: Kernel calls must be to global functions
5134 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5135 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5136 << FDecl->getName() << Fn->getSourceRange());
5137
5138 // CUDA: Kernel function must have 'void' return type
5139 if (!FuncT->getResultType()->isVoidType())
5140 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5141 << Fn->getType() << Fn->getSourceRange());
5142 }
5143 }
5144
Eli Friedman3164fb12009-03-22 22:00:50 +00005145 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005146 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00005147 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00005148 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00005149 return ExprError();
5150
Chris Lattner08464942007-12-28 05:29:59 +00005151 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00005152 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00005153 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005154
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005155 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00005156 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005157 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005158 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00005159 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005160 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005161
Douglas Gregord8e97de2009-04-02 15:37:10 +00005162 if (FDecl) {
5163 // Check if we have too few/too many template arguments, based
5164 // on our knowledge of the function definition.
5165 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00005166 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00005167 const FunctionProtoType *Proto
5168 = Def->getType()->getAs<FunctionProtoType>();
5169 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00005170 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5171 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00005172 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00005173
5174 // If the function we're calling isn't a function prototype, but we have
5175 // a function prototype from a prior declaratiom, use that prototype.
5176 if (!FDecl->hasPrototype())
5177 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00005178 }
5179
Steve Naroff0b661582007-08-28 23:30:39 +00005180 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00005181 for (unsigned i = 0; i != NumArgs; i++) {
5182 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00005183
5184 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00005185 InitializedEntity Entity
5186 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00005187 Proto->getArgType(i),
5188 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00005189 ExprResult ArgE = PerformCopyInitialization(Entity,
5190 SourceLocation(),
5191 Owned(Arg));
5192 if (ArgE.isInvalid())
5193 return true;
5194
5195 Arg = ArgE.takeAs<Expr>();
5196
5197 } else {
John Wiegley01296292011-04-08 18:41:53 +00005198 ExprResult ArgE = DefaultArgumentPromotion(Arg);
5199
5200 if (ArgE.isInvalid())
5201 return true;
5202
5203 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00005204 }
5205
Douglas Gregor83025412010-10-26 05:45:40 +00005206 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
5207 Arg->getType(),
5208 PDiag(diag::err_call_incomplete_argument)
5209 << Arg->getSourceRange()))
5210 return ExprError();
5211
Chris Lattner08464942007-12-28 05:29:59 +00005212 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00005213 }
Steve Naroffae4143e2007-04-26 20:39:23 +00005214 }
Chris Lattner08464942007-12-28 05:29:59 +00005215
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005216 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5217 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005218 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5219 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005220
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00005221 // Check for sentinels
5222 if (NDecl)
5223 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00005224
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005225 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005226 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00005227 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005228 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00005229
John McCallbebede42011-02-26 05:39:39 +00005230 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00005231 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005232 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00005233 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005234 return ExprError();
5235 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005236
John McCallb268a282010-08-23 23:25:46 +00005237 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00005238}
5239
John McCalldadc5752010-08-24 06:29:42 +00005240ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005241Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005242 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00005243 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00005244 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00005245 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00005246
5247 TypeSourceInfo *TInfo;
5248 QualType literalType = GetTypeFromParser(Ty, &TInfo);
5249 if (!TInfo)
5250 TInfo = Context.getTrivialTypeSourceInfo(literalType);
5251
John McCallb268a282010-08-23 23:25:46 +00005252 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00005253}
5254
John McCalldadc5752010-08-24 06:29:42 +00005255ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00005256Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00005257 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00005258 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00005259
Eli Friedman37a186d2008-05-20 05:22:08 +00005260 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00005261 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5262 PDiag(diag::err_illegal_decl_array_incomplete_type)
5263 << SourceRange(LParenLoc,
5264 literalExpr->getSourceRange().getEnd())))
5265 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00005266 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005267 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5268 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00005269 } else if (!literalType->isDependentType() &&
5270 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00005271 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00005272 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00005273 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005274 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00005275
Douglas Gregor85dabae2009-12-16 01:38:02 +00005276 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00005277 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005278 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00005279 = InitializationKind::CreateCStyleCast(LParenLoc,
5280 SourceRange(LParenLoc, RParenLoc));
Eli Friedmana553d4a2009-12-22 02:35:53 +00005281 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00005282 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00005283 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00005284 &literalType);
5285 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005286 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00005287 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00005288
Chris Lattner79413952008-12-04 23:50:19 +00005289 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00005290 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00005291 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005292 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00005293 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00005294
John McCall7decc9e2010-11-18 06:31:45 +00005295 // In C, compound literals are l-values for some reason.
5296 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
5297
John McCall5d7aa7f2010-01-19 22:33:45 +00005298 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCall7decc9e2010-11-18 06:31:45 +00005299 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00005300}
5301
John McCalldadc5752010-08-24 06:29:42 +00005302ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00005303Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00005304 SourceLocation RBraceLoc) {
5305 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00005306 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00005307
Steve Naroff30d242c2007-09-15 18:49:24 +00005308 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00005309 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005310
Ted Kremenekac034612010-04-13 23:39:13 +00005311 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
5312 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005313 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005314 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00005315}
5316
John McCalld7646252010-11-14 08:17:51 +00005317/// Prepares for a scalar cast, performing all the necessary stages
5318/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00005319static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00005320 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5321 // Also, callers should have filtered out the invalid cases with
5322 // pointers. Everything else should be possible.
5323
John Wiegley01296292011-04-08 18:41:53 +00005324 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00005325 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00005326 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00005327
John McCall8cb679e2010-11-15 09:13:47 +00005328 switch (SrcTy->getScalarTypeKind()) {
5329 case Type::STK_MemberPointer:
5330 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00005331
John McCall8cb679e2010-11-15 09:13:47 +00005332 case Type::STK_Pointer:
5333 switch (DestTy->getScalarTypeKind()) {
5334 case Type::STK_Pointer:
5335 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00005336 CK_AnyPointerToObjCPointerCast :
5337 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00005338 case Type::STK_Bool:
5339 return CK_PointerToBoolean;
5340 case Type::STK_Integral:
5341 return CK_PointerToIntegral;
5342 case Type::STK_Floating:
5343 case Type::STK_FloatingComplex:
5344 case Type::STK_IntegralComplex:
5345 case Type::STK_MemberPointer:
5346 llvm_unreachable("illegal cast from pointer");
5347 }
5348 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005349
John McCall8cb679e2010-11-15 09:13:47 +00005350 case Type::STK_Bool: // casting from bool is like casting from an integer
5351 case Type::STK_Integral:
5352 switch (DestTy->getScalarTypeKind()) {
5353 case Type::STK_Pointer:
John Wiegley01296292011-04-08 18:41:53 +00005354 if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00005355 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00005356 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005357 case Type::STK_Bool:
5358 return CK_IntegralToBoolean;
5359 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00005360 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00005361 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00005362 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00005363 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00005364 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5365 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00005366 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005367 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00005368 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5369 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00005370 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005371 case Type::STK_MemberPointer:
5372 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005373 }
5374 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005375
John McCall8cb679e2010-11-15 09:13:47 +00005376 case Type::STK_Floating:
5377 switch (DestTy->getScalarTypeKind()) {
5378 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00005379 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00005380 case Type::STK_Bool:
5381 return CK_FloatingToBoolean;
5382 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00005383 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00005384 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00005385 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5386 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00005387 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005388 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00005389 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5390 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00005391 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005392 case Type::STK_Pointer:
5393 llvm_unreachable("valid float->pointer cast?");
5394 case Type::STK_MemberPointer:
5395 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005396 }
5397 break;
5398
John McCall8cb679e2010-11-15 09:13:47 +00005399 case Type::STK_FloatingComplex:
5400 switch (DestTy->getScalarTypeKind()) {
5401 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005402 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00005403 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005404 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00005405 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00005406 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005407 if (S.Context.hasSameType(ET, DestTy))
5408 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00005409 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00005410 return CK_FloatingCast;
5411 }
John McCall8cb679e2010-11-15 09:13:47 +00005412 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005413 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005414 case Type::STK_Integral:
John Wiegley01296292011-04-08 18:41:53 +00005415 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5416 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00005417 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00005418 case Type::STK_Pointer:
5419 llvm_unreachable("valid complex float->pointer cast?");
5420 case Type::STK_MemberPointer:
5421 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005422 }
5423 break;
5424
John McCall8cb679e2010-11-15 09:13:47 +00005425 case Type::STK_IntegralComplex:
5426 switch (DestTy->getScalarTypeKind()) {
5427 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005428 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005429 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005430 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00005431 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00005432 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005433 if (S.Context.hasSameType(ET, DestTy))
5434 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00005435 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00005436 return CK_IntegralCast;
5437 }
John McCall8cb679e2010-11-15 09:13:47 +00005438 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005439 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005440 case Type::STK_Floating:
John Wiegley01296292011-04-08 18:41:53 +00005441 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5442 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00005443 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00005444 case Type::STK_Pointer:
5445 llvm_unreachable("valid complex int->pointer cast?");
5446 case Type::STK_MemberPointer:
5447 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005448 }
5449 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00005450 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005451
John McCalld7646252010-11-14 08:17:51 +00005452 llvm_unreachable("Unhandled scalar cast");
5453 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00005454}
5455
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005456/// CheckCastTypes - Check type constraints for casting between types.
John McCall31168b02011-06-15 23:02:42 +00005457ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyR,
5458 QualType castType, Expr *castExpr,
5459 CastKind& Kind, ExprValueKind &VK,
John Wiegley01296292011-04-08 18:41:53 +00005460 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall31996342011-04-07 08:22:57 +00005461 if (castExpr->getType() == Context.UnknownAnyTy)
5462 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
5463
Sebastian Redl9f831db2009-07-25 15:41:38 +00005464 if (getLangOptions().CPlusPlus)
John McCall31168b02011-06-15 23:02:42 +00005465 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Douglas Gregor15417cf2010-11-03 00:35:38 +00005466 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00005467 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00005468 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00005469
John McCall3aef3d82011-04-10 19:13:55 +00005470 assert(!castExpr->getType()->isPlaceholderType());
5471
John McCall7decc9e2010-11-18 06:31:45 +00005472 // We only support r-value casts in C.
5473 VK = VK_RValue;
5474
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005475 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
5476 // type needs to be scalar.
5477 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00005478 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley01296292011-04-08 18:41:53 +00005479 ExprResult castExprRes = IgnoredValueConversions(castExpr);
5480 if (castExprRes.isInvalid())
5481 return ExprError();
5482 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00005483
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005484 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00005485 Kind = CK_ToVoid;
John Wiegley01296292011-04-08 18:41:53 +00005486 return Owned(castExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00005487 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005488
John Wiegley01296292011-04-08 18:41:53 +00005489 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
5490 if (castExprRes.isInvalid())
5491 return ExprError();
5492 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00005493
Eli Friedmane98194d2010-07-17 20:43:49 +00005494 if (RequireCompleteType(TyR.getBegin(), castType,
5495 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00005496 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00005497
Anders Carlssonef918ac2009-10-16 02:35:04 +00005498 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005499 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005500 (castType->isStructureType() || castType->isUnionType())) {
5501 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00005502 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005503 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
5504 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005505 Kind = CK_NoOp;
John Wiegley01296292011-04-08 18:41:53 +00005506 return Owned(castExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00005507 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005508
Anders Carlsson525b76b2009-10-16 02:48:28 +00005509 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005510 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005511 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005512 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005513 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005514 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005515 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00005516 castExpr->getType()) &&
5517 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005518 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5519 << castExpr->getSourceRange();
5520 break;
5521 }
5522 }
John Wiegley01296292011-04-08 18:41:53 +00005523 if (Field == FieldEnd) {
5524 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005525 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005526 return ExprError();
5527 }
John McCalle3027922010-08-25 11:45:40 +00005528 Kind = CK_ToUnion;
John Wiegley01296292011-04-08 18:41:53 +00005529 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005530 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005531
Anders Carlsson525b76b2009-10-16 02:48:28 +00005532 // Reject any other conversions to non-scalar types.
John Wiegley01296292011-04-08 18:41:53 +00005533 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlsson525b76b2009-10-16 02:48:28 +00005534 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005535 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005536 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005537
John McCalld7646252010-11-14 08:17:51 +00005538 // The type we're casting to is known to be a scalar or vector.
5539
5540 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005541 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00005542 !castExpr->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005543 Diag(castExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00005544 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005545 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005546 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005547 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005548
5549 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00005550 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005551
Anton Yartsev28ccef72011-03-27 09:32:40 +00005552 if (castType->isVectorType()) {
5553 if (castType->getAs<VectorType>()->getVectorKind() ==
5554 VectorType::AltiVecVector &&
5555 (castExpr->getType()->isIntegerType() ||
5556 castExpr->getType()->isFloatingType())) {
5557 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00005558 return Owned(castExpr);
5559 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
5560 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00005561 } else
John Wiegley01296292011-04-08 18:41:53 +00005562 return Owned(castExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00005563 }
John Wiegley01296292011-04-08 18:41:53 +00005564 if (castExpr->getType()->isVectorType()) {
5565 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
5566 return ExprError();
5567 else
5568 return Owned(castExpr);
5569 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00005570
John McCalld7646252010-11-14 08:17:51 +00005571 // The source and target types are both scalars, i.e.
5572 // - arithmetic types (fundamental, enum, and complex)
5573 // - all kinds of pointers
5574 // Note that member pointers were filtered out with C++, above.
5575
John Wiegley01296292011-04-08 18:41:53 +00005576 if (isa<ObjCSelectorExpr>(castExpr)) {
5577 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
5578 return ExprError();
5579 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005580
John McCalld7646252010-11-14 08:17:51 +00005581 // If either type is a pointer, the other type has to be either an
5582 // integer or a pointer.
John McCall31168b02011-06-15 23:02:42 +00005583 QualType castExprType = castExpr->getType();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005584 if (!castType->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00005585 if (!castExprType->isIntegralType(Context) &&
John Wiegley01296292011-04-08 18:41:53 +00005586 castExprType->isArithmeticType()) {
5587 Diag(castExpr->getLocStart(),
5588 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005589 << castExprType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005590 return ExprError();
5591 }
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005592 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley01296292011-04-08 18:41:53 +00005593 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
5594 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005595 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005596 return ExprError();
5597 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005598 }
Anders Carlsson094c4592009-10-18 18:12:03 +00005599
John McCall31168b02011-06-15 23:02:42 +00005600 if (getLangOptions().ObjCAutoRefCount) {
5601 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
5602 CheckObjCARCConversion(SourceRange(CastStartLoc, castExpr->getLocEnd()),
5603 castType, castExpr, CCK_CStyleCast);
5604
5605 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
5606 if (const PointerType *ExprPtr = castExprType->getAs<PointerType>()) {
5607 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
5608 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
5609 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
5610 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
5611 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
5612 Diag(castExpr->getLocStart(),
5613 diag::err_typecheck_incompatible_lifetime)
5614 << castExprType << castType << AA_Casting
5615 << castExpr->getSourceRange();
5616
5617 return ExprError();
5618 }
5619 }
5620 }
5621 }
5622
John Wiegley01296292011-04-08 18:41:53 +00005623 castExprRes = Owned(castExpr);
5624 Kind = PrepareScalarCast(*this, castExprRes, castType);
5625 if (castExprRes.isInvalid())
5626 return ExprError();
5627 castExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00005628
John McCalld7646252010-11-14 08:17:51 +00005629 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00005630 CheckCastAlign(castExpr, castType, TyR);
5631
John Wiegley01296292011-04-08 18:41:53 +00005632 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005633}
5634
Anders Carlsson525b76b2009-10-16 02:48:28 +00005635bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00005636 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00005637 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005638
Anders Carlssonde71adf2007-11-27 05:51:55 +00005639 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00005640 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00005641 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00005642 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00005643 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00005644 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005645 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005646 } else
5647 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00005648 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005649 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005650
John McCalle3027922010-08-25 11:45:40 +00005651 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005652 return false;
5653}
5654
John Wiegley01296292011-04-08 18:41:53 +00005655ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5656 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00005657 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005658
Anders Carlsson43d70f82009-10-16 05:23:41 +00005659 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005660
Nate Begemanc8961a42009-06-27 22:05:55 +00005661 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5662 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00005663 if (SrcTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005664 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
5665 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00005666 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00005667 return ExprError();
5668 }
John McCalle3027922010-08-25 11:45:40 +00005669 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00005670 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00005671 }
5672
Nate Begemanbd956c42009-06-28 02:36:38 +00005673 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00005674 // conversion will take place first from scalar to elt type, and then
5675 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00005676 if (SrcTy->isPointerType())
5677 return Diag(R.getBegin(),
5678 diag::err_invalid_conversion_between_vector_and_scalar)
5679 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00005680
5681 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00005682 ExprResult CastExprRes = Owned(CastExpr);
5683 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
5684 if (CastExprRes.isInvalid())
5685 return ExprError();
5686 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005687
John McCalle3027922010-08-25 11:45:40 +00005688 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00005689 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00005690}
5691
John McCalldadc5752010-08-24 06:29:42 +00005692ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005693Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005694 SourceLocation RParenLoc, Expr *castExpr) {
5695 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00005696 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00005697
John McCall97513962010-01-15 18:39:57 +00005698 TypeSourceInfo *castTInfo;
5699 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5700 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00005701 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00005702
Nate Begeman5ec4b312009-08-10 23:49:36 +00005703 // If the Expr being casted is a ParenListExpr, handle it specially.
5704 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00005705 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00005706 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00005707
John McCallb268a282010-08-23 23:25:46 +00005708 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00005709}
5710
John McCalldadc5752010-08-24 06:29:42 +00005711ExprResult
John McCallebe54742010-01-15 18:56:44 +00005712Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00005713 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00005714 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00005715 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00005716 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00005717 ExprResult CastResult =
John McCall31168b02011-06-15 23:02:42 +00005718 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
5719 castExpr, Kind, VK, BasePath);
John Wiegley01296292011-04-08 18:41:53 +00005720 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005721 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00005722 castExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00005723
John McCallcf142162010-08-07 06:22:56 +00005724 return Owned(CStyleCastExpr::Create(Context,
John Wiegley01296292011-04-08 18:41:53 +00005725 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00005726 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00005727 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00005728}
5729
Nate Begeman5ec4b312009-08-10 23:49:36 +00005730/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5731/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00005732ExprResult
John McCallb268a282010-08-23 23:25:46 +00005733Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005734 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5735 if (!E)
5736 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00005737
John McCalldadc5752010-08-24 06:29:42 +00005738 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00005739
Nate Begeman5ec4b312009-08-10 23:49:36 +00005740 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00005741 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5742 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00005743
John McCallb268a282010-08-23 23:25:46 +00005744 if (Result.isInvalid()) return ExprError();
5745
5746 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005747}
5748
John McCalldadc5752010-08-24 06:29:42 +00005749ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00005750Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00005751 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00005752 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00005753 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00005754 QualType Ty = TInfo->getType();
Anton Yartsev28ccef72011-03-27 09:32:40 +00005755 bool isVectorLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00005756
Anton Yartsev28ccef72011-03-27 09:32:40 +00005757 // Check for an altivec or OpenCL literal,
John Thompson781ad172010-06-30 22:55:51 +00005758 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005759 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5760 if (PE->getNumExprs() == 0) {
5761 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5762 return ExprError();
5763 }
John Thompson781ad172010-06-30 22:55:51 +00005764 if (PE->getNumExprs() == 1) {
5765 if (!PE->getExpr(0)->getType()->isVectorType())
Anton Yartsev28ccef72011-03-27 09:32:40 +00005766 isVectorLiteral = true;
John Thompson781ad172010-06-30 22:55:51 +00005767 }
5768 else
Anton Yartsev28ccef72011-03-27 09:32:40 +00005769 isVectorLiteral = true;
John Thompson781ad172010-06-30 22:55:51 +00005770 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00005771
Anton Yartsev28ccef72011-03-27 09:32:40 +00005772 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
John Thompson781ad172010-06-30 22:55:51 +00005773 // then handle it as such.
Anton Yartsev28ccef72011-03-27 09:32:40 +00005774 if (isVectorLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005775 llvm::SmallVector<Expr *, 8> initExprs;
Anton Yartsev28ccef72011-03-27 09:32:40 +00005776 // '(...)' form of vector initialization in AltiVec: the number of
5777 // initializers must be one or must match the size of the vector.
5778 // If a single value is specified in the initializer then it will be
5779 // replicated to all the components of the vector
5780 if (Ty->getAs<VectorType>()->getVectorKind() ==
5781 VectorType::AltiVecVector) {
5782 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5783 // The number of initializers must be one or must match the size of the
5784 // vector. If a single value is specified in the initializer then it will
5785 // be replicated to all the components of the vector
5786 if (PE->getNumExprs() == 1) {
5787 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00005788 ExprResult Literal = Owned(PE->getExpr(0));
5789 Literal = ImpCastExprToType(Literal.take(), ElemTy,
5790 PrepareScalarCast(*this, Literal, ElemTy));
5791 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
Anton Yartsev28ccef72011-03-27 09:32:40 +00005792 }
5793 else if (PE->getNumExprs() < numElems) {
5794 Diag(PE->getExprLoc(),
5795 diag::err_incorrect_number_of_vector_initializers);
5796 return ExprError();
5797 }
5798 else
5799 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5800 initExprs.push_back(PE->getExpr(i));
5801 }
5802 else
5803 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5804 initExprs.push_back(PE->getExpr(i));
Nate Begeman5ec4b312009-08-10 23:49:36 +00005805
5806 // FIXME: This means that pretty-printing the final AST will produce curly
5807 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00005808 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5809 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00005810 initExprs.size(), RParenLoc);
5811 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00005812 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005813 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005814 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00005815 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00005816 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00005817 if (Result.isInvalid()) return ExprError();
5818 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005819 }
5820}
5821
John McCalldadc5752010-08-24 06:29:42 +00005822ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00005823 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005824 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00005825 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005826 unsigned nexprs = Val.size();
5827 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005828 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5829 Expr *expr;
5830 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5831 expr = new (Context) ParenExpr(L, R, exprs[0]);
5832 else
5833 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005834 return Owned(expr);
5835}
5836
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005837/// \brief Emit a specialized diagnostic when one expression is a null pointer
5838/// constant and the other is not a pointer.
5839bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5840 SourceLocation QuestionLoc) {
5841 Expr *NullExpr = LHS;
5842 Expr *NonPointerExpr = RHS;
5843 Expr::NullPointerConstantKind NullKind =
5844 NullExpr->isNullPointerConstant(Context,
5845 Expr::NPC_ValueDependentIsNotNull);
5846
5847 if (NullKind == Expr::NPCK_NotNull) {
5848 NullExpr = RHS;
5849 NonPointerExpr = LHS;
5850 NullKind =
5851 NullExpr->isNullPointerConstant(Context,
5852 Expr::NPC_ValueDependentIsNotNull);
5853 }
5854
5855 if (NullKind == Expr::NPCK_NotNull)
5856 return false;
5857
5858 if (NullKind == Expr::NPCK_ZeroInteger) {
5859 // In this case, check to make sure that we got here from a "NULL"
5860 // string in the source code.
5861 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00005862 SourceLocation loc = NullExpr->getExprLoc();
5863 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005864 return false;
5865 }
5866
5867 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5868 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5869 << NonPointerExpr->getType() << DiagType
5870 << NonPointerExpr->getSourceRange();
5871 return true;
5872}
5873
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005874/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5875/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00005876/// C99 6.5.15
John Wiegley01296292011-04-08 18:41:53 +00005877QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005878 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00005879 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00005880
John McCall3aef3d82011-04-10 19:13:55 +00005881 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00005882 if (!lhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005883 LHS = move(lhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005884
John McCall3aef3d82011-04-10 19:13:55 +00005885 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00005886 if (!rhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005887 RHS = move(rhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005888
Sebastian Redl1a99f442009-04-16 17:51:27 +00005889 // C++ is sufficiently different to merit its own checker.
5890 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00005891 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00005892
5893 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005894 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005895
John Wiegley01296292011-04-08 18:41:53 +00005896 Cond = UsualUnaryConversions(Cond.take());
5897 if (Cond.isInvalid())
5898 return QualType();
5899 LHS = UsualUnaryConversions(LHS.take());
5900 if (LHS.isInvalid())
5901 return QualType();
5902 RHS = UsualUnaryConversions(RHS.take());
5903 if (RHS.isInvalid())
5904 return QualType();
5905
5906 QualType CondTy = Cond.get()->getType();
5907 QualType LHSTy = LHS.get()->getType();
5908 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00005909
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005910 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005911 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00005912 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5913 // Throw an error if its not either.
5914 if (getLangOptions().OpenCL) {
5915 if (!CondTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005916 Diag(Cond.get()->getLocStart(),
Nate Begemanabb5a732010-09-20 22:41:17 +00005917 diag::err_typecheck_cond_expect_scalar_or_vector)
5918 << CondTy;
5919 return QualType();
5920 }
5921 }
5922 else {
John Wiegley01296292011-04-08 18:41:53 +00005923 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005924 << CondTy;
5925 return QualType();
5926 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005927 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005928
Chris Lattnere2949f42008-01-06 22:42:25 +00005929 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005930 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5931 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00005932
Nate Begemanabb5a732010-09-20 22:41:17 +00005933 // OpenCL: If the condition is a vector, and both operands are scalar,
5934 // attempt to implicity convert them to the vector type to act like the
5935 // built in select.
5936 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5937 // Both operands should be of scalar type.
5938 if (!LHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00005939 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005940 << CondTy;
5941 return QualType();
5942 }
5943 if (!RHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00005944 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005945 << CondTy;
5946 return QualType();
5947 }
5948 // Implicity convert these scalars to the type of the condition.
John Wiegley01296292011-04-08 18:41:53 +00005949 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5950 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begemanabb5a732010-09-20 22:41:17 +00005951 }
5952
Chris Lattnere2949f42008-01-06 22:42:25 +00005953 // If both operands have arithmetic type, do the usual arithmetic conversions
5954 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00005955 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5956 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005957 if (LHS.isInvalid() || RHS.isInvalid())
5958 return QualType();
5959 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00005960 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005961
Chris Lattnere2949f42008-01-06 22:42:25 +00005962 // If both operands are the same structure or union type, the result is that
5963 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005964 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5965 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00005966 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005967 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00005968 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00005969 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00005970 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005971 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005972
Chris Lattnere2949f42008-01-06 22:42:25 +00005973 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00005974 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00005975 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5976 if (!LHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00005977 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5978 << RHS.get()->getSourceRange();
Chris Lattner432cff52009-02-18 04:28:32 +00005979 if (!RHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00005980 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5981 << LHS.get()->getSourceRange();
5982 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
5983 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00005984 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00005985 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00005986 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5987 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00005988 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00005989 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005990 // promote the null to a pointer.
John Wiegley01296292011-04-08 18:41:53 +00005991 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005992 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005993 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005994 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00005995 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5996 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005997 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005998 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005999
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006000 // All objective-c pointer type analysis is done here.
6001 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6002 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00006003 if (LHS.isInvalid() || RHS.isInvalid())
6004 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006005 if (!compositeType.isNull())
6006 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006007
6008
Steve Naroff05efa972009-07-01 14:36:47 +00006009 // Handle block pointer types.
6010 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
6011 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6012 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6013 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00006014 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
6015 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00006016 return destType;
6017 }
6018 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00006019 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00006020 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00006021 }
Steve Naroff05efa972009-07-01 14:36:47 +00006022 // We have 2 block pointer types.
6023 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6024 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00006025 return LHSTy;
6026 }
Steve Naroff05efa972009-07-01 14:36:47 +00006027 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006028 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
6029 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006030
Steve Naroff05efa972009-07-01 14:36:47 +00006031 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
6032 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00006033 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006034 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00006035 // In this situation, we assume void* type. No especially good
6036 // reason, but this is what gcc does, and we do have to pick
6037 // to get a consistent AST.
6038 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00006039 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6040 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00006041 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00006042 }
Steve Naroff05efa972009-07-01 14:36:47 +00006043 // The block pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00006044 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
6045 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00006046 return LHSTy;
6047 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006048
Steve Naroff05efa972009-07-01 14:36:47 +00006049 // Check constraints for C object pointers types (C99 6.5.15p3,6).
6050 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
6051 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006052 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6053 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00006054
6055 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6056 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6057 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00006058 QualType destPointee
6059 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00006060 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00006061 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00006062 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00006063 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00006064 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00006065 return destType;
6066 }
6067 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006068 QualType destPointee
6069 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00006070 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00006071 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00006072 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00006073 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00006074 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00006075 return destType;
6076 }
6077
6078 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6079 // Two identical pointer types are always compatible.
6080 return LHSTy;
6081 }
6082 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
6083 rhptee.getUnqualifiedType())) {
6084 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006085 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00006086 // In this situation, we assume void* type. No especially good
6087 // reason, but this is what gcc does, and we do have to pick
6088 // to get a consistent AST.
6089 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00006090 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6091 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00006092 return incompatTy;
6093 }
6094 // The pointer types are compatible.
6095 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
6096 // differently qualified versions of compatible types, the result type is
6097 // a pointer to an appropriately qualified version of the *composite*
6098 // type.
6099 // FIXME: Need to calculate the composite type.
6100 // FIXME: Need to add qualifiers
John Wiegley01296292011-04-08 18:41:53 +00006101 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
6102 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00006103 return LHSTy;
6104 }
Mike Stump11289f42009-09-09 15:08:12 +00006105
John McCalle84af4e2010-11-13 01:35:44 +00006106 // GCC compatibility: soften pointer/integer mismatch. Note that
6107 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00006108 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
6109 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00006110 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6111 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00006112 return RHSTy;
6113 }
6114 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
6115 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00006116 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6117 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00006118 return LHSTy;
6119 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00006120
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006121 // Emit a better diagnostic if one of the expressions is a null pointer
6122 // constant and the other is not a pointer type. In this case, the user most
6123 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00006124 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006125 return QualType();
6126
Chris Lattnere2949f42008-01-06 22:42:25 +00006127 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00006128 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00006129 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00006130 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00006131}
6132
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006133/// FindCompositeObjCPointerType - Helper method to find composite type of
6134/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00006135QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006136 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00006137 QualType LHSTy = LHS.get()->getType();
6138 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006139
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006140 // Handle things like Class and struct objc_class*. Here we case the result
6141 // to the pseudo-builtin, because that will be implicitly cast back to the
6142 // redefinition type if an attempt is made to access its fields.
6143 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00006144 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006145 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006146 return LHSTy;
6147 }
6148 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00006149 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006150 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006151 return RHSTy;
6152 }
6153 // And the same for struct objc_object* / id
6154 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00006155 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006156 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006157 return LHSTy;
6158 }
6159 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00006160 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006161 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006162 return RHSTy;
6163 }
6164 // And the same for struct objc_selector* / SEL
6165 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00006166 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006167 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006168 return LHSTy;
6169 }
6170 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00006171 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006172 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006173 return RHSTy;
6174 }
6175 // Check constraints for Objective-C object pointers types.
6176 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006177
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006178 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6179 // Two identical object pointer types are always compatible.
6180 return LHSTy;
6181 }
6182 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
6183 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
6184 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006185
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006186 // If both operands are interfaces and either operand can be
6187 // assigned to the other, use that type as the composite
6188 // type. This allows
6189 // xxx ? (A*) a : (B*) b
6190 // where B is a subclass of A.
6191 //
6192 // Additionally, as for assignment, if either type is 'id'
6193 // allow silent coercion. Finally, if the types are
6194 // incompatible then make sure to use 'id' as the composite
6195 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006196
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006197 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6198 // It could return the composite type.
6199 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6200 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6201 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6202 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6203 } else if ((LHSTy->isObjCQualifiedIdType() ||
6204 RHSTy->isObjCQualifiedIdType()) &&
6205 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6206 // Need to handle "id<xx>" explicitly.
6207 // GCC allows qualified id and any Objective-C type to devolve to
6208 // id. Currently localizing to here until clear this should be
6209 // part of ObjCQualifiedIdTypesAreCompatible.
6210 compositeType = Context.getObjCIdType();
6211 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6212 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006213 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006214 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
6215 ;
6216 else {
6217 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6218 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00006219 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006220 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00006221 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6222 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006223 return incompatTy;
6224 }
6225 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00006226 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
6227 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006228 return compositeType;
6229 }
6230 // Check Objective-C object pointer types and 'void *'
6231 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6232 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6233 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6234 QualType destPointee
6235 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6236 QualType destType = Context.getPointerType(destPointee);
6237 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00006238 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006239 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00006240 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006241 return destType;
6242 }
6243 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6244 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6245 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6246 QualType destPointee
6247 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6248 QualType destType = Context.getPointerType(destPointee);
6249 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00006250 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006251 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00006252 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006253 return destType;
6254 }
6255 return QualType();
6256}
6257
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006258/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6259/// ParenRange in parentheses.
6260static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6261 const PartialDiagnostic &PD,
6262 const PartialDiagnostic &FirstNote,
6263 SourceRange FirstParenRange,
6264 const PartialDiagnostic &SecondNote,
6265 SourceRange SecondParenRange) {
6266 Self.Diag(Loc, PD);
6267
6268 if (!FirstNote.getDiagID())
6269 return;
6270
6271 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
6272 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6273 // We can't display the parentheses, so just return.
6274 return;
6275 }
6276
6277 Self.Diag(Loc, FirstNote)
6278 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
6279 << FixItHint::CreateInsertion(EndLoc, ")");
6280
6281 if (!SecondNote.getDiagID())
6282 return;
6283
6284 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
6285 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6286 // We can't display the parentheses, so just dig the
6287 // warning/error and return.
6288 Self.Diag(Loc, SecondNote);
6289 return;
6290 }
6291
6292 Self.Diag(Loc, SecondNote)
6293 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
6294 << FixItHint::CreateInsertion(EndLoc, ")");
6295}
6296
6297static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6298 return Opc >= BO_Mul && Opc <= BO_Shr;
6299}
6300
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006301/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6302/// expression, either using a built-in or overloaded operator,
6303/// and sets *OpCode to the opcode and *RHS to the right-hand side expression.
6304static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6305 Expr **RHS) {
6306 E = E->IgnoreParenImpCasts();
6307 E = E->IgnoreConversionOperator();
6308 E = E->IgnoreParenImpCasts();
6309
6310 // Built-in binary operator.
6311 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6312 if (IsArithmeticOp(OP->getOpcode())) {
6313 *Opcode = OP->getOpcode();
6314 *RHS = OP->getRHS();
6315 return true;
6316 }
6317 }
6318
6319 // Overloaded operator.
6320 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6321 if (Call->getNumArgs() != 2)
6322 return false;
6323
6324 // Make sure this is really a binary operator that is safe to pass into
6325 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6326 OverloadedOperatorKind OO = Call->getOperator();
6327 if (OO < OO_Plus || OO > OO_Arrow)
6328 return false;
6329
6330 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6331 if (IsArithmeticOp(OpKind)) {
6332 *Opcode = OpKind;
6333 *RHS = Call->getArg(1);
6334 return true;
6335 }
6336 }
6337
6338 return false;
6339}
6340
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006341static bool IsLogicOp(BinaryOperatorKind Opc) {
6342 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
6343}
6344
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006345/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6346/// or is a logical expression such as (x==y) which has int type, but is
6347/// commonly interpreted as boolean.
6348static bool ExprLooksBoolean(Expr *E) {
6349 E = E->IgnoreParenImpCasts();
6350
6351 if (E->getType()->isBooleanType())
6352 return true;
6353 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6354 return IsLogicOp(OP->getOpcode());
6355 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6356 return OP->getOpcode() == UO_LNot;
6357
6358 return false;
6359}
6360
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006361/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6362/// and binary operator are mixed in a way that suggests the programmer assumed
6363/// the conditional operator has higher precedence, for example:
6364/// "int x = a + someBinaryCondition ? 1 : 2".
6365static void DiagnoseConditionalPrecedence(Sema &Self,
6366 SourceLocation OpLoc,
6367 Expr *cond,
6368 Expr *lhs,
6369 Expr *rhs) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006370 BinaryOperatorKind CondOpcode;
6371 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006372
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006373 if (!IsArithmeticBinaryExpr(cond, &CondOpcode, &CondRHS))
6374 return;
6375 if (!ExprLooksBoolean(CondRHS))
6376 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006377
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006378 // The condition is an arithmetic binary expression, with a right-
6379 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006380
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006381 PartialDiagnostic Warn = Self.PDiag(diag::warn_precedence_conditional)
6382 << cond->getSourceRange()
6383 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006384
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006385 PartialDiagnostic FirstNote =
6386 Self.PDiag(diag::note_precedence_conditional_silence)
6387 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006388
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006389 SourceRange FirstParenRange(cond->getLocStart(),
6390 cond->getLocEnd());
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006391
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006392 PartialDiagnostic SecondNote =
6393 Self.PDiag(diag::note_precedence_conditional_first);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006394
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006395 SourceRange SecondParenRange(CondRHS->getLocStart(),
6396 rhs->getLocEnd());
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006397
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006398 SuggestParentheses(Self, OpLoc, Warn, FirstNote, FirstParenRange,
6399 SecondNote, SecondParenRange);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006400}
6401
Steve Naroff83895f72007-09-16 03:34:24 +00006402/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00006403/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00006404ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00006405 SourceLocation ColonLoc,
6406 Expr *CondExpr, Expr *LHSExpr,
6407 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00006408 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6409 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00006410 OpaqueValueExpr *opaqueValue = 0;
6411 Expr *commonExpr = 0;
6412 if (LHSExpr == 0) {
6413 commonExpr = CondExpr;
6414
6415 // We usually want to apply unary conversions *before* saving, except
6416 // in the special case of a C++ l-value conditional.
6417 if (!(getLangOptions().CPlusPlus
6418 && !commonExpr->isTypeDependent()
6419 && commonExpr->getValueKind() == RHSExpr->getValueKind()
6420 && commonExpr->isGLValue()
6421 && commonExpr->isOrdinaryOrBitFieldObject()
6422 && RHSExpr->isOrdinaryOrBitFieldObject()
6423 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00006424 ExprResult commonRes = UsualUnaryConversions(commonExpr);
6425 if (commonRes.isInvalid())
6426 return ExprError();
6427 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00006428 }
6429
6430 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6431 commonExpr->getType(),
6432 commonExpr->getValueKind(),
6433 commonExpr->getObjectKind());
6434 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00006435 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00006436
John McCall7decc9e2010-11-18 06:31:45 +00006437 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00006438 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00006439 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
6440 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00006441 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00006442 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6443 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00006444 return ExprError();
6445
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006446 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6447 RHS.get());
6448
John McCallc07a0c72011-02-17 10:25:35 +00006449 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00006450 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
6451 LHS.take(), ColonLoc,
6452 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00006453
6454 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00006455 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
6456 RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00006457}
6458
John McCallaba90822011-01-31 23:13:11 +00006459// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00006460// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00006461// routine is it effectively iqnores the qualifiers on the top level pointee.
6462// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6463// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00006464static Sema::AssignConvertType
6465checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6466 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6467 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006468
Steve Naroff1f4d7272007-05-11 04:00:31 +00006469 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00006470 const Type *lhptee, *rhptee;
6471 Qualifiers lhq, rhq;
6472 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
6473 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006474
John McCallaba90822011-01-31 23:13:11 +00006475 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006476
6477 // C99 6.5.16.1p1: This following citation is common to constraints
6478 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6479 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00006480 Qualifiers lq;
6481
John McCall31168b02011-06-15 23:02:42 +00006482 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
6483 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
6484 lhq.compatiblyIncludesObjCLifetime(rhq)) {
6485 // Ignore lifetime for further calculation.
6486 lhq.removeObjCLifetime();
6487 rhq.removeObjCLifetime();
6488 }
6489
John McCall4fff8f62011-02-01 00:10:29 +00006490 if (!lhq.compatiblyIncludes(rhq)) {
6491 // Treat address-space mismatches as fatal. TODO: address subspaces
6492 if (lhq.getAddressSpace() != rhq.getAddressSpace())
6493 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6494
John McCall31168b02011-06-15 23:02:42 +00006495 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00006496 // and from void*.
John McCall31168b02011-06-15 23:02:42 +00006497 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
6498 .compatiblyIncludes(
6499 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall78535952011-03-26 02:56:45 +00006500 && (lhptee->isVoidType() || rhptee->isVoidType()))
6501 ; // keep old
6502
John McCall31168b02011-06-15 23:02:42 +00006503 // Treat lifetime mismatches as fatal.
6504 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6505 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6506
John McCall4fff8f62011-02-01 00:10:29 +00006507 // For GCC compatibility, other qualifier mismatches are treated
6508 // as still compatible in C.
6509 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6510 }
Steve Naroff3f597292007-05-11 22:18:03 +00006511
Mike Stump4e1f26a2009-02-19 03:04:26 +00006512 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6513 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00006514 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00006515 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006516 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00006517 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006518
Chris Lattner0a788432008-01-03 22:56:36 +00006519 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006520 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00006521 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00006522 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006523
Chris Lattner0a788432008-01-03 22:56:36 +00006524 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006525 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00006526 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00006527
6528 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006529 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00006530 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00006531 }
John McCall4fff8f62011-02-01 00:10:29 +00006532
Mike Stump4e1f26a2009-02-19 03:04:26 +00006533 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00006534 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00006535 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6536 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00006537 // Check if the pointee types are compatible ignoring the sign.
6538 // We explicitly check for char so that we catch "char" vs
6539 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00006540 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00006541 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006542 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00006543 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006544
Chris Lattnerec3a1562009-10-17 20:33:28 +00006545 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00006546 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006547 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00006548 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00006549
John McCall4fff8f62011-02-01 00:10:29 +00006550 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00006551 // Types are compatible ignoring the sign. Qualifier incompatibility
6552 // takes priority over sign incompatibility because the sign
6553 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00006554 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00006555 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00006556
John McCallaba90822011-01-31 23:13:11 +00006557 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00006558 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006559
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006560 // If we are a multi-level pointer, it's possible that our issue is simply
6561 // one of qualification - e.g. char ** -> const char ** is not allowed. If
6562 // the eventual target type is the same and the pointers have the same
6563 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00006564 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006565 do {
John McCall4fff8f62011-02-01 00:10:29 +00006566 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6567 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00006568 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006569
John McCall4fff8f62011-02-01 00:10:29 +00006570 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00006571 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006572 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006573
Eli Friedman80160bd2009-03-22 23:59:44 +00006574 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00006575 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00006576 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00006577 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00006578}
6579
John McCallaba90822011-01-31 23:13:11 +00006580/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00006581/// block pointer types are compatible or whether a block and normal pointer
6582/// are compatible. It is more restrict than comparing two function pointer
6583// types.
John McCallaba90822011-01-31 23:13:11 +00006584static Sema::AssignConvertType
6585checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
6586 QualType rhsType) {
6587 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6588 assert(rhsType.isCanonical() && "RHS not canonicalized!");
6589
Steve Naroff081c7422008-09-04 15:10:53 +00006590 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006591
Steve Naroff081c7422008-09-04 15:10:53 +00006592 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00006593 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
6594 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006595
John McCallaba90822011-01-31 23:13:11 +00006596 // In C++, the types have to match exactly.
6597 if (S.getLangOptions().CPlusPlus)
6598 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006599
John McCallaba90822011-01-31 23:13:11 +00006600 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006601
Steve Naroff081c7422008-09-04 15:10:53 +00006602 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00006603 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6604 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006605
John McCallaba90822011-01-31 23:13:11 +00006606 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
6607 return Sema::IncompatibleBlockPointer;
6608
Steve Naroff081c7422008-09-04 15:10:53 +00006609 return ConvTy;
6610}
6611
John McCallaba90822011-01-31 23:13:11 +00006612/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006613/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00006614static Sema::AssignConvertType
6615checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6616 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
6617 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
6618
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006619 if (lhsType->isObjCBuiltinType()) {
6620 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00006621 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
6622 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00006623 return Sema::IncompatiblePointer;
6624 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006625 }
6626 if (rhsType->isObjCBuiltinType()) {
6627 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00006628 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
6629 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00006630 return Sema::IncompatiblePointer;
6631 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006632 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006633 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006634 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006635 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006636 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006637
John McCallaba90822011-01-31 23:13:11 +00006638 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
6639 return Sema::CompatiblePointerDiscardsQualifiers;
6640
6641 if (S.Context.typesAreCompatible(lhsType, rhsType))
6642 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006643 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00006644 return Sema::IncompatibleObjCQualifiedId;
6645 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006646}
6647
John McCall29600e12010-11-16 02:32:08 +00006648Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00006649Sema::CheckAssignmentConstraints(SourceLocation Loc,
6650 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00006651 // Fake up an opaque expression. We don't actually care about what
6652 // cast operations are required, so if CheckAssignmentConstraints
6653 // adds casts to this they'll be wasted, but fortunately that doesn't
6654 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00006655 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00006656 ExprResult rhsPtr = &rhs;
John McCall29600e12010-11-16 02:32:08 +00006657 CastKind K = CK_Invalid;
6658
6659 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
6660}
6661
Mike Stump4e1f26a2009-02-19 03:04:26 +00006662/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6663/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00006664/// pointers. Here are some objectionable examples that GCC considers warnings:
6665///
6666/// int a, *pint;
6667/// short *pshort;
6668/// struct foo *pfoo;
6669///
6670/// pint = pshort; // warning: assignment from incompatible pointer type
6671/// a = pint; // warning: assignment makes integer from pointer without a cast
6672/// pint = a; // warning: assignment makes pointer from integer without a cast
6673/// pint = pfoo; // warning: assignment from incompatible pointer type
6674///
6675/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00006676/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00006677///
John McCall8cb679e2010-11-15 09:13:47 +00006678/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00006679Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006680Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCall8cb679e2010-11-15 09:13:47 +00006681 CastKind &Kind) {
John Wiegley01296292011-04-08 18:41:53 +00006682 QualType rhsType = rhs.get()->getType();
John McCall29600e12010-11-16 02:32:08 +00006683
Chris Lattnera52c2f22008-01-04 23:18:45 +00006684 // Get canonical types. We're not formatting these types, just comparing
6685 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00006686 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
6687 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00006688
John McCalle5255932011-01-31 22:28:28 +00006689 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00006690 if (lhsType == rhsType) {
6691 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00006692 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00006693 }
6694
Douglas Gregor6b754842008-10-28 00:22:11 +00006695 // If the left-hand side is a reference type, then we are in a
6696 // (rare!) case where we've allowed the use of references in C,
6697 // e.g., as a parameter type in a built-in function. In this case,
6698 // just make sure that the type referenced is compatible with the
6699 // right-hand side type. The caller is responsible for adjusting
6700 // lhsType so that the resulting expression does not have reference
6701 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006702 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00006703 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
6704 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00006705 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006706 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00006707 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00006708 }
John McCalle5255932011-01-31 22:28:28 +00006709
Nate Begemanbd956c42009-06-28 02:36:38 +00006710 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6711 // to the same ExtVector type.
6712 if (lhsType->isExtVectorType()) {
6713 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00006714 return Incompatible;
6715 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00006716 // CK_VectorSplat does T -> vector T, so first cast to the
6717 // element type.
6718 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
6719 if (elType != rhsType) {
6720 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley01296292011-04-08 18:41:53 +00006721 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00006722 }
6723 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00006724 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006725 }
Nate Begemanbd956c42009-06-28 02:36:38 +00006726 }
Mike Stump11289f42009-09-09 15:08:12 +00006727
John McCalle5255932011-01-31 22:28:28 +00006728 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00006729 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006730 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00006731 // Allow assignments of an AltiVec vector type to an equivalent GCC
6732 // vector type and vice versa
6733 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6734 Kind = CK_BitCast;
6735 return Compatible;
6736 }
6737
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006738 // If we are allowing lax vector conversions, and LHS and RHS are both
6739 // vectors, the total size only needs to be the same. This is a bitcast;
6740 // no bits are changed but the result type is different.
6741 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00006742 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00006743 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006744 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00006745 }
Chris Lattner881a2122008-01-04 23:32:24 +00006746 }
6747 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006748 }
Eli Friedman3360d892008-05-30 18:07:22 +00006749
John McCalle5255932011-01-31 22:28:28 +00006750 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00006751 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00006752 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00006753 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00006754 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006755 }
Eli Friedman3360d892008-05-30 18:07:22 +00006756
John McCalle5255932011-01-31 22:28:28 +00006757 // Conversions to normal pointers.
6758 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
6759 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00006760 if (isa<PointerType>(rhsType)) {
6761 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006762 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00006763 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006764
John McCalle5255932011-01-31 22:28:28 +00006765 // int -> T*
6766 if (rhsType->isIntegerType()) {
6767 Kind = CK_IntegralToPointer; // FIXME: null?
6768 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006769 }
John McCalle5255932011-01-31 22:28:28 +00006770
6771 // C pointers are not compatible with ObjC object pointers,
6772 // with two exceptions:
6773 if (isa<ObjCObjectPointerType>(rhsType)) {
6774 // - conversions to void*
6775 if (lhsPointer->getPointeeType()->isVoidType()) {
6776 Kind = CK_AnyPointerToObjCPointerCast;
6777 return Compatible;
6778 }
6779
6780 // - conversions from 'Class' to the redefinition type
6781 if (rhsType->isObjCClassType() &&
6782 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006783 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006784 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006785 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006786
John McCalle5255932011-01-31 22:28:28 +00006787 Kind = CK_BitCast;
6788 return IncompatiblePointer;
6789 }
6790
6791 // U^ -> void*
6792 if (rhsType->getAs<BlockPointerType>()) {
6793 if (lhsPointer->getPointeeType()->isVoidType()) {
6794 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006795 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006796 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006797 }
John McCalle5255932011-01-31 22:28:28 +00006798
Steve Naroff081c7422008-09-04 15:10:53 +00006799 return Incompatible;
6800 }
6801
John McCalle5255932011-01-31 22:28:28 +00006802 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00006803 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006804 // U^ -> T^
6805 if (rhsType->isBlockPointerType()) {
6806 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00006807 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006808 }
6809
6810 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006811 if (rhsType->isIntegerType()) {
6812 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00006813 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006814 }
6815
John McCalle5255932011-01-31 22:28:28 +00006816 // id -> T^
6817 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6818 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006819 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006820 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006821
John McCalle5255932011-01-31 22:28:28 +00006822 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006823 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00006824 if (RHSPT->getPointeeType()->isVoidType()) {
6825 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006826 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006827 }
John McCall8cb679e2010-11-15 09:13:47 +00006828
Chris Lattnera52c2f22008-01-04 23:18:45 +00006829 return Incompatible;
6830 }
6831
John McCalle5255932011-01-31 22:28:28 +00006832 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006833 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006834 // A* -> B*
6835 if (rhsType->isObjCObjectPointerType()) {
6836 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006837 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006838 }
6839
6840 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00006841 if (rhsType->isIntegerType()) {
6842 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00006843 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006844 }
6845
John McCalle5255932011-01-31 22:28:28 +00006846 // In general, C pointers are not compatible with ObjC object pointers,
6847 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00006848 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006849 // - conversions from 'void*'
6850 if (rhsType->isVoidPointerType()) {
6851 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006852 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006853 }
6854
6855 // - conversions to 'Class' from its redefinition type
6856 if (lhsType->isObjCClassType() &&
6857 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6858 Kind = CK_BitCast;
6859 return Compatible;
6860 }
6861
6862 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006863 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006864 }
John McCalle5255932011-01-31 22:28:28 +00006865
6866 // T^ -> A*
6867 if (rhsType->isBlockPointerType()) {
6868 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006869 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006870 }
6871
Steve Naroff7cae42b2009-07-10 23:34:53 +00006872 return Incompatible;
6873 }
John McCalle5255932011-01-31 22:28:28 +00006874
6875 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00006876 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006877 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006878 if (lhsType == Context.BoolTy) {
6879 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00006880 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006881 }
Eli Friedman3360d892008-05-30 18:07:22 +00006882
John McCalle5255932011-01-31 22:28:28 +00006883 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006884 if (lhsType->isIntegerType()) {
6885 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006886 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006887 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006888
Chris Lattnera52c2f22008-01-04 23:18:45 +00006889 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00006890 }
John McCalle5255932011-01-31 22:28:28 +00006891
6892 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006893 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006894 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006895 if (lhsType == Context.BoolTy) {
6896 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006897 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006898 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006899
John McCalle5255932011-01-31 22:28:28 +00006900 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006901 if (lhsType->isIntegerType()) {
6902 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006903 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006904 }
6905
Steve Naroff7cae42b2009-07-10 23:34:53 +00006906 return Incompatible;
6907 }
Eli Friedman3360d892008-05-30 18:07:22 +00006908
John McCalle5255932011-01-31 22:28:28 +00006909 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00006910 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006911 if (Context.typesAreCompatible(lhsType, rhsType)) {
6912 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00006913 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006914 }
Bill Wendling216423b2007-05-30 06:30:29 +00006915 }
John McCalle5255932011-01-31 22:28:28 +00006916
Steve Naroff98cf3e92007-06-06 18:38:38 +00006917 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00006918}
6919
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006920/// \brief Constructs a transparent union from an expression that is
6921/// used to initialize the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00006922static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006923 QualType UnionType, FieldDecl *Field) {
6924 // Build an initializer list that designates the appropriate member
6925 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00006926 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00006927 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00006928 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006929 SourceLocation());
6930 Initializer->setType(UnionType);
6931 Initializer->setInitializedFieldInUnion(Field);
6932
6933 // Build a compound literal constructing a value of the transparent
6934 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00006935 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00006936 EResult = S.Owned(
6937 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6938 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006939}
6940
6941Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006942Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
6943 QualType FromType = rExpr.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006944
Mike Stump11289f42009-09-09 15:08:12 +00006945 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006946 // transparent_union GCC extension.
6947 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006948 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006949 return Incompatible;
6950
6951 // The field to initialize within the transparent union.
6952 RecordDecl *UD = UT->getDecl();
6953 FieldDecl *InitField = 0;
6954 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006955 for (RecordDecl::field_iterator it = UD->field_begin(),
6956 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006957 it != itend; ++it) {
6958 if (it->getType()->isPointerType()) {
6959 // If the transparent union contains a pointer type, we allow:
6960 // 1) void pointer
6961 // 2) null pointer constant
6962 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006963 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley01296292011-04-08 18:41:53 +00006964 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006965 InitField = *it;
6966 break;
6967 }
Mike Stump11289f42009-09-09 15:08:12 +00006968
John Wiegley01296292011-04-08 18:41:53 +00006969 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006970 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006971 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006972 InitField = *it;
6973 break;
6974 }
6975 }
6976
John McCall8cb679e2010-11-15 09:13:47 +00006977 CastKind Kind = CK_Invalid;
John Wiegley01296292011-04-08 18:41:53 +00006978 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006979 == Compatible) {
John Wiegley01296292011-04-08 18:41:53 +00006980 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006981 InitField = *it;
6982 break;
6983 }
6984 }
6985
6986 if (!InitField)
6987 return Incompatible;
6988
John Wiegley01296292011-04-08 18:41:53 +00006989 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006990 return Compatible;
6991}
6992
Chris Lattner9bad62c2008-01-04 18:04:52 +00006993Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006994Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00006995 if (getLangOptions().CPlusPlus) {
6996 if (!lhsType->isRecordType()) {
6997 // C++ 5.17p3: If the left operand is not of class type, the
6998 // expression is implicitly converted (C++ 4) to the
6999 // cv-unqualified type of the left operand.
John Wiegley01296292011-04-08 18:41:53 +00007000 ExprResult Res = PerformImplicitConversion(rExpr.get(),
7001 lhsType.getUnqualifiedType(),
7002 AA_Assigning);
7003 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00007004 return Incompatible;
John Wiegley01296292011-04-08 18:41:53 +00007005 rExpr = move(Res);
Chris Lattner0d5640c2009-04-12 09:02:39 +00007006 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00007007 }
7008
7009 // FIXME: Currently, we fall through and treat C++ classes like C
7010 // structures.
John McCall34376a62010-12-04 03:47:34 +00007011 }
Douglas Gregor9a657932008-10-21 23:43:52 +00007012
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00007013 // C99 6.5.16.1p1: the left operand is a pointer and the right is
7014 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00007015 if ((lhsType->isPointerType() ||
7016 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00007017 lhsType->isBlockPointerType())
John Wiegley01296292011-04-08 18:41:53 +00007018 && rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007019 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00007020 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00007021 return Compatible;
7022 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007023
Chris Lattnere6dcd502007-10-16 02:55:40 +00007024 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007025 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00007026 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00007027 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00007028 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00007029 // Suppress this for references: C++ 8.5.3p5.
John Wiegley01296292011-04-08 18:41:53 +00007030 if (!lhsType->isReferenceType()) {
7031 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
7032 if (rExpr.isInvalid())
7033 return Incompatible;
7034 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00007035
John McCall8cb679e2010-11-15 09:13:47 +00007036 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007037 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00007038 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007039
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00007040 // C99 6.5.16.1p2: The value of the right operand is converted to the
7041 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00007042 // CheckAssignmentConstraints allows the left-hand side to be a reference,
7043 // so that we can use references in built-in functions even in C.
7044 // The getNonReferenceType() call makes sure that the resulting expression
7045 // does not have reference type.
John Wiegley01296292011-04-08 18:41:53 +00007046 if (result != Incompatible && rExpr.get()->getType() != lhsType)
7047 rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00007048 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007049}
7050
John Wiegley01296292011-04-08 18:41:53 +00007051QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007052 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley01296292011-04-08 18:41:53 +00007053 << lex.get()->getType() << rex.get()->getType()
7054 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00007055 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00007056}
7057
John Wiegley01296292011-04-08 18:41:53 +00007058QualType Sema::CheckVectorOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00007059 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00007060 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00007061 QualType lhsType =
John Wiegley01296292011-04-08 18:41:53 +00007062 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattner574dee62008-07-26 22:17:49 +00007063 QualType rhsType =
John Wiegley01296292011-04-08 18:41:53 +00007064 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007065
Nate Begeman191a6b12008-07-14 18:02:46 +00007066 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00007067 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00007068 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00007069
Nate Begeman191a6b12008-07-14 18:02:46 +00007070 // Handle the case of a vector & extvector type of the same size and element
7071 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00007072 if (getLangOptions().LaxVectorConversions) {
John McCall9dd450b2009-09-21 23:43:11 +00007073 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00007074 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00007075 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00007076 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007077 if (lhsType->isExtVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00007078 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007079 return lhsType;
7080 }
7081
John Wiegley01296292011-04-08 18:41:53 +00007082 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007083 return rhsType;
Eric Christophera613f562010-08-26 00:42:16 +00007084 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
7085 // If we are allowing lax vector conversions, and LHS and RHS are both
7086 // vectors, the total size only needs to be the same. This is a
7087 // bitcast; no bits are changed but the result type is different.
John Wiegley01296292011-04-08 18:41:53 +00007088 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Eric Christophera613f562010-08-26 00:42:16 +00007089 return lhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00007090 }
Eric Christophera613f562010-08-26 00:42:16 +00007091 }
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00007092 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +00007093 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007094
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007095 // Handle the case of equivalent AltiVec and GCC vector types
7096 if (lhsType->isVectorType() && rhsType->isVectorType() &&
7097 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John Wiegley01296292011-04-08 18:41:53 +00007098 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007099 return rhsType;
7100 }
7101
Nate Begemanbd956c42009-06-28 02:36:38 +00007102 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
7103 // swap back (so that we don't reverse the inputs to a subtract, for instance.
7104 bool swapped = false;
7105 if (rhsType->isExtVectorType()) {
7106 swapped = true;
7107 std::swap(rex, lex);
7108 std::swap(rhsType, lhsType);
7109 }
Mike Stump11289f42009-09-09 15:08:12 +00007110
Nate Begeman886448d2009-06-28 19:12:57 +00007111 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00007112 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00007113 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00007114 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00007115 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
7116 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00007117 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00007118 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00007119 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00007120 if (swapped) std::swap(rex, lex);
7121 return lhsType;
7122 }
7123 }
7124 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
7125 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00007126 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
7127 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00007128 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00007129 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00007130 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00007131 if (swapped) std::swap(rex, lex);
7132 return lhsType;
7133 }
Nate Begeman330aaa72007-12-30 02:59:45 +00007134 }
7135 }
Mike Stump11289f42009-09-09 15:08:12 +00007136
Nate Begeman886448d2009-06-28 19:12:57 +00007137 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00007138 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley01296292011-04-08 18:41:53 +00007139 << lex.get()->getType() << rex.get()->getType()
7140 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00007141 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00007142}
7143
Chris Lattnerfaa54172010-01-12 21:23:57 +00007144QualType Sema::CheckMultiplyDivideOperands(
John Wiegley01296292011-04-08 18:41:53 +00007145 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
7146 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00007147 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007148
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007149 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00007150 if (lex.isInvalid() || rex.isInvalid())
7151 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007152
John Wiegley01296292011-04-08 18:41:53 +00007153 if (!lex.get()->getType()->isArithmeticType() ||
7154 !rex.get()->getType()->isArithmeticType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00007155 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007156
Chris Lattnerfaa54172010-01-12 21:23:57 +00007157 // Check for division by zero.
7158 if (isDiv &&
John Wiegley01296292011-04-08 18:41:53 +00007159 rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
7160 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
7161 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007162
Chris Lattnerfaa54172010-01-12 21:23:57 +00007163 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00007164}
7165
Chris Lattnerfaa54172010-01-12 21:23:57 +00007166QualType Sema::CheckRemainderOperands(
John Wiegley01296292011-04-08 18:41:53 +00007167 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
7168 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
7169 if (lex.get()->getType()->hasIntegerRepresentation() &&
7170 rex.get()->getType()->hasIntegerRepresentation())
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00007171 return CheckVectorOperands(Loc, lex, rex);
7172 return InvalidOperands(Loc, lex, rex);
7173 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007174
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007175 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00007176 if (lex.isInvalid() || rex.isInvalid())
7177 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007178
John Wiegley01296292011-04-08 18:41:53 +00007179 if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00007180 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007181
Chris Lattnerfaa54172010-01-12 21:23:57 +00007182 // Check for remainder by zero.
John Wiegley01296292011-04-08 18:41:53 +00007183 if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
7184 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
7185 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007186
Chris Lattnerfaa54172010-01-12 21:23:57 +00007187 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007188}
7189
Chris Lattnerfaa54172010-01-12 21:23:57 +00007190QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00007191 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
7192 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007193 QualType compType = CheckVectorOperands(Loc, lex, rex);
7194 if (CompLHSTy) *CompLHSTy = compType;
7195 return compType;
7196 }
Steve Naroff7a5af782007-07-13 16:58:59 +00007197
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007198 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007199 if (lex.isInvalid() || rex.isInvalid())
7200 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00007201
Steve Naroffe4718892007-04-27 18:30:00 +00007202 // handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00007203 if (lex.get()->getType()->isArithmeticType() &&
7204 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007205 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007206 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007207 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00007208
Eli Friedman8e122982008-05-18 18:08:51 +00007209 // Put any potential pointer into PExp
John Wiegley01296292011-04-08 18:41:53 +00007210 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00007211 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00007212 std::swap(PExp, IExp);
7213
Steve Naroff6b712a72009-07-14 18:25:06 +00007214 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00007215
Eli Friedman8e122982008-05-18 18:08:51 +00007216 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00007217 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00007218
Chris Lattner12bdebb2009-04-24 23:50:08 +00007219 // Check for arithmetic on pointers to incomplete types.
7220 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00007221 if (getLangOptions().CPlusPlus) {
7222 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00007223 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00007224 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00007225 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00007226
7227 // GNU extension: arithmetic on pointer to void
7228 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00007229 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00007230 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00007231 if (getLangOptions().CPlusPlus) {
7232 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00007233 << lex.get()->getType() << lex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007234 return QualType();
7235 }
7236
7237 // GNU extension: arithmetic on pointer to function
7238 Diag(Loc, diag::ext_gnu_ptr_func_arith)
John Wiegley01296292011-04-08 18:41:53 +00007239 << lex.get()->getType() << lex.get()->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00007240 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00007241 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00007242 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00007243 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00007244 PExp->getType()->isObjCObjectPointerType()) &&
7245 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00007246 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
7247 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00007248 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00007249 return QualType();
7250 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00007251 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00007252 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00007253 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
7254 << PointeeTy << PExp->getSourceRange();
7255 return QualType();
7256 }
Mike Stump11289f42009-09-09 15:08:12 +00007257
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007258 if (CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00007259 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman629ffb92009-08-20 04:21:42 +00007260 if (LHSTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +00007261 LHSTy = lex.get()->getType();
Eli Friedman629ffb92009-08-20 04:21:42 +00007262 if (LHSTy->isPromotableIntegerType())
7263 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00007264 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007265 *CompLHSTy = LHSTy;
7266 }
Eli Friedman8e122982008-05-18 18:08:51 +00007267 return PExp->getType();
7268 }
7269 }
7270
Chris Lattner326f7572008-11-18 01:30:42 +00007271 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007272}
7273
Chris Lattner2a3569b2008-04-07 05:30:13 +00007274// C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00007275QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007276 SourceLocation Loc, QualType* CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00007277 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007278 QualType compType = CheckVectorOperands(Loc, lex, rex);
7279 if (CompLHSTy) *CompLHSTy = compType;
7280 return compType;
7281 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007282
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007283 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007284 if (lex.isInvalid() || rex.isInvalid())
7285 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007286
Chris Lattner4d62f422007-12-09 21:53:25 +00007287 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007288
Chris Lattner4d62f422007-12-09 21:53:25 +00007289 // Handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00007290 if (lex.get()->getType()->isArithmeticType() &&
7291 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007292 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007293 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007294 }
Mike Stump11289f42009-09-09 15:08:12 +00007295
Chris Lattner4d62f422007-12-09 21:53:25 +00007296 // Either ptr - int or ptr - ptr.
John Wiegley01296292011-04-08 18:41:53 +00007297 if (lex.get()->getType()->isAnyPointerType()) {
7298 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007299
Douglas Gregorac1fb652009-03-24 19:52:54 +00007300 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007301
Douglas Gregorac1fb652009-03-24 19:52:54 +00007302 bool ComplainAboutVoid = false;
7303 Expr *ComplainAboutFunc = 0;
7304 if (lpointee->isVoidType()) {
7305 if (getLangOptions().CPlusPlus) {
7306 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00007307 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007308 return QualType();
7309 }
7310
7311 // GNU C extension: arithmetic on pointer to void
7312 ComplainAboutVoid = true;
7313 } else if (lpointee->isFunctionType()) {
7314 if (getLangOptions().CPlusPlus) {
7315 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00007316 << lex.get()->getType() << lex.get()->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00007317 return QualType();
7318 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00007319
7320 // GNU C extension: arithmetic on pointer to function
John Wiegley01296292011-04-08 18:41:53 +00007321 ComplainAboutFunc = lex.get();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007322 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00007323 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00007324 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley01296292011-04-08 18:41:53 +00007325 << lex.get()->getSourceRange()
7326 << lex.get()->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00007327 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00007328
Chris Lattner12bdebb2009-04-24 23:50:08 +00007329 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00007330 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00007331 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley01296292011-04-08 18:41:53 +00007332 << lpointee << lex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00007333 return QualType();
7334 }
Mike Stump11289f42009-09-09 15:08:12 +00007335
Chris Lattner4d62f422007-12-09 21:53:25 +00007336 // The result type of a pointer-int computation is the pointer type.
John Wiegley01296292011-04-08 18:41:53 +00007337 if (rex.get()->getType()->isIntegerType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00007338 if (ComplainAboutVoid)
7339 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00007340 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007341 if (ComplainAboutFunc)
7342 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00007343 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00007344 << ComplainAboutFunc->getSourceRange();
7345
John Wiegley01296292011-04-08 18:41:53 +00007346 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
7347 return lex.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007348 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007349
Chris Lattner4d62f422007-12-09 21:53:25 +00007350 // Handle pointer-pointer subtractions.
John Wiegley01296292011-04-08 18:41:53 +00007351 if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00007352 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007353
Douglas Gregorac1fb652009-03-24 19:52:54 +00007354 // RHS must be a completely-type object type.
7355 // Handle the GNU void* extension.
7356 if (rpointee->isVoidType()) {
7357 if (getLangOptions().CPlusPlus) {
7358 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00007359 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007360 return QualType();
7361 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007362
Douglas Gregorac1fb652009-03-24 19:52:54 +00007363 ComplainAboutVoid = true;
7364 } else if (rpointee->isFunctionType()) {
7365 if (getLangOptions().CPlusPlus) {
7366 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00007367 << rex.get()->getType() << rex.get()->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00007368 return QualType();
7369 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00007370
7371 // GNU extension: arithmetic on pointer to function
7372 if (!ComplainAboutFunc)
John Wiegley01296292011-04-08 18:41:53 +00007373 ComplainAboutFunc = rex.get();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007374 } else if (!rpointee->isDependentType() &&
7375 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00007376 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley01296292011-04-08 18:41:53 +00007377 << rex.get()->getSourceRange()
7378 << rex.get()->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00007379 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007380
Eli Friedman168fe152009-05-16 13:54:38 +00007381 if (getLangOptions().CPlusPlus) {
7382 // Pointee types must be the same: C++ [expr.add]
7383 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7384 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00007385 << lex.get()->getType() << rex.get()->getType()
7386 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00007387 return QualType();
7388 }
7389 } else {
7390 // Pointee types must be compatible C99 6.5.6p3
7391 if (!Context.typesAreCompatible(
7392 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7393 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7394 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00007395 << lex.get()->getType() << rex.get()->getType()
7396 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00007397 return QualType();
7398 }
Chris Lattner4d62f422007-12-09 21:53:25 +00007399 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007400
Douglas Gregorac1fb652009-03-24 19:52:54 +00007401 if (ComplainAboutVoid)
7402 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00007403 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007404 if (ComplainAboutFunc)
7405 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00007406 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00007407 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007408
John Wiegley01296292011-04-08 18:41:53 +00007409 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00007410 return Context.getPointerDiffType();
7411 }
7412 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007413
Chris Lattner326f7572008-11-18 01:30:42 +00007414 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00007415}
7416
Douglas Gregor0bf31402010-10-08 23:50:27 +00007417static bool isScopedEnumerationType(QualType T) {
7418 if (const EnumType *ET = dyn_cast<EnumType>(T))
7419 return ET->getDecl()->isScoped();
7420 return false;
7421}
7422
John Wiegley01296292011-04-08 18:41:53 +00007423static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007424 SourceLocation Loc, unsigned Opc,
7425 QualType LHSTy) {
7426 llvm::APSInt Right;
7427 // Check right/shifter operand
John Wiegley01296292011-04-08 18:41:53 +00007428 if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007429 return;
7430
7431 if (Right.isNegative()) {
John Wiegley01296292011-04-08 18:41:53 +00007432 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00007433 S.PDiag(diag::warn_shift_negative)
John Wiegley01296292011-04-08 18:41:53 +00007434 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007435 return;
7436 }
7437 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley01296292011-04-08 18:41:53 +00007438 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007439 if (Right.uge(LeftBits)) {
John Wiegley01296292011-04-08 18:41:53 +00007440 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00007441 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley01296292011-04-08 18:41:53 +00007442 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007443 return;
7444 }
7445 if (Opc != BO_Shl)
7446 return;
7447
7448 // When left shifting an ICE which is signed, we can check for overflow which
7449 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7450 // integers have defined behavior modulo one more than the maximum value
7451 // representable in the result type, so never warn for those.
7452 llvm::APSInt Left;
John Wiegley01296292011-04-08 18:41:53 +00007453 if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007454 LHSTy->hasUnsignedIntegerRepresentation())
7455 return;
7456 llvm::APInt ResultBits =
7457 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7458 if (LeftBits.uge(ResultBits))
7459 return;
7460 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7461 Result = Result.shl(Right);
7462
Ted Kremenek70f05fd2011-06-15 00:54:52 +00007463 // Print the bit representation of the signed integer as an unsigned
7464 // hexadecimal number.
7465 llvm::SmallString<40> HexResult;
7466 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7467
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007468 // If we are only missing a sign bit, this is less likely to result in actual
7469 // bugs -- if the result is cast back to an unsigned type, it will have the
7470 // expected value. Thus we place this behind a different warning that can be
7471 // turned off separately if needed.
7472 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00007473 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
7474 << HexResult.str() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00007475 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007476 return;
7477 }
7478
7479 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Ted Kremenek70f05fd2011-06-15 00:54:52 +00007480 << HexResult.str() << Result.getMinSignedBits() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00007481 << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007482}
7483
Chris Lattner2a3569b2008-04-07 05:30:13 +00007484// C99 6.5.7
John Wiegley01296292011-04-08 18:41:53 +00007485QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007486 unsigned Opc, bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00007487 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley01296292011-04-08 18:41:53 +00007488 if (!lex.get()->getType()->hasIntegerRepresentation() ||
7489 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00007490 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007491
Douglas Gregor0bf31402010-10-08 23:50:27 +00007492 // C++0x: Don't allow scoped enums. FIXME: Use something better than
7493 // hasIntegerRepresentation() above instead of this.
John Wiegley01296292011-04-08 18:41:53 +00007494 if (isScopedEnumerationType(lex.get()->getType()) ||
7495 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00007496 return InvalidOperands(Loc, lex, rex);
7497 }
7498
Nate Begemane46ee9a2009-10-25 02:26:48 +00007499 // Vector shifts promote their scalar inputs to vector type.
John Wiegley01296292011-04-08 18:41:53 +00007500 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Nate Begemane46ee9a2009-10-25 02:26:48 +00007501 return CheckVectorOperands(Loc, lex, rex);
7502
Chris Lattner5c11c412007-12-12 05:47:28 +00007503 // Shifts don't perform usual arithmetic conversions, they just do integer
7504 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007505
John McCall57cdd882010-12-16 19:28:59 +00007506 // For the LHS, do usual unary conversions, but then reset them away
7507 // if this is a compound assignment.
John Wiegley01296292011-04-08 18:41:53 +00007508 ExprResult old_lex = lex;
7509 lex = UsualUnaryConversions(lex.take());
7510 if (lex.isInvalid())
7511 return QualType();
7512 QualType LHSTy = lex.get()->getType();
John McCall57cdd882010-12-16 19:28:59 +00007513 if (isCompAssign) lex = old_lex;
7514
7515 // The RHS is simpler.
John Wiegley01296292011-04-08 18:41:53 +00007516 rex = UsualUnaryConversions(rex.take());
7517 if (rex.isInvalid())
7518 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007519
Ryan Flynnf53fab82009-08-07 16:20:20 +00007520 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007521 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00007522
Chris Lattner5c11c412007-12-12 05:47:28 +00007523 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007524 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00007525}
7526
Chandler Carruth17773fc2010-07-10 12:30:03 +00007527static bool IsWithinTemplateSpecialization(Decl *D) {
7528 if (DeclContext *DC = D->getDeclContext()) {
7529 if (isa<ClassTemplateSpecializationDecl>(DC))
7530 return true;
7531 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7532 return FD->isFunctionTemplateSpecialization();
7533 }
7534 return false;
7535}
7536
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007537// C99 6.5.8, C++ [expr.rel]
John Wiegley01296292011-04-08 18:41:53 +00007538QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007539 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00007540 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007541
Chris Lattner9a152e22009-12-05 05:40:13 +00007542 // Handle vector comparisons separately.
John Wiegley01296292011-04-08 18:41:53 +00007543 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00007544 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007545
John Wiegley01296292011-04-08 18:41:53 +00007546 QualType lType = lex.get()->getType();
7547 QualType rType = rex.get()->getType();
Douglas Gregor1beec452011-03-12 01:48:56 +00007548
John Wiegley01296292011-04-08 18:41:53 +00007549 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
7550 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00007551 QualType LHSStrippedType = LHSStripped->getType();
7552 QualType RHSStrippedType = RHSStripped->getType();
7553
Douglas Gregor1beec452011-03-12 01:48:56 +00007554
7555
Chandler Carruth712563b2011-02-17 08:37:06 +00007556 // Two different enums will raise a warning when compared.
7557 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
7558 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
7559 if (LHSEnumType->getDecl()->getIdentifier() &&
7560 RHSEnumType->getDecl()->getIdentifier() &&
7561 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
7562 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7563 << LHSStrippedType << RHSStrippedType
John Wiegley01296292011-04-08 18:41:53 +00007564 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth712563b2011-02-17 08:37:06 +00007565 }
7566 }
7567 }
7568
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007569 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00007570 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley01296292011-04-08 18:41:53 +00007571 !lex.get()->getLocStart().isMacroID() &&
7572 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00007573 // For non-floating point types, check for self-comparisons of the form
7574 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7575 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00007576 //
7577 // NOTE: Don't warn about comparison expressions resulting from macro
7578 // expansion. Also don't warn about comparisons which are only self
7579 // comparisons within a template specialization. The warnings should catch
7580 // obvious cases in the definition of the template anyways. The idea is to
7581 // warn when the typed comparison operator will always evaluate to the same
7582 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00007583 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00007584 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00007585 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00007586 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00007587 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00007588 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00007589 << (Opc == BO_EQ
7590 || Opc == BO_LE
7591 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00007592 } else if (lType->isArrayType() && rType->isArrayType() &&
7593 !DRL->getDecl()->getType()->isReferenceType() &&
7594 !DRR->getDecl()->getType()->isReferenceType()) {
7595 // what is it always going to eval to?
7596 char always_evals_to;
7597 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00007598 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00007599 always_evals_to = 0; // false
7600 break;
John McCalle3027922010-08-25 11:45:40 +00007601 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00007602 always_evals_to = 1; // true
7603 break;
7604 default:
7605 // best we can say is 'a constant'
7606 always_evals_to = 2; // e.g. array1 <= array2
7607 break;
7608 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00007609 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00007610 << 1 // array
7611 << always_evals_to);
7612 }
7613 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00007614 }
Mike Stump11289f42009-09-09 15:08:12 +00007615
Chris Lattner222b8bd2009-03-08 19:39:53 +00007616 if (isa<CastExpr>(LHSStripped))
7617 LHSStripped = LHSStripped->IgnoreParenCasts();
7618 if (isa<CastExpr>(RHSStripped))
7619 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00007620
Chris Lattner222b8bd2009-03-08 19:39:53 +00007621 // Warn about comparisons against a string constant (unless the other
7622 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007623 Expr *literalString = 0;
7624 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00007625 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007626 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007627 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00007628 literalString = lex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007629 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00007630 } else if ((isa<StringLiteral>(RHSStripped) ||
7631 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007632 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007633 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00007634 literalString = rex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007635 literalStringStripped = RHSStripped;
7636 }
7637
7638 if (literalString) {
7639 std::string resultComparison;
7640 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007641 case BO_LT: resultComparison = ") < 0"; break;
7642 case BO_GT: resultComparison = ") > 0"; break;
7643 case BO_LE: resultComparison = ") <= 0"; break;
7644 case BO_GE: resultComparison = ") >= 0"; break;
7645 case BO_EQ: resultComparison = ") == 0"; break;
7646 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007647 default: assert(false && "Invalid comparison operator");
7648 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007649
Ted Kremenek3427fac2011-02-23 01:52:04 +00007650 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00007651 PDiag(diag::warn_stringcompare)
7652 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00007653 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007654 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00007655 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007656
Douglas Gregorec170db2010-06-08 19:50:34 +00007657 // C99 6.5.8p3 / C99 6.5.9p4
John Wiegley01296292011-04-08 18:41:53 +00007658 if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
Douglas Gregorec170db2010-06-08 19:50:34 +00007659 UsualArithmeticConversions(lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00007660 if (lex.isInvalid() || rex.isInvalid())
7661 return QualType();
7662 }
Douglas Gregorec170db2010-06-08 19:50:34 +00007663 else {
John Wiegley01296292011-04-08 18:41:53 +00007664 lex = UsualUnaryConversions(lex.take());
7665 if (lex.isInvalid())
7666 return QualType();
7667
7668 rex = UsualUnaryConversions(rex.take());
7669 if (rex.isInvalid())
7670 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007671 }
7672
John Wiegley01296292011-04-08 18:41:53 +00007673 lType = lex.get()->getType();
7674 rType = rex.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007675
Douglas Gregorca63811b2008-11-19 03:25:36 +00007676 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007677 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00007678
Chris Lattnerb620c342007-08-26 01:18:55 +00007679 if (isRelational) {
7680 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007681 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007682 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00007683 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007684 if (lType->hasFloatingRepresentation())
John Wiegley01296292011-04-08 18:41:53 +00007685 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007686
Chris Lattnerb620c342007-08-26 01:18:55 +00007687 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007688 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007689 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007690
John Wiegley01296292011-04-08 18:41:53 +00007691 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007692 Expr::NPC_ValueDependentIsNull);
John Wiegley01296292011-04-08 18:41:53 +00007693 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007694 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007695
Douglas Gregorf267edd2010-06-15 21:38:40 +00007696 // All of the following pointer-related warnings are GCC extensions, except
7697 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00007698 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00007699 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007700 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00007701 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007702 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007703
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007704 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00007705 if (LCanPointeeTy == RCanPointeeTy)
7706 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007707 if (!isRelational &&
7708 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7709 // Valid unless comparison between non-null pointer and function pointer
7710 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00007711 // In a SFINAE context, we treat this as a hard error to maintain
7712 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007713 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7714 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00007715 Diag(Loc,
7716 isSFINAEContext()?
7717 diag::err_typecheck_comparison_of_fptr_to_void
7718 : diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00007719 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007720
7721 if (isSFINAEContext())
7722 return QualType();
7723
John Wiegley01296292011-04-08 18:41:53 +00007724 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007725 return ResultTy;
7726 }
7727 }
Anders Carlssona95069c2010-11-04 03:17:43 +00007728
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007729 // C++ [expr.rel]p2:
7730 // [...] Pointer conversions (4.10) and qualification
7731 // conversions (4.4) are performed on pointer operands (or on
7732 // a pointer operand and a null pointer constant) to bring
7733 // them to their composite pointer type. [...]
7734 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007735 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007736 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007737 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007738 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007739 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007740 if (T.isNull()) {
7741 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007742 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007743 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007744 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007745 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007746 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007747 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00007748 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007749 }
7750
John Wiegley01296292011-04-08 18:41:53 +00007751 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7752 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007753 return ResultTy;
7754 }
Eli Friedman16c209612009-08-23 00:27:47 +00007755 // C99 6.5.9p2 and C99 6.5.8p2
7756 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7757 RCanPointeeTy.getUnqualifiedType())) {
7758 // Valid unless a relational comparison of function pointers
7759 if (isRelational && LCanPointeeTy->isFunctionType()) {
7760 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007761 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007762 }
7763 } else if (!isRelational &&
7764 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7765 // Valid unless comparison between non-null pointer and function pointer
7766 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7767 && !LHSIsNull && !RHSIsNull) {
7768 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00007769 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007770 }
7771 } else {
7772 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00007773 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007774 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00007775 }
John McCall7684dde2011-03-11 04:25:25 +00007776 if (LCanPointeeTy != RCanPointeeTy) {
7777 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007778 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007779 else
John Wiegley01296292011-04-08 18:41:53 +00007780 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007781 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00007782 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00007783 }
Mike Stump11289f42009-09-09 15:08:12 +00007784
Sebastian Redl576fd422009-05-10 18:38:11 +00007785 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00007786 // Comparison of nullptr_t with itself.
7787 if (lType->isNullPtrType() && rType->isNullPtrType())
7788 return ResultTy;
7789
Mike Stump11289f42009-09-09 15:08:12 +00007790 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007791 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00007792 if (RHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00007793 ((lType->isAnyPointerType() || lType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007794 (!isRelational && lType->isMemberPointerType()))) {
John Wiegley01296292011-04-08 18:41:53 +00007795 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00007796 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007797 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007798 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007799 return ResultTy;
7800 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007801 if (LHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00007802 ((rType->isAnyPointerType() || rType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007803 (!isRelational && rType->isMemberPointerType()))) {
John Wiegley01296292011-04-08 18:41:53 +00007804 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00007805 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007806 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007807 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007808 return ResultTy;
7809 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007810
7811 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00007812 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007813 lType->isMemberPointerType() && rType->isMemberPointerType()) {
7814 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00007815 // In addition, pointers to members can be compared, or a pointer to
7816 // member and a null pointer constant. Pointer to member conversions
7817 // (4.11) and qualification conversions (4.4) are performed to bring
7818 // them to a common type. If one operand is a null pointer constant,
7819 // the common type is the type of the other operand. Otherwise, the
7820 // common type is a pointer to member type similar (4.4) to the type
7821 // of one of the operands, with a cv-qualification signature (4.4)
7822 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007823 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007824 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007825 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007826 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007827 if (T.isNull()) {
7828 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007829 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007830 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007831 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007832 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007833 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007834 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00007835 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007836 }
Mike Stump11289f42009-09-09 15:08:12 +00007837
John Wiegley01296292011-04-08 18:41:53 +00007838 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7839 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007840 return ResultTy;
7841 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007842
7843 // Handle scoped enumeration types specifically, since they don't promote
7844 // to integers.
John Wiegley01296292011-04-08 18:41:53 +00007845 if (lex.get()->getType()->isEnumeralType() &&
7846 Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007847 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00007848 }
Mike Stump11289f42009-09-09 15:08:12 +00007849
Steve Naroff081c7422008-09-04 15:10:53 +00007850 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00007851 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007852 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7853 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007854
Steve Naroff081c7422008-09-04 15:10:53 +00007855 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007856 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007857 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00007858 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007859 }
John Wiegley01296292011-04-08 18:41:53 +00007860 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007861 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007862 }
John Wiegley01296292011-04-08 18:41:53 +00007863
Steve Naroffe18f94c2008-09-28 01:11:11 +00007864 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00007865 if (!isRelational
7866 && ((lType->isBlockPointerType() && rType->isPointerType())
7867 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007868 if (!LHSIsNull && !RHSIsNull) {
John McCall7684dde2011-03-11 04:25:25 +00007869 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007870 ->getPointeeType()->isVoidType())
John McCall7684dde2011-03-11 04:25:25 +00007871 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007872 ->getPointeeType()->isVoidType())))
7873 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00007874 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007875 }
John McCall7684dde2011-03-11 04:25:25 +00007876 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007877 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007878 else
John Wiegley01296292011-04-08 18:41:53 +00007879 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007880 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007881 }
Steve Naroff081c7422008-09-04 15:10:53 +00007882
John McCall7684dde2011-03-11 04:25:25 +00007883 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
7884 const PointerType *LPT = lType->getAs<PointerType>();
7885 const PointerType *RPT = rType->getAs<PointerType>();
7886 if (LPT || RPT) {
7887 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7888 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007889
Steve Naroff753567f2008-11-17 19:49:16 +00007890 if (!LPtrToVoid && !RPtrToVoid &&
7891 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007892 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007893 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007894 }
John McCall7684dde2011-03-11 04:25:25 +00007895 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007896 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007897 else
John Wiegley01296292011-04-08 18:41:53 +00007898 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007899 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007900 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007901 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007902 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007903 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007904 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
John McCall7684dde2011-03-11 04:25:25 +00007905 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007906 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007907 else
John Wiegley01296292011-04-08 18:41:53 +00007908 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007909 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007910 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007911 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007912 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7913 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007914 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007915 bool isError = false;
7916 if ((LHSIsNull && lType->isIntegerType()) ||
7917 (RHSIsNull && rType->isIntegerType())) {
7918 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007919 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007920 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007921 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007922 else if (getLangOptions().CPlusPlus) {
7923 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7924 isError = true;
7925 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007926 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007927
Chris Lattnerd99bd522009-08-23 00:03:44 +00007928 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007929 Diag(Loc, DiagID)
John Wiegley01296292011-04-08 18:41:53 +00007930 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007931 if (isError)
7932 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007933 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007934
7935 if (lType->isIntegerType())
John Wiegley01296292011-04-08 18:41:53 +00007936 lex = ImpCastExprToType(lex.take(), rType,
John McCalle84af4e2010-11-13 01:35:44 +00007937 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007938 else
John Wiegley01296292011-04-08 18:41:53 +00007939 rex = ImpCastExprToType(rex.take(), lType,
John McCalle84af4e2010-11-13 01:35:44 +00007940 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007941 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007942 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007943
Steve Naroff4b191572008-09-04 16:56:14 +00007944 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00007945 if (!isRelational && RHSIsNull
7946 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley01296292011-04-08 18:41:53 +00007947 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007948 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007949 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00007950 if (!isRelational && LHSIsNull
7951 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley01296292011-04-08 18:41:53 +00007952 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007953 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007954 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007955
Chris Lattner326f7572008-11-18 01:30:42 +00007956 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007957}
7958
Nate Begeman191a6b12008-07-14 18:02:46 +00007959/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007960/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007961/// like a scalar comparison, a vector comparison produces a vector of integer
7962/// types.
John Wiegley01296292011-04-08 18:41:53 +00007963QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner326f7572008-11-18 01:30:42 +00007964 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00007965 bool isRelational) {
7966 // Check to make sure we're operating on vectors of the same type and width,
7967 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00007968 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00007969 if (vType.isNull())
7970 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007971
John Wiegley01296292011-04-08 18:41:53 +00007972 QualType lType = lex.get()->getType();
7973 QualType rType = rex.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007974
Anton Yartsev530deb92011-03-27 15:36:07 +00007975 // If AltiVec, the comparison results in a numeric type, i.e.
7976 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00007977 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00007978 return Context.getLogicalOperationType();
7979
Nate Begeman191a6b12008-07-14 18:02:46 +00007980 // For non-floating point types, check for self-comparisons of the form
7981 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7982 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007983 if (!lType->hasFloatingRepresentation()) {
John Wiegley01296292011-04-08 18:41:53 +00007984 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
7985 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00007986 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007987 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007988 PDiag(diag::warn_comparison_always)
7989 << 0 // self-
7990 << 2 // "a constant"
7991 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007992 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007993
Nate Begeman191a6b12008-07-14 18:02:46 +00007994 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007995 if (!isRelational && lType->hasFloatingRepresentation()) {
7996 assert (rType->hasFloatingRepresentation());
John Wiegley01296292011-04-08 18:41:53 +00007997 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00007998 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007999
Nate Begeman191a6b12008-07-14 18:02:46 +00008000 // Return the type for the comparison, which is the same as vector type for
8001 // integer vectors, or an integer type of identical size and number of
8002 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00008003 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00008004 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008005
John McCall9dd450b2009-09-21 23:43:11 +00008006 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00008007 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008008 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00008009 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00008010 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008011 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
8012
Mike Stump4e1f26a2009-02-19 03:04:26 +00008013 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008014 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00008015 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
8016}
8017
Steve Naroff218bc2b2007-05-04 21:54:46 +00008018inline QualType Sema::CheckBitwiseOperands(
John Wiegley01296292011-04-08 18:41:53 +00008019 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
8020 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
8021 if (lex.get()->getType()->hasIntegerRepresentation() &&
8022 rex.get()->getType()->hasIntegerRepresentation())
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00008023 return CheckVectorOperands(Loc, lex, rex);
8024
8025 return InvalidOperands(Loc, lex, rex);
8026 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00008027
John Wiegley01296292011-04-08 18:41:53 +00008028 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
8029 QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
8030 if (lexResult.isInvalid() || rexResult.isInvalid())
8031 return QualType();
8032 lex = lexResult.take();
8033 rex = rexResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008034
John Wiegley01296292011-04-08 18:41:53 +00008035 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
8036 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00008037 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00008038 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00008039}
8040
Steve Naroff218bc2b2007-05-04 21:54:46 +00008041inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley01296292011-04-08 18:41:53 +00008042 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00008043
8044 // Diagnose cases where the user write a logical and/or but probably meant a
8045 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
8046 // is a constant.
John Wiegley01296292011-04-08 18:41:53 +00008047 if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
8048 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00008049 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00008050 !Loc.isMacroID()) {
8051 // If the RHS can be constant folded, and if it constant folds to something
8052 // that isn't 0 or 1 (which indicate a potential logical operation that
8053 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00008054 // Parens on the RHS are ignored.
Chris Lattner938533d2010-07-24 01:10:11 +00008055 Expr::EvalResult Result;
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00008056 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
8057 if ((getLangOptions().Bool && !rex.get()->getType()->isBooleanType()) ||
8058 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
8059 Diag(Loc, diag::warn_logical_instead_of_bitwise)
8060 << rex.get()->getSourceRange()
8061 << (Opc == BO_LAnd ? "&&" : "||")
8062 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00008063 }
8064 }
Chris Lattner8406c512010-07-13 19:41:32 +00008065
Anders Carlsson2e7bc112009-11-23 21:47:44 +00008066 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00008067 lex = UsualUnaryConversions(lex.take());
8068 if (lex.isInvalid())
8069 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008070
John Wiegley01296292011-04-08 18:41:53 +00008071 rex = UsualUnaryConversions(rex.take());
8072 if (rex.isInvalid())
8073 return QualType();
8074
8075 if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00008076 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008077
Anders Carlsson2e7bc112009-11-23 21:47:44 +00008078 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00008079 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008080
John McCall4a2429a2010-06-04 00:29:51 +00008081 // The following is safe because we only use this method for
8082 // non-overloadable operands.
8083
Anders Carlsson2e7bc112009-11-23 21:47:44 +00008084 // C++ [expr.log.and]p1
8085 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00008086 // The operands are both contextually converted to type bool.
John Wiegley01296292011-04-08 18:41:53 +00008087 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
8088 if (lexRes.isInvalid())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00008089 return InvalidOperands(Loc, lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00008090 lex = move(lexRes);
8091
8092 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
8093 if (rexRes.isInvalid())
8094 return InvalidOperands(Loc, lex, rex);
8095 rex = move(rexRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008096
Anders Carlsson2e7bc112009-11-23 21:47:44 +00008097 // C++ [expr.log.and]p2
8098 // C++ [expr.log.or]p2
8099 // The result is a bool.
8100 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00008101}
8102
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00008103/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
8104/// is a read-only property; return true if so. A readonly property expression
8105/// depends on various declarations and thus must be treated specially.
8106///
Mike Stump11289f42009-09-09 15:08:12 +00008107static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00008108 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
8109 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00008110 if (PropExpr->isImplicitProperty()) return false;
8111
8112 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
8113 QualType BaseType = PropExpr->isSuperReceiver() ?
8114 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00008115 PropExpr->getBase()->getType();
8116
John McCallb7bd14f2010-12-02 01:19:52 +00008117 if (const ObjCObjectPointerType *OPT =
8118 BaseType->getAsObjCInterfacePointerType())
8119 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
8120 if (S.isPropertyReadonly(PDecl, IFace))
8121 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00008122 }
8123 return false;
8124}
8125
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00008126static bool IsConstProperty(Expr *E, Sema &S) {
8127 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
8128 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
8129 if (PropExpr->isImplicitProperty()) return false;
8130
8131 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
8132 QualType T = PDecl->getType();
8133 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00008134 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00008135 CanQualType CT = S.Context.getCanonicalType(T);
8136 return CT.isConstQualified();
8137 }
8138 return false;
8139}
8140
Fariborz Jahanian071caef2011-03-26 19:48:30 +00008141static bool IsReadonlyMessage(Expr *E, Sema &S) {
8142 if (E->getStmtClass() != Expr::MemberExprClass)
8143 return false;
8144 const MemberExpr *ME = cast<MemberExpr>(E);
8145 NamedDecl *Member = ME->getMemberDecl();
8146 if (isa<FieldDecl>(Member)) {
8147 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
8148 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
8149 return false;
8150 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
8151 }
8152 return false;
8153}
8154
Chris Lattner30bd3272008-11-18 01:22:49 +00008155/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
8156/// emit an error and return true. If so, return false.
8157static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00008158 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00008159 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00008160 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00008161 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
8162 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00008163 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
8164 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00008165 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
8166 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00008167 if (IsLV == Expr::MLV_Valid)
8168 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008169
Chris Lattner30bd3272008-11-18 01:22:49 +00008170 unsigned Diag = 0;
8171 bool NeedType = false;
8172 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00008173 case Expr::MLV_ConstQualified:
8174 Diag = diag::err_typecheck_assign_const;
8175
8176 // In ARC, use some specialized diagnostics for the times when we
8177 // infer const.
8178 if (S.getLangOptions().ObjCAutoRefCount) {
8179 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
8180 if (declRef && isa<VarDecl>(declRef->getDecl())) {
8181 VarDecl *var = cast<VarDecl>(declRef->getDecl());
8182
8183 // If the variable wasn't written with 'const', there are some
8184 // cases where we infer const anyway:
8185 // - self
8186 // - fast enumeration variables
8187 if (!var->getTypeSourceInfo() ||
8188 !var->getTypeSourceInfo()->getType().isConstQualified()) {
8189 ObjCMethodDecl *method = S.getCurMethodDecl();
8190 if (method && var == method->getSelfDecl())
8191 Diag = diag::err_typecheck_arr_assign_self;
8192 else if (var->getType().getObjCLifetime()
8193 == Qualifiers::OCL_ExplicitNone)
8194 Diag = diag::err_typecheck_arr_assign_enumeration;
8195 SourceRange Assign;
8196 if (Loc != OrigLoc)
8197 Assign = SourceRange(OrigLoc, OrigLoc);
8198 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8199 // We need to preserve the AST regardless, so migration tool
8200 // can do its job.
8201 return false;
8202 }
8203 }
8204 }
8205
8206 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008207 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00008208 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
8209 NeedType = true;
8210 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008211 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00008212 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
8213 NeedType = true;
8214 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00008215 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00008216 Diag = diag::err_typecheck_lvalue_casts_not_supported;
8217 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008218 case Expr::MLV_Valid:
8219 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00008220 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008221 case Expr::MLV_MemberFunction:
8222 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00008223 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
8224 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008225 case Expr::MLV_IncompleteType:
8226 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00008227 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00008228 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00008229 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00008230 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00008231 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
8232 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00008233 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00008234 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
8235 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00008236 case Expr::MLV_ReadonlyProperty:
8237 Diag = diag::error_readonly_property_assignment;
8238 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00008239 case Expr::MLV_NoSetterProperty:
8240 Diag = diag::error_nosetter_property_assignment;
8241 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00008242 case Expr::MLV_InvalidMessageExpression:
8243 Diag = diag::error_readonly_message_assignment;
8244 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00008245 case Expr::MLV_SubObjCPropertySetting:
8246 Diag = diag::error_no_subobject_property_setting;
8247 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008248 }
Steve Naroffad373bd2007-07-31 12:34:36 +00008249
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00008250 SourceRange Assign;
8251 if (Loc != OrigLoc)
8252 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00008253 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00008254 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00008255 else
Mike Stump11289f42009-09-09 15:08:12 +00008256 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00008257 return true;
8258}
8259
8260
8261
8262// C99 6.5.16.1
John Wiegley01296292011-04-08 18:41:53 +00008263QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00008264 SourceLocation Loc,
8265 QualType CompoundType) {
8266 // Verify that LHS is a modifiable lvalue, and emit error if not.
8267 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00008268 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00008269
8270 QualType LHSType = LHS->getType();
John Wiegley01296292011-04-08 18:41:53 +00008271 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008272 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00008273 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00008274 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00008275 // Simple assignment "x = y".
John Wiegley01296292011-04-08 18:41:53 +00008276 if (LHS->getObjectKind() == OK_ObjCProperty) {
8277 ExprResult LHSResult = Owned(LHS);
8278 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
8279 if (LHSResult.isInvalid())
8280 return QualType();
8281 LHS = LHSResult.take();
8282 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00008283 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00008284 if (RHS.isInvalid())
8285 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00008286 // Special case of NSObject attributes on c-style pointer types.
8287 if (ConvTy == IncompatiblePointer &&
8288 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00008289 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00008290 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00008291 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00008292 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008293
John McCall7decc9e2010-11-18 06:31:45 +00008294 if (ConvTy == Compatible &&
8295 getLangOptions().ObjCNonFragileABI &&
8296 LHSType->isObjCObjectType())
8297 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
8298 << LHSType;
8299
Chris Lattnerea714382008-08-21 18:04:13 +00008300 // If the RHS is a unary plus or minus, check to see if they = and + are
8301 // right next to each other. If so, the user may have typo'd "x =+ 4"
8302 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00008303 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00008304 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8305 RHSCheck = ICE->getSubExpr();
8306 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00008307 if ((UO->getOpcode() == UO_Plus ||
8308 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00008309 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00008310 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00008311 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
8312 // And there is a space or other character before the subexpr of the
8313 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00008314 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
8315 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00008316 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00008317 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00008318 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00008319 }
Chris Lattnerea714382008-08-21 18:04:13 +00008320 }
John McCall31168b02011-06-15 23:02:42 +00008321
8322 if (ConvTy == Compatible) {
8323 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
8324 checkRetainCycles(LHS, RHS.get());
8325 else
8326 checkUnsafeAssigns(Loc, LHSType, RHS.get());
8327 }
Chris Lattnerea714382008-08-21 18:04:13 +00008328 } else {
8329 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00008330 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00008331 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00008332
Chris Lattner326f7572008-11-18 01:30:42 +00008333 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00008334 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00008335 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008336
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +00008337 CheckForNullPointerDereference(*this, LHS);
Ted Kremenek64699be2011-02-16 01:57:07 +00008338 // Check for trivial buffer overflows.
Ted Kremenekdf26df72011-03-01 18:41:00 +00008339 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremenek64699be2011-02-16 01:57:07 +00008340
Steve Naroff98cf3e92007-06-06 18:38:38 +00008341 // C99 6.5.16p3: The type of an assignment expression is the type of the
8342 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00008343 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00008344 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8345 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00008346 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00008347 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00008348 return (getLangOptions().CPlusPlus
8349 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00008350}
8351
Chris Lattner326f7572008-11-18 01:30:42 +00008352// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00008353static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00008354 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00008355 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00008356
John McCall3aef3d82011-04-10 19:13:55 +00008357 LHS = S.CheckPlaceholderExpr(LHS.take());
8358 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00008359 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00008360 return QualType();
8361
John McCall73d36182010-10-12 07:14:40 +00008362 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8363 // operands, but not unary promotions.
8364 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00008365
John McCall34376a62010-12-04 03:47:34 +00008366 // So we treat the LHS as a ignored value, and in C++ we allow the
8367 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00008368 LHS = S.IgnoredValueConversions(LHS.take());
8369 if (LHS.isInvalid())
8370 return QualType();
John McCall34376a62010-12-04 03:47:34 +00008371
8372 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00008373 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8374 if (RHS.isInvalid())
8375 return QualType();
8376 if (!RHS.get()->getType()->isVoidType())
8377 S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00008378 }
Eli Friedmanba961a92009-03-23 00:24:07 +00008379
John Wiegley01296292011-04-08 18:41:53 +00008380 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00008381}
8382
Steve Naroff7a5af782007-07-13 16:58:59 +00008383/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8384/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00008385static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8386 ExprValueKind &VK,
8387 SourceLocation OpLoc,
8388 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008389 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008390 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008391
Chris Lattner6b0cf142008-11-21 07:05:48 +00008392 QualType ResType = Op->getType();
8393 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00008394
John McCall4bc41ae2010-11-18 19:01:18 +00008395 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00008396 // Decrement of bool is not allowed.
8397 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00008398 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00008399 return QualType();
8400 }
8401 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00008402 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00008403 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00008404 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00008405 } else if (ResType->isAnyPointerType()) {
8406 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00008407
Chris Lattner6b0cf142008-11-21 07:05:48 +00008408 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00008409 if (PointeeTy->isVoidType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008410 if (S.getLangOptions().CPlusPlus) {
8411 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00008412 << Op->getSourceRange();
8413 return QualType();
8414 }
8415
8416 // Pointer to void is a GNU extension in C.
John McCall4bc41ae2010-11-18 19:01:18 +00008417 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00008418 } else if (PointeeTy->isFunctionType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008419 if (S.getLangOptions().CPlusPlus) {
8420 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00008421 << Op->getType() << Op->getSourceRange();
8422 return QualType();
8423 }
8424
John McCall4bc41ae2010-11-18 19:01:18 +00008425 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008426 << ResType << Op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00008427 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
8428 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00008429 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00008430 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00008431 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00008432 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00008433 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
8434 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00008435 << PointeeTy << Op->getSourceRange();
8436 return QualType();
8437 }
Eli Friedman090addd2010-01-03 00:20:48 +00008438 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00008439 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00008440 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008441 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008442 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008443 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00008444 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008445 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8446 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00008447 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
8448 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00008449 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00008450 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00008451 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00008452 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00008453 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008454 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00008455 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00008456 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00008457 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00008458 // In C++, a prefix increment is the same type as the operand. Otherwise
8459 // (in C or with postfix), the increment is the unqualified type of the
8460 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00008461 if (isPrefix && S.getLangOptions().CPlusPlus) {
8462 VK = VK_LValue;
8463 return ResType;
8464 } else {
8465 VK = VK_RValue;
8466 return ResType.getUnqualifiedType();
8467 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00008468}
8469
John Wiegley01296292011-04-08 18:41:53 +00008470ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00008471 assert(E->getValueKind() == VK_LValue &&
8472 E->getObjectKind() == OK_ObjCProperty);
8473 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
8474
Douglas Gregor33823722011-06-11 01:09:30 +00008475 QualType T = E->getType();
8476 QualType ReceiverType;
8477 if (PRE->isObjectReceiver())
8478 ReceiverType = PRE->getBase()->getType();
8479 else if (PRE->isSuperReceiver())
8480 ReceiverType = PRE->getSuperReceiverType();
8481 else
8482 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
8483
John McCall34376a62010-12-04 03:47:34 +00008484 ExprValueKind VK = VK_RValue;
8485 if (PRE->isImplicitProperty()) {
Douglas Gregor33823722011-06-11 01:09:30 +00008486 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00008487 PRE->getImplicitPropertyGetter()) {
Douglas Gregor33823722011-06-11 01:09:30 +00008488 T = getMessageSendResultType(ReceiverType, GetterMethod,
8489 PRE->isClassReceiver(),
8490 PRE->isSuperReceiver());
8491 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00008492 }
8493 else {
8494 Diag(PRE->getLocation(), diag::err_getter_not_found)
8495 << PRE->getBase()->getType();
8496 }
John McCall34376a62010-12-04 03:47:34 +00008497 }
Douglas Gregor33823722011-06-11 01:09:30 +00008498
8499 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCall34376a62010-12-04 03:47:34 +00008500 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00008501
8502 ExprResult Result = MaybeBindToTemporary(E);
8503 if (!Result.isInvalid())
8504 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00008505
8506 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00008507}
8508
John Wiegley01296292011-04-08 18:41:53 +00008509void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
8510 assert(LHS.get()->getValueKind() == VK_LValue &&
8511 LHS.get()->getObjectKind() == OK_ObjCProperty);
8512 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00008513
John McCall31168b02011-06-15 23:02:42 +00008514 bool Consumed = false;
8515
John Wiegley01296292011-04-08 18:41:53 +00008516 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00008517 // If using property-dot syntax notation for assignment, and there is a
8518 // setter, RHS expression is being passed to the setter argument. So,
8519 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00008520 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00008521 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
8522 LHSTy = (*P)->getType();
John McCall31168b02011-06-15 23:02:42 +00008523 Consumed = (getLangOptions().ObjCAutoRefCount &&
8524 (*P)->hasAttr<NSConsumedAttr>());
John McCall34376a62010-12-04 03:47:34 +00008525
8526 // Otherwise, if the getter returns an l-value, just call that.
8527 } else {
John Wiegley01296292011-04-08 18:41:53 +00008528 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00008529 ExprValueKind VK = Expr::getValueKindForType(Result);
8530 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00008531 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
8532 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00008533 return;
John McCallb7bd14f2010-12-02 01:19:52 +00008534 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008535 }
John McCall31168b02011-06-15 23:02:42 +00008536 } else if (getLangOptions().ObjCAutoRefCount) {
8537 const ObjCMethodDecl *setter
8538 = PropRef->getExplicitProperty()->getSetterMethodDecl();
8539 if (setter) {
8540 ObjCMethodDecl::param_iterator P = setter->param_begin();
8541 LHSTy = (*P)->getType();
8542 Consumed = (*P)->hasAttr<NSConsumedAttr>();
8543 }
John McCall34376a62010-12-04 03:47:34 +00008544 }
8545
John McCall31168b02011-06-15 23:02:42 +00008546 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
8547 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008548 InitializedEntity Entity =
John McCall31168b02011-06-15 23:02:42 +00008549 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley01296292011-04-08 18:41:53 +00008550 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCall31168b02011-06-15 23:02:42 +00008551 if (!ArgE.isInvalid()) {
John Wiegley01296292011-04-08 18:41:53 +00008552 RHS = ArgE;
John McCall31168b02011-06-15 23:02:42 +00008553 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
8554 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
8555 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008556 }
8557}
8558
8559
Anders Carlsson806700f2008-02-01 07:15:58 +00008560/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00008561/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008562/// where the declaration is needed for type checking. We only need to
8563/// handle cases when the expression references a function designator
8564/// or is an lvalue. Here are some examples:
8565/// - &(x) => x
8566/// - &*****f => f for f a function designator.
8567/// - &s.xx => s
8568/// - &s.zz[1].yy -> s, if zz is an array
8569/// - *(x + 1) -> x, if x is an array
8570/// - &"123"[2] -> 0
8571/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00008572static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008573 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00008574 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008575 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00008576 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00008577 // If this is an arrow operator, the address is an offset from
8578 // the base's value, so the object the base refers to is
8579 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008580 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00008581 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00008582 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008583 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00008584 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00008585 // FIXME: This code shouldn't be necessary! We should catch the implicit
8586 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00008587 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8588 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8589 if (ICE->getSubExpr()->getType()->isArrayType())
8590 return getPrimaryDecl(ICE->getSubExpr());
8591 }
8592 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00008593 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008594 case Stmt::UnaryOperatorClass: {
8595 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008596
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008597 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008598 case UO_Real:
8599 case UO_Imag:
8600 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008601 return getPrimaryDecl(UO->getSubExpr());
8602 default:
8603 return 0;
8604 }
8605 }
Steve Naroff47500512007-04-19 23:00:49 +00008606 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008607 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00008608 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00008609 // If the result of an implicit cast is an l-value, we care about
8610 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008611 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00008612 default:
8613 return 0;
8614 }
8615}
8616
8617/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00008618/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00008619/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008620/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00008621/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008622/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00008623/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00008624static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
8625 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00008626 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008627 return S.Context.DependentTy;
8628 if (OrigOp->getType() == S.Context.OverloadTy)
8629 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00008630 if (OrigOp->getType() == S.Context.UnknownAnyTy)
8631 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00008632 if (OrigOp->getType() == S.Context.BoundMemberTy) {
8633 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8634 << OrigOp->getSourceRange();
8635 return QualType();
8636 }
John McCall8d08b9b2010-08-27 09:08:28 +00008637
John McCall2979fe02011-04-12 00:42:48 +00008638 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00008639
John McCall8d08b9b2010-08-27 09:08:28 +00008640 // Make sure to ignore parentheses in subsequent checks
8641 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00008642
John McCall4bc41ae2010-11-18 19:01:18 +00008643 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00008644 // Implement C99-only parts of addressof rules.
8645 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00008646 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00008647 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8648 // (assuming the deref expression is valid).
8649 return uOp->getSubExpr()->getType();
8650 }
8651 // Technically, there should be a check for array subscript
8652 // expressions here, but the result of one is always an lvalue anyway.
8653 }
John McCallf3a88602011-02-03 08:15:49 +00008654 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00008655 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00008656
Fariborz Jahanian071caef2011-03-26 19:48:30 +00008657 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00008658 bool sfinae = S.isSFINAEContext();
8659 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8660 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008661 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00008662 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008663 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00008664 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008665 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00008666 } else if (lval == Expr::LV_MemberFunction) {
8667 // If it's an instance method, make a member pointer.
8668 // The expression must have exactly the form &A::foo.
8669
8670 // If the underlying expression isn't a decl ref, give up.
8671 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008672 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008673 << OrigOp->getSourceRange();
8674 return QualType();
8675 }
8676 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8677 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8678
8679 // The id-expression was parenthesized.
8680 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00008681 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008682 << OrigOp->getSourceRange();
8683
8684 // The method was named without a qualifier.
8685 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008686 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008687 << op->getSourceRange();
8688 }
8689
John McCall4bc41ae2010-11-18 19:01:18 +00008690 return S.Context.getMemberPointerType(op->getType(),
8691 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00008692 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00008693 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008694 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00008695 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00008696 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00008697 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00008698 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00008699 return QualType();
8700 }
John McCall086a4642010-11-24 05:12:34 +00008701 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008702 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00008703 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00008704 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00008705 return QualType();
John McCall086a4642010-11-24 05:12:34 +00008706 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00008707 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00008708 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00008709 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008710 return QualType();
John McCall086a4642010-11-24 05:12:34 +00008711 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00008712 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00008713 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00008714 << "property expression" << op->getSourceRange();
8715 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008716 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00008717 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00008718 // with the register storage-class specifier.
8719 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00008720 // in C++ it is not error to take address of a register
8721 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00008722 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00008723 !S.getLangOptions().CPlusPlus) {
8724 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00008725 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00008726 return QualType();
8727 }
John McCalld14a8642009-11-21 08:51:07 +00008728 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008729 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00008730 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00008731 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008732 // Could be a pointer to member, though, if there is an explicit
8733 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00008734 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008735 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008736 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00008737 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008738 S.Diag(OpLoc,
8739 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00008740 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008741 return QualType();
8742 }
Mike Stump11289f42009-09-09 15:08:12 +00008743
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00008744 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8745 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00008746 return S.Context.getMemberPointerType(op->getType(),
8747 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00008748 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008749 }
Anders Carlsson5b535762009-05-16 21:43:42 +00008750 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00008751 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00008752 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008753
Eli Friedmance7f9002009-05-16 23:27:50 +00008754 if (lval == Expr::LV_IncompleteVoidType) {
8755 // Taking the address of a void variable is technically illegal, but we
8756 // allow it in cases which are otherwise valid.
8757 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00008758 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00008759 }
8760
Steve Naroff47500512007-04-19 23:00:49 +00008761 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00008762 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00008763 return S.Context.getObjCObjectPointerType(op->getType());
8764 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00008765}
8766
Chris Lattner9156f1b2010-07-05 19:17:26 +00008767/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00008768static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8769 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008770 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008771 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008772
John Wiegley01296292011-04-08 18:41:53 +00008773 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8774 if (ConvResult.isInvalid())
8775 return QualType();
8776 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00008777 QualType OpTy = Op->getType();
8778 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00008779
8780 if (isa<CXXReinterpretCastExpr>(Op)) {
8781 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8782 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8783 Op->getSourceRange());
8784 }
8785
Chris Lattner9156f1b2010-07-05 19:17:26 +00008786 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8787 // is an incomplete type or void. It would be possible to warn about
8788 // dereferencing a void pointer, but it's completely well-defined, and such a
8789 // warning is unlikely to catch any mistakes.
8790 if (const PointerType *PT = OpTy->getAs<PointerType>())
8791 Result = PT->getPointeeType();
8792 else if (const ObjCObjectPointerType *OPT =
8793 OpTy->getAs<ObjCObjectPointerType>())
8794 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00008795 else {
John McCall3aef3d82011-04-10 19:13:55 +00008796 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00008797 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008798 if (PR.take() != Op)
8799 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00008800 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008801
Chris Lattner9156f1b2010-07-05 19:17:26 +00008802 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008803 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00008804 << OpTy << Op->getSourceRange();
8805 return QualType();
8806 }
John McCall4bc41ae2010-11-18 19:01:18 +00008807
8808 // Dereferences are usually l-values...
8809 VK = VK_LValue;
8810
8811 // ...except that certain expressions are never l-values in C.
8812 if (!S.getLangOptions().CPlusPlus &&
8813 IsCForbiddenLValueType(S.Context, Result))
8814 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00008815
8816 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00008817}
Steve Naroff218bc2b2007-05-04 21:54:46 +00008818
John McCalle3027922010-08-25 11:45:40 +00008819static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00008820 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008821 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008822 switch (Kind) {
8823 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00008824 case tok::periodstar: Opc = BO_PtrMemD; break;
8825 case tok::arrowstar: Opc = BO_PtrMemI; break;
8826 case tok::star: Opc = BO_Mul; break;
8827 case tok::slash: Opc = BO_Div; break;
8828 case tok::percent: Opc = BO_Rem; break;
8829 case tok::plus: Opc = BO_Add; break;
8830 case tok::minus: Opc = BO_Sub; break;
8831 case tok::lessless: Opc = BO_Shl; break;
8832 case tok::greatergreater: Opc = BO_Shr; break;
8833 case tok::lessequal: Opc = BO_LE; break;
8834 case tok::less: Opc = BO_LT; break;
8835 case tok::greaterequal: Opc = BO_GE; break;
8836 case tok::greater: Opc = BO_GT; break;
8837 case tok::exclaimequal: Opc = BO_NE; break;
8838 case tok::equalequal: Opc = BO_EQ; break;
8839 case tok::amp: Opc = BO_And; break;
8840 case tok::caret: Opc = BO_Xor; break;
8841 case tok::pipe: Opc = BO_Or; break;
8842 case tok::ampamp: Opc = BO_LAnd; break;
8843 case tok::pipepipe: Opc = BO_LOr; break;
8844 case tok::equal: Opc = BO_Assign; break;
8845 case tok::starequal: Opc = BO_MulAssign; break;
8846 case tok::slashequal: Opc = BO_DivAssign; break;
8847 case tok::percentequal: Opc = BO_RemAssign; break;
8848 case tok::plusequal: Opc = BO_AddAssign; break;
8849 case tok::minusequal: Opc = BO_SubAssign; break;
8850 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8851 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8852 case tok::ampequal: Opc = BO_AndAssign; break;
8853 case tok::caretequal: Opc = BO_XorAssign; break;
8854 case tok::pipeequal: Opc = BO_OrAssign; break;
8855 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008856 }
8857 return Opc;
8858}
8859
John McCalle3027922010-08-25 11:45:40 +00008860static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00008861 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008862 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00008863 switch (Kind) {
8864 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00008865 case tok::plusplus: Opc = UO_PreInc; break;
8866 case tok::minusminus: Opc = UO_PreDec; break;
8867 case tok::amp: Opc = UO_AddrOf; break;
8868 case tok::star: Opc = UO_Deref; break;
8869 case tok::plus: Opc = UO_Plus; break;
8870 case tok::minus: Opc = UO_Minus; break;
8871 case tok::tilde: Opc = UO_Not; break;
8872 case tok::exclaim: Opc = UO_LNot; break;
8873 case tok::kw___real: Opc = UO_Real; break;
8874 case tok::kw___imag: Opc = UO_Imag; break;
8875 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00008876 }
8877 return Opc;
8878}
8879
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008880/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8881/// This warning is only emitted for builtin assignment operations. It is also
8882/// suppressed in the event of macro expansions.
8883static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
8884 SourceLocation OpLoc) {
8885 if (!S.ActiveTemplateInstantiations.empty())
8886 return;
8887 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8888 return;
8889 lhs = lhs->IgnoreParenImpCasts();
8890 rhs = rhs->IgnoreParenImpCasts();
8891 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
8892 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
8893 if (!LeftDeclRef || !RightDeclRef ||
8894 LeftDeclRef->getLocation().isMacroID() ||
8895 RightDeclRef->getLocation().isMacroID())
8896 return;
8897 const ValueDecl *LeftDecl =
8898 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
8899 const ValueDecl *RightDecl =
8900 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
8901 if (LeftDecl != RightDecl)
8902 return;
8903 if (LeftDecl->getType().isVolatileQualified())
8904 return;
8905 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
8906 if (RefTy->getPointeeType().isVolatileQualified())
8907 return;
8908
8909 S.Diag(OpLoc, diag::warn_self_assignment)
8910 << LeftDeclRef->getType()
8911 << lhs->getSourceRange() << rhs->getSourceRange();
8912}
8913
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008914/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8915/// operator @p Opc at location @c TokLoc. This routine only supports
8916/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00008917ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008918 BinaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008919 Expr *lhsExpr, Expr *rhsExpr) {
8920 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008921 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008922 // The following two variables are used for compound assignment operators
8923 QualType CompLHSTy; // Type of LHS after promotions for computation
8924 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00008925 ExprValueKind VK = VK_RValue;
8926 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008927
Douglas Gregor1beec452011-03-12 01:48:56 +00008928 // Check if a 'foo<int>' involved in a binary op, identifies a single
8929 // function unambiguously (i.e. an lvalue ala 13.4)
8930 // But since an assignment can trigger target based overload, exclude it in
8931 // our blind search. i.e:
8932 // template<class T> void f(); template<class T, class U> void f(U);
8933 // f<int> == 0; // resolve f<int> blindly
8934 // void (*p)(int); p = f<int>; // resolve f<int> using target
8935 if (Opc != BO_Assign) {
John McCall3aef3d82011-04-10 19:13:55 +00008936 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall31996342011-04-07 08:22:57 +00008937 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008938 lhs = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00008939
John McCall3aef3d82011-04-10 19:13:55 +00008940 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall31996342011-04-07 08:22:57 +00008941 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008942 rhs = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00008943 }
8944
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008945 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008946 case BO_Assign:
John Wiegley01296292011-04-08 18:41:53 +00008947 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00008948 if (getLangOptions().CPlusPlus &&
John Wiegley01296292011-04-08 18:41:53 +00008949 lhs.get()->getObjectKind() != OK_ObjCProperty) {
8950 VK = lhs.get()->getValueKind();
8951 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008952 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008953 if (!ResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00008954 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008955 break;
John McCalle3027922010-08-25 11:45:40 +00008956 case BO_PtrMemD:
8957 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00008958 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008959 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00008960 break;
John McCalle3027922010-08-25 11:45:40 +00008961 case BO_Mul:
8962 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008963 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00008964 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008965 break;
John McCalle3027922010-08-25 11:45:40 +00008966 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008967 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
8968 break;
John McCalle3027922010-08-25 11:45:40 +00008969 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008970 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
8971 break;
John McCalle3027922010-08-25 11:45:40 +00008972 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008973 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
8974 break;
John McCalle3027922010-08-25 11:45:40 +00008975 case BO_Shl:
8976 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008977 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008978 break;
John McCalle3027922010-08-25 11:45:40 +00008979 case BO_LE:
8980 case BO_LT:
8981 case BO_GE:
8982 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008983 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008984 break;
John McCalle3027922010-08-25 11:45:40 +00008985 case BO_EQ:
8986 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008987 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008988 break;
John McCalle3027922010-08-25 11:45:40 +00008989 case BO_And:
8990 case BO_Xor:
8991 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008992 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
8993 break;
John McCalle3027922010-08-25 11:45:40 +00008994 case BO_LAnd:
8995 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00008996 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008997 break;
John McCalle3027922010-08-25 11:45:40 +00008998 case BO_MulAssign:
8999 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00009000 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00009001 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00009002 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00009003 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9004 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009005 break;
John McCalle3027922010-08-25 11:45:40 +00009006 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00009007 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
9008 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00009009 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9010 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009011 break;
John McCalle3027922010-08-25 11:45:40 +00009012 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00009013 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00009014 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9015 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009016 break;
John McCalle3027922010-08-25 11:45:40 +00009017 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00009018 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00009019 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9020 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009021 break;
John McCalle3027922010-08-25 11:45:40 +00009022 case BO_ShlAssign:
9023 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00009024 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00009025 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00009026 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9027 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009028 break;
John McCalle3027922010-08-25 11:45:40 +00009029 case BO_AndAssign:
9030 case BO_XorAssign:
9031 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00009032 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
9033 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00009034 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9035 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009036 break;
John McCalle3027922010-08-25 11:45:40 +00009037 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00009038 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009039 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
9040 VK = rhs.get()->getValueKind();
9041 OK = rhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00009042 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009043 break;
9044 }
John Wiegley01296292011-04-08 18:41:53 +00009045 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00009046 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00009047 if (CompResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00009048 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
9049 ResultTy, VK, OK, OpLoc));
9050 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00009051 VK = VK_LValue;
John Wiegley01296292011-04-08 18:41:53 +00009052 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00009053 }
John Wiegley01296292011-04-08 18:41:53 +00009054 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
9055 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00009056 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009057}
9058
Sebastian Redl44615072009-10-27 12:10:02 +00009059/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
9060/// operators are mixed in a way that suggests that the programmer forgot that
9061/// comparison operators have higher precedence. The most typical example of
9062/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00009063static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00009064 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00009065 typedef BinaryOperator BinOp;
9066 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
9067 rhsopc = static_cast<BinOp::Opcode>(-1);
9068 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00009069 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00009070 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00009071 rhsopc = BO->getOpcode();
9072
9073 // Subs are not binary operators.
9074 if (lhsopc == -1 && rhsopc == -1)
9075 return;
9076
9077 // Bitwise operations are sometimes used as eager logical ops.
9078 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00009079 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
9080 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00009081 return;
9082
Sebastian Redl44615072009-10-27 12:10:02 +00009083 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00009084 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009085 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00009086 << SourceRange(lhs->getLocStart(), OpLoc)
9087 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009088 Self.PDiag(diag::note_precedence_bitwise_silence)
9089 << BinOp::getOpcodeStr(lhsopc),
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009090 lhs->getSourceRange(),
9091 Self.PDiag(diag::note_precedence_bitwise_first)
9092 << BinOp::getOpcodeStr(Opc),
9093 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
Sebastian Redl44615072009-10-27 12:10:02 +00009094 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00009095 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009096 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00009097 << SourceRange(OpLoc, rhs->getLocEnd())
9098 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009099 Self.PDiag(diag::note_precedence_bitwise_silence)
9100 << BinOp::getOpcodeStr(rhsopc),
9101 rhs->getSourceRange(),
Douglas Gregor89336232010-03-29 23:34:08 +00009102 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00009103 << BinOp::getOpcodeStr(Opc),
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009104 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl43028242009-10-26 15:24:15 +00009105}
9106
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009107/// \brief It accepts a '&&' expr that is inside a '||' one.
9108/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
9109/// in parentheses.
9110static void
9111EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00009112 BinaryOperator *Bop) {
9113 assert(Bop->getOpcode() == BO_LAnd);
9114 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009115 Self.PDiag(diag::warn_logical_and_in_logical_or)
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00009116 << Bop->getSourceRange() << OpLoc,
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009117 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00009118 Bop->getSourceRange(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009119 Self.PDiag(0), SourceRange());
9120}
9121
9122/// \brief Returns true if the given expression can be evaluated as a constant
9123/// 'true'.
9124static bool EvaluatesAsTrue(Sema &S, Expr *E) {
9125 bool Res;
9126 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
9127}
9128
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00009129/// \brief Returns true if the given expression can be evaluated as a constant
9130/// 'false'.
9131static bool EvaluatesAsFalse(Sema &S, Expr *E) {
9132 bool Res;
9133 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
9134}
9135
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009136/// \brief Look for '&&' in the left hand of a '||' expr.
9137static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00009138 Expr *OrLHS, Expr *OrRHS) {
9139 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00009140 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00009141 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
9142 if (EvaluatesAsFalse(S, OrRHS))
9143 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009144 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
9145 if (!EvaluatesAsTrue(S, Bop->getLHS()))
9146 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9147 } else if (Bop->getOpcode() == BO_LOr) {
9148 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
9149 // If it's "a || b && 1 || c" we didn't warn earlier for
9150 // "a || b && 1", but warn now.
9151 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
9152 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
9153 }
9154 }
9155 }
9156}
9157
9158/// \brief Look for '&&' in the right hand of a '||' expr.
9159static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00009160 Expr *OrLHS, Expr *OrRHS) {
9161 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009162 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00009163 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
9164 if (EvaluatesAsFalse(S, OrLHS))
9165 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009166 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
9167 if (!EvaluatesAsTrue(S, Bop->getRHS()))
9168 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00009169 }
9170 }
9171}
9172
Sebastian Redl43028242009-10-26 15:24:15 +00009173/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00009174/// precedence.
John McCalle3027922010-08-25 11:45:40 +00009175static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00009176 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00009177 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00009178 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00009179 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
9180
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009181 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9182 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00009183 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00009184 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
9185 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00009186 }
Sebastian Redl43028242009-10-26 15:24:15 +00009187}
9188
Steve Naroff218bc2b2007-05-04 21:54:46 +00009189// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00009190ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00009191 tok::TokenKind Kind,
9192 Expr *lhs, Expr *rhs) {
9193 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00009194 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
9195 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00009196
Sebastian Redl43028242009-10-26 15:24:15 +00009197 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
9198 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
9199
Douglas Gregor5287f092009-11-05 00:51:44 +00009200 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
9201}
9202
John McCalldadc5752010-08-24 06:29:42 +00009203ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00009204 BinaryOperatorKind Opc,
9205 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00009206 if (getLangOptions().CPlusPlus) {
9207 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009208
John McCall622114c2010-12-06 05:26:58 +00009209 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
9210 UseBuiltinOperator = false;
9211 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
9212 UseBuiltinOperator = true;
9213 } else {
9214 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
9215 !rhs->getType()->isOverloadableType();
9216 }
9217
9218 if (!UseBuiltinOperator) {
9219 // Find all of the overloaded operators visible from this
9220 // point. We perform both an operator-name lookup from the local
9221 // scope and an argument-dependent lookup based on the types of
9222 // the arguments.
9223 UnresolvedSet<16> Functions;
9224 OverloadedOperatorKind OverOp
9225 = BinaryOperator::getOverloadedOperator(Opc);
9226 if (S && OverOp != OO_None)
9227 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
9228 Functions);
9229
9230 // Build the (potentially-overloaded, potentially-dependent)
9231 // binary operation.
9232 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
9233 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00009234 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009235
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009236 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00009237 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00009238}
9239
John McCalldadc5752010-08-24 06:29:42 +00009240ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00009241 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00009242 Expr *InputExpr) {
9243 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00009244 ExprValueKind VK = VK_RValue;
9245 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00009246 QualType resultType;
9247 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00009248 case UO_PreInc:
9249 case UO_PreDec:
9250 case UO_PostInc:
9251 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00009252 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00009253 Opc == UO_PreInc ||
9254 Opc == UO_PostInc,
9255 Opc == UO_PreInc ||
9256 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00009257 break;
John McCalle3027922010-08-25 11:45:40 +00009258 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00009259 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00009260 break;
John McCall31996342011-04-07 08:22:57 +00009261 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00009262 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00009263 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009264 Input = move(resolved);
9265 Input = DefaultFunctionArrayLvalueConversion(Input.take());
9266 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00009267 break;
John McCall31996342011-04-07 08:22:57 +00009268 }
John McCalle3027922010-08-25 11:45:40 +00009269 case UO_Plus:
9270 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00009271 Input = UsualUnaryConversions(Input.take());
9272 if (Input.isInvalid()) return ExprError();
9273 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009274 if (resultType->isDependentType())
9275 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00009276 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9277 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00009278 break;
9279 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
9280 resultType->isEnumeralType())
9281 break;
9282 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00009283 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00009284 resultType->isPointerType())
9285 break;
John McCall36226622010-10-12 02:09:17 +00009286 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00009287 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00009288 if (Input.isInvalid()) return ExprError();
9289 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00009290 }
Douglas Gregord08452f2008-11-19 15:42:04 +00009291
Sebastian Redlc215cfc2009-01-19 00:08:26 +00009292 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00009293 << resultType << Input.get()->getSourceRange());
9294
John McCalle3027922010-08-25 11:45:40 +00009295 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00009296 Input = UsualUnaryConversions(Input.take());
9297 if (Input.isInvalid()) return ExprError();
9298 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009299 if (resultType->isDependentType())
9300 break;
Chris Lattner0d707612008-07-25 23:52:49 +00009301 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9302 if (resultType->isComplexType() || resultType->isComplexIntegerType())
9303 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00009304 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00009305 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00009306 else if (resultType->hasIntegerRepresentation())
9307 break;
9308 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00009309 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00009310 if (Input.isInvalid()) return ExprError();
9311 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00009312 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00009313 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00009314 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00009315 }
Steve Naroff35d85152007-05-07 00:24:15 +00009316 break;
John Wiegley01296292011-04-08 18:41:53 +00009317
John McCalle3027922010-08-25 11:45:40 +00009318 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00009319 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00009320 Input = DefaultFunctionArrayLvalueConversion(Input.take());
9321 if (Input.isInvalid()) return ExprError();
9322 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009323 if (resultType->isDependentType())
9324 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00009325 if (resultType->isScalarType()) {
9326 // C99 6.5.3.3p1: ok, fallthrough;
9327 if (Context.getLangOptions().CPlusPlus) {
9328 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9329 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00009330 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
9331 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00009332 }
John McCall36226622010-10-12 02:09:17 +00009333 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00009334 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00009335 if (Input.isInvalid()) return ExprError();
9336 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00009337 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00009338 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00009339 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00009340 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00009341
Chris Lattnerbe31ed82007-06-02 19:11:33 +00009342 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00009343 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00009344 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00009345 break;
John McCalle3027922010-08-25 11:45:40 +00009346 case UO_Real:
9347 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00009348 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00009349 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00009350 if (Input.isInvalid()) return ExprError();
9351 if (Input.get()->getValueKind() != VK_RValue &&
9352 Input.get()->getObjectKind() == OK_Ordinary)
9353 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00009354 break;
John McCalle3027922010-08-25 11:45:40 +00009355 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00009356 resultType = Input.get()->getType();
9357 VK = Input.get()->getValueKind();
9358 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00009359 break;
Steve Naroff35d85152007-05-07 00:24:15 +00009360 }
John Wiegley01296292011-04-08 18:41:53 +00009361 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00009362 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00009363
John Wiegley01296292011-04-08 18:41:53 +00009364 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00009365 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00009366}
Chris Lattnereefa10e2007-05-28 06:56:27 +00009367
John McCalldadc5752010-08-24 06:29:42 +00009368ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00009369 UnaryOperatorKind Opc,
9370 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00009371 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00009372 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009373 // Find all of the overloaded operators visible from this
9374 // point. We perform both an operator-name lookup from the local
9375 // scope and an argument-dependent lookup based on the types of
9376 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00009377 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00009378 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00009379 if (S && OverOp != OO_None)
9380 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9381 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009382
John McCallb268a282010-08-23 23:25:46 +00009383 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009384 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009385
John McCallb268a282010-08-23 23:25:46 +00009386 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009387}
9388
Douglas Gregor5287f092009-11-05 00:51:44 +00009389// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00009390ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00009391 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00009392 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00009393}
9394
Steve Naroff66356bd2007-09-16 14:56:35 +00009395/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00009396ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00009397 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00009398 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00009399 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00009400 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009401 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00009402}
9403
John McCall31168b02011-06-15 23:02:42 +00009404/// Given the last statement in a statement-expression, check whether
9405/// the result is a producing expression (like a call to an
9406/// ns_returns_retained function) and, if so, rebuild it to hoist the
9407/// release out of the full-expression. Otherwise, return null.
9408/// Cannot fail.
9409static Expr *maybeRebuildARCConsumingStmt(Stmt *s) {
9410 // Should always be wrapped with one of these.
9411 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(s);
9412 if (!cleanups) return 0;
9413
9414 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
9415 if (!cast || cast->getCastKind() != CK_ObjCConsumeObject)
9416 return 0;
9417
9418 // Splice out the cast. This shouldn't modify any interesting
9419 // features of the statement.
9420 Expr *producer = cast->getSubExpr();
9421 assert(producer->getType() == cast->getType());
9422 assert(producer->getValueKind() == cast->getValueKind());
9423 cleanups->setSubExpr(producer);
9424 return cleanups;
9425}
9426
John McCalldadc5752010-08-24 06:29:42 +00009427ExprResult
John McCallb268a282010-08-23 23:25:46 +00009428Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009429 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00009430 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9431 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9432
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00009433 bool isFileScope
9434 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00009435 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009436 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00009437
Chris Lattner366727f2007-07-24 16:58:17 +00009438 // FIXME: there are a variety of strange constraints to enforce here, for
9439 // example, it is not possible to goto into a stmt expression apparently.
9440 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00009441
Chris Lattner366727f2007-07-24 16:58:17 +00009442 // If there are sub stmts in the compound stmt, take the type of the last one
9443 // as the type of the stmtexpr.
9444 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009445 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00009446 if (!Compound->body_empty()) {
9447 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009448 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00009449 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009450 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9451 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00009452 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009453 }
John McCall31168b02011-06-15 23:02:42 +00009454
John Wiegley01296292011-04-08 18:41:53 +00009455 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00009456 // Do function/array conversion on the last expression, but not
9457 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00009458 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9459 if (LastExpr.isInvalid())
9460 return ExprError();
9461 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00009462
John Wiegley01296292011-04-08 18:41:53 +00009463 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00009464 // In ARC, if the final expression ends in a consume, splice
9465 // the consume out and bind it later. In the alternate case
9466 // (when dealing with a retainable type), the result
9467 // initialization will create a produce. In both cases the
9468 // result will be +1, and we'll need to balance that out with
9469 // a bind.
9470 if (Expr *rebuiltLastStmt
9471 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9472 LastExpr = rebuiltLastStmt;
9473 } else {
9474 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009475 InitializedEntity::InitializeResult(LPLoc,
9476 Ty,
9477 false),
9478 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00009479 LastExpr);
9480 }
9481
John Wiegley01296292011-04-08 18:41:53 +00009482 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009483 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009484 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009485 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00009486 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009487 else
John Wiegley01296292011-04-08 18:41:53 +00009488 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009489 StmtExprMayBindToTemp = true;
9490 }
9491 }
9492 }
Chris Lattner944d3062008-07-26 19:51:01 +00009493 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009494
Eli Friedmanba961a92009-03-23 00:24:07 +00009495 // FIXME: Check that expression type is complete/non-abstract; statement
9496 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009497 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9498 if (StmtExprMayBindToTemp)
9499 return MaybeBindToTemporary(ResStmtExpr);
9500 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00009501}
Steve Naroff78864672007-08-01 22:05:33 +00009502
John McCalldadc5752010-08-24 06:29:42 +00009503ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009504 TypeSourceInfo *TInfo,
9505 OffsetOfComponent *CompPtr,
9506 unsigned NumComponents,
9507 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00009508 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009509 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00009510 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00009511
Chris Lattnerf17bd422007-08-30 17:45:32 +00009512 // We must have at least one component that refers to the type, and the first
9513 // one is known to be a field designator. Verify that the ArgTy represents
9514 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009515 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00009516 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9517 << ArgTy << TypeRange);
9518
9519 // Type must be complete per C99 7.17p3 because a declaring a variable
9520 // with an incomplete type would be ill-formed.
9521 if (!Dependent
9522 && RequireCompleteType(BuiltinLoc, ArgTy,
9523 PDiag(diag::err_offsetof_incomplete_type)
9524 << TypeRange))
9525 return ExprError();
9526
Chris Lattner78502cf2007-08-31 21:49:13 +00009527 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9528 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00009529 // FIXME: This diagnostic isn't actually visible because the location is in
9530 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00009531 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00009532 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9533 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00009534
9535 bool DidWarnAboutNonPOD = false;
9536 QualType CurrentType = ArgTy;
9537 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9538 llvm::SmallVector<OffsetOfNode, 4> Comps;
9539 llvm::SmallVector<Expr*, 4> Exprs;
9540 for (unsigned i = 0; i != NumComponents; ++i) {
9541 const OffsetOfComponent &OC = CompPtr[i];
9542 if (OC.isBrackets) {
9543 // Offset of an array sub-field. TODO: Should we allow vector elements?
9544 if (!CurrentType->isDependentType()) {
9545 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9546 if(!AT)
9547 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9548 << CurrentType);
9549 CurrentType = AT->getElementType();
9550 } else
9551 CurrentType = Context.DependentTy;
9552
9553 // The expression must be an integral expression.
9554 // FIXME: An integral constant expression?
9555 Expr *Idx = static_cast<Expr*>(OC.U.E);
9556 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9557 !Idx->getType()->isIntegerType())
9558 return ExprError(Diag(Idx->getLocStart(),
9559 diag::err_typecheck_subscript_not_integer)
9560 << Idx->getSourceRange());
9561
9562 // Record this array index.
9563 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9564 Exprs.push_back(Idx);
9565 continue;
9566 }
9567
9568 // Offset of a field.
9569 if (CurrentType->isDependentType()) {
9570 // We have the offset of a field, but we can't look into the dependent
9571 // type. Just record the identifier of the field.
9572 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9573 CurrentType = Context.DependentTy;
9574 continue;
9575 }
9576
9577 // We need to have a complete type to look into.
9578 if (RequireCompleteType(OC.LocStart, CurrentType,
9579 diag::err_offsetof_incomplete_type))
9580 return ExprError();
9581
9582 // Look for the designated field.
9583 const RecordType *RC = CurrentType->getAs<RecordType>();
9584 if (!RC)
9585 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9586 << CurrentType);
9587 RecordDecl *RD = RC->getDecl();
9588
9589 // C++ [lib.support.types]p5:
9590 // The macro offsetof accepts a restricted set of type arguments in this
9591 // International Standard. type shall be a POD structure or a POD union
9592 // (clause 9).
9593 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9594 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00009595 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00009596 PDiag(diag::warn_offsetof_non_pod_type)
9597 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9598 << CurrentType))
9599 DidWarnAboutNonPOD = true;
9600 }
9601
9602 // Look for the field.
9603 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9604 LookupQualifiedName(R, RD);
9605 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009606 IndirectFieldDecl *IndirectMemberDecl = 0;
9607 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00009608 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00009609 MemberDecl = IndirectMemberDecl->getAnonField();
9610 }
9611
Douglas Gregor882211c2010-04-28 22:16:22 +00009612 if (!MemberDecl)
9613 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9614 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9615 OC.LocEnd));
9616
Douglas Gregor10982ea2010-04-28 22:36:06 +00009617 // C99 7.17p3:
9618 // (If the specified member is a bit-field, the behavior is undefined.)
9619 //
9620 // We diagnose this as an error.
9621 if (MemberDecl->getBitWidth()) {
9622 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9623 << MemberDecl->getDeclName()
9624 << SourceRange(BuiltinLoc, RParenLoc);
9625 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9626 return ExprError();
9627 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009628
9629 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009630 if (IndirectMemberDecl)
9631 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009632
Douglas Gregord1702062010-04-29 00:18:15 +00009633 // If the member was found in a base class, introduce OffsetOfNodes for
9634 // the base class indirections.
9635 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9636 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009637 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00009638 CXXBasePath &Path = Paths.front();
9639 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9640 B != BEnd; ++B)
9641 Comps.push_back(OffsetOfNode(B->Base));
9642 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009643
Francois Pichet783dd6e2010-11-21 06:08:52 +00009644 if (IndirectMemberDecl) {
9645 for (IndirectFieldDecl::chain_iterator FI =
9646 IndirectMemberDecl->chain_begin(),
9647 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9648 assert(isa<FieldDecl>(*FI));
9649 Comps.push_back(OffsetOfNode(OC.LocStart,
9650 cast<FieldDecl>(*FI), OC.LocEnd));
9651 }
9652 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00009653 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00009654
Douglas Gregor882211c2010-04-28 22:16:22 +00009655 CurrentType = MemberDecl->getType().getNonReferenceType();
9656 }
9657
9658 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9659 TInfo, Comps.data(), Comps.size(),
9660 Exprs.data(), Exprs.size(), RParenLoc));
9661}
Mike Stump4e1f26a2009-02-19 03:04:26 +00009662
John McCalldadc5752010-08-24 06:29:42 +00009663ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00009664 SourceLocation BuiltinLoc,
9665 SourceLocation TypeLoc,
9666 ParsedType argty,
9667 OffsetOfComponent *CompPtr,
9668 unsigned NumComponents,
9669 SourceLocation RPLoc) {
9670
Douglas Gregor882211c2010-04-28 22:16:22 +00009671 TypeSourceInfo *ArgTInfo;
9672 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
9673 if (ArgTy.isNull())
9674 return ExprError();
9675
Eli Friedman06dcfd92010-08-05 10:15:45 +00009676 if (!ArgTInfo)
9677 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9678
9679 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9680 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00009681}
9682
9683
John McCalldadc5752010-08-24 06:29:42 +00009684ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009685 Expr *CondExpr,
9686 Expr *LHSExpr, Expr *RHSExpr,
9687 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00009688 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9689
John McCall7decc9e2010-11-18 06:31:45 +00009690 ExprValueKind VK = VK_RValue;
9691 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009692 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00009693 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00009694 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009695 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00009696 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009697 } else {
9698 // The conditional expression is required to be a constant expression.
9699 llvm::APSInt condEval(32);
9700 SourceLocation ExpLoc;
9701 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009702 return ExprError(Diag(ExpLoc,
9703 diag::err_typecheck_choose_expr_requires_constant)
9704 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00009705
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009706 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00009707 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9708
9709 resType = ActiveExpr->getType();
9710 ValueDependent = ActiveExpr->isValueDependent();
9711 VK = ActiveExpr->getValueKind();
9712 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009713 }
9714
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009715 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00009716 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00009717 resType->isDependentType(),
9718 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00009719}
9720
Steve Naroffc540d662008-09-03 18:15:37 +00009721//===----------------------------------------------------------------------===//
9722// Clang Extensions.
9723//===----------------------------------------------------------------------===//
9724
9725/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009726void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009727 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9728 PushBlockScope(BlockScope, Block);
9729 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009730 if (BlockScope)
9731 PushDeclContext(BlockScope, Block);
9732 else
9733 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009734}
9735
Mike Stump82f071f2009-02-04 22:31:32 +00009736void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00009737 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00009738 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009739 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009740
John McCall8cb7bdf2010-06-04 23:28:52 +00009741 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00009742 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00009743
John McCall3882ace2011-01-05 12:14:39 +00009744 // GetTypeForDeclarator always produces a function type for a block
9745 // literal signature. Furthermore, it is always a FunctionProtoType
9746 // unless the function was written with a typedef.
9747 assert(T->isFunctionType() &&
9748 "GetTypeForDeclarator made a non-function block signature");
9749
9750 // Look for an explicit signature in that function type.
9751 FunctionProtoTypeLoc ExplicitSignature;
9752
9753 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9754 if (isa<FunctionProtoTypeLoc>(tmp)) {
9755 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9756
9757 // Check whether that explicit signature was synthesized by
9758 // GetTypeForDeclarator. If so, don't save that as part of the
9759 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00009760 if (ExplicitSignature.getLocalRangeBegin() ==
9761 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00009762 // This would be much cheaper if we stored TypeLocs instead of
9763 // TypeSourceInfos.
9764 TypeLoc Result = ExplicitSignature.getResultLoc();
9765 unsigned Size = Result.getFullDataSize();
9766 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9767 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9768
9769 ExplicitSignature = FunctionProtoTypeLoc();
9770 }
John McCalla3ccba02010-06-04 11:21:44 +00009771 }
Mike Stump11289f42009-09-09 15:08:12 +00009772
John McCall3882ace2011-01-05 12:14:39 +00009773 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9774 CurBlock->FunctionType = T;
9775
9776 const FunctionType *Fn = T->getAs<FunctionType>();
9777 QualType RetTy = Fn->getResultType();
9778 bool isVariadic =
9779 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9780
John McCall8e346702010-06-04 19:02:56 +00009781 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00009782
John McCalla3ccba02010-06-04 11:21:44 +00009783 // Don't allow returning a objc interface by value.
9784 if (RetTy->isObjCObjectType()) {
9785 Diag(ParamInfo.getSourceRange().getBegin(),
9786 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9787 return;
9788 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009789
John McCalla3ccba02010-06-04 11:21:44 +00009790 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00009791 // return type. TODO: what should we do with declarators like:
9792 // ^ * { ... }
9793 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00009794 if (RetTy != Context.DependentTy)
9795 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009796
John McCalla3ccba02010-06-04 11:21:44 +00009797 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00009798 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00009799 if (ExplicitSignature) {
9800 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9801 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009802 if (Param->getIdentifier() == 0 &&
9803 !Param->isImplicit() &&
9804 !Param->isInvalidDecl() &&
9805 !getLangOptions().CPlusPlus)
9806 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00009807 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009808 }
John McCalla3ccba02010-06-04 11:21:44 +00009809
9810 // Fake up parameter variables if we have a typedef, like
9811 // ^ fntype { ... }
9812 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9813 for (FunctionProtoType::arg_type_iterator
9814 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9815 ParmVarDecl *Param =
9816 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9817 ParamInfo.getSourceRange().getBegin(),
9818 *I);
John McCall8e346702010-06-04 19:02:56 +00009819 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00009820 }
Steve Naroffc540d662008-09-03 18:15:37 +00009821 }
John McCalla3ccba02010-06-04 11:21:44 +00009822
John McCall8e346702010-06-04 19:02:56 +00009823 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00009824 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00009825 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00009826 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9827 CurBlock->TheDecl->param_end(),
9828 /*CheckParameterNames=*/false);
9829 }
9830
John McCalla3ccba02010-06-04 11:21:44 +00009831 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00009832 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00009833
John McCall8e346702010-06-04 19:02:56 +00009834 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00009835 Diag(ParamInfo.getAttributes()->getLoc(),
9836 diag::warn_attribute_sentinel_not_variadic) << 1;
9837 // FIXME: remove the attribute.
9838 }
9839
9840 // Put the parameter variables in scope. We can bail out immediately
9841 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00009842 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00009843 return;
9844
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009845 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00009846 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9847 (*AI)->setOwningFunction(CurBlock->TheDecl);
9848
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009849 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009850 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009851 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00009852
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009853 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009854 }
John McCallf7b2fb52010-01-22 00:28:27 +00009855 }
Steve Naroffc540d662008-09-03 18:15:37 +00009856}
9857
9858/// ActOnBlockError - If there is an error parsing a block, this callback
9859/// is invoked to pop the information about the block from the action impl.
9860void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00009861 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00009862 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00009863 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00009864}
9865
9866/// ActOnBlockStmtExpr - This is called when the body of a block statement
9867/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00009868ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00009869 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00009870 // If blocks are disabled, emit an error.
9871 if (!LangOpts.Blocks)
9872 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00009873
Douglas Gregor9a28e842010-03-01 23:15:13 +00009874 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009875
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009876 PopDeclContext();
9877
Steve Naroffc540d662008-09-03 18:15:37 +00009878 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00009879 if (!BSI->ReturnType.isNull())
9880 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009881
Mike Stump3bf1ab42009-07-28 22:04:01 +00009882 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00009883 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00009884
John McCallc63de662011-02-02 13:00:07 +00009885 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00009886 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
9887 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00009888
John McCall8e346702010-06-04 19:02:56 +00009889 // If the user wrote a function type in some form, try to use that.
9890 if (!BSI->FunctionType.isNull()) {
9891 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9892
9893 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9894 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9895
9896 // Turn protoless block types into nullary block types.
9897 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009898 FunctionProtoType::ExtProtoInfo EPI;
9899 EPI.ExtInfo = Ext;
9900 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009901
9902 // Otherwise, if we don't need to change anything about the function type,
9903 // preserve its sugar structure.
9904 } else if (FTy->getResultType() == RetTy &&
9905 (!NoReturn || FTy->getNoReturnAttr())) {
9906 BlockTy = BSI->FunctionType;
9907
9908 // Otherwise, make the minimal modifications to the function type.
9909 } else {
9910 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009911 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9912 EPI.TypeQuals = 0; // FIXME: silently?
9913 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009914 BlockTy = Context.getFunctionType(RetTy,
9915 FPT->arg_type_begin(),
9916 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009917 EPI);
John McCall8e346702010-06-04 19:02:56 +00009918 }
9919
9920 // If we don't have a function type, just build one from nothing.
9921 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009922 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00009923 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00009924 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009925 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009926
John McCall8e346702010-06-04 19:02:56 +00009927 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9928 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009929 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009930
Chris Lattner45542ea2009-04-19 05:28:12 +00009931 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00009932 if (getCurFunction()->NeedsScopeChecking() &&
9933 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00009934 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009935
Chris Lattner60f84492011-02-17 23:58:47 +00009936 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009937
John McCallc63de662011-02-02 13:00:07 +00009938 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCall1d570a72010-08-25 05:56:39 +00009939
Ted Kremenek1767a272011-02-23 01:51:48 +00009940 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9941 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009942 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009943}
9944
John McCalldadc5752010-08-24 06:29:42 +00009945ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00009946 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009947 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009948 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009949 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00009950 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009951}
9952
John McCalldadc5752010-08-24 06:29:42 +00009953ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009954 Expr *E, TypeSourceInfo *TInfo,
9955 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009956 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009957
Eli Friedman121ba0c2008-08-09 23:32:40 +00009958 // Get the va_list type
9959 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009960 if (VaListType->isArrayType()) {
9961 // Deal with implicit array decay; for example, on x86-64,
9962 // va_list is an array, but it's supposed to decay to
9963 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009964 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009965 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00009966 ExprResult Result = UsualUnaryConversions(E);
9967 if (Result.isInvalid())
9968 return ExprError();
9969 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00009970 } else {
9971 // Otherwise, the va_list argument must be an l-value because
9972 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009973 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009974 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009975 return ExprError();
9976 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009977
Douglas Gregorad3150c2009-05-19 23:10:31 +00009978 if (!E->isTypeDependent() &&
9979 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009980 return ExprError(Diag(E->getLocStart(),
9981 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009982 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009983 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009984
David Majnemerc75d1a12011-06-14 05:17:32 +00009985 if (!TInfo->getType()->isDependentType()) {
9986 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
9987 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
9988 << TInfo->getTypeLoc().getSourceRange()))
9989 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00009990
David Majnemerc75d1a12011-06-14 05:17:32 +00009991 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
9992 TInfo->getType(),
9993 PDiag(diag::err_second_parameter_to_va_arg_abstract)
9994 << TInfo->getTypeLoc().getSourceRange()))
9995 return ExprError();
9996
John McCall31168b02011-06-15 23:02:42 +00009997 if (!TInfo->getType().isPODType(Context))
David Majnemerc75d1a12011-06-14 05:17:32 +00009998 Diag(TInfo->getTypeLoc().getBeginLoc(),
9999 diag::warn_second_parameter_to_va_arg_not_pod)
10000 << TInfo->getType()
10001 << TInfo->getTypeLoc().getSourceRange();
10002 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000010003
Abramo Bagnara27db2392010-08-10 10:06:15 +000010004 QualType T = TInfo->getType().getNonLValueExprType(Context);
10005 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +000010006}
10007
John McCalldadc5752010-08-24 06:29:42 +000010008ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +000010009 // The type of __null will be int or long, depending on the size of
10010 // pointers on the target.
10011 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +000010012 unsigned pw = Context.Target.getPointerWidth(0);
10013 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +000010014 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +000010015 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +000010016 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +000010017 else if (pw == Context.Target.getLongLongWidth())
10018 Ty = Context.LongLongTy;
10019 else {
10020 assert(!"I don't know size of pointer!");
10021 Ty = Context.IntTy;
10022 }
Douglas Gregor3be4b122008-11-29 04:51:27 +000010023
Sebastian Redl6d4256c2009-03-15 17:47:39 +000010024 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +000010025}
10026
Alexis Huntc46382e2010-04-28 23:02:27 +000010027static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +000010028 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +000010029 if (!SemaRef.getLangOptions().ObjC1)
10030 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010031
Anders Carlssonace5d072009-11-10 04:46:30 +000010032 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10033 if (!PT)
10034 return;
10035
10036 // Check if the destination is of type 'id'.
10037 if (!PT->isObjCIdType()) {
10038 // Check if the destination is the 'NSString' interface.
10039 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10040 if (!ID || !ID->getIdentifier()->isStr("NSString"))
10041 return;
10042 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010043
Anders Carlssonace5d072009-11-10 04:46:30 +000010044 // Strip off any parens and casts.
10045 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
10046 if (!SL || SL->isWide())
10047 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010048
Douglas Gregora771f462010-03-31 17:46:05 +000010049 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +000010050}
10051
Chris Lattner9bad62c2008-01-04 18:04:52 +000010052bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10053 SourceLocation Loc,
10054 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +000010055 Expr *SrcExpr, AssignmentAction Action,
10056 bool *Complained) {
10057 if (Complained)
10058 *Complained = false;
10059
Chris Lattner9bad62c2008-01-04 18:04:52 +000010060 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +000010061 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +000010062 bool isInvalid = false;
10063 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +000010064 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010065
Chris Lattner9bad62c2008-01-04 18:04:52 +000010066 switch (ConvTy) {
10067 default: assert(0 && "Unknown conversion type");
10068 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +000010069 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +000010070 DiagKind = diag::ext_typecheck_convert_pointer_int;
10071 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +000010072 case IntToPointer:
10073 DiagKind = diag::ext_typecheck_convert_int_pointer;
10074 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +000010075 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +000010076 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +000010077 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +000010078 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10079 SrcType->isObjCObjectPointerType();
Chris Lattner9bad62c2008-01-04 18:04:52 +000010080 break;
Eli Friedman80160bd2009-03-22 23:59:44 +000010081 case IncompatiblePointerSign:
10082 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10083 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +000010084 case FunctionVoidPointer:
10085 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10086 break;
John McCall4fff8f62011-02-01 00:10:29 +000010087 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +000010088 // Perform array-to-pointer decay if necessary.
10089 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10090
John McCall4fff8f62011-02-01 00:10:29 +000010091 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10092 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10093 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10094 DiagKind = diag::err_typecheck_incompatible_address_space;
10095 break;
John McCall31168b02011-06-15 23:02:42 +000010096
10097
10098 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
10099 DiagKind = diag::err_typecheck_incompatible_lifetime;
10100 break;
John McCall4fff8f62011-02-01 00:10:29 +000010101 }
10102
10103 llvm_unreachable("unknown error case for discarding qualifiers!");
10104 // fallthrough
10105 }
Chris Lattner9bad62c2008-01-04 18:04:52 +000010106 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +000010107 // If the qualifiers lost were because we were applying the
10108 // (deprecated) C++ conversion from a string literal to a char*
10109 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
10110 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +000010111 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +000010112 // bit of refactoring (so that the second argument is an
10113 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +000010114 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +000010115 // C++ semantics.
10116 if (getLangOptions().CPlusPlus &&
10117 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10118 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +000010119 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10120 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +000010121 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +000010122 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +000010123 break;
Steve Naroff081c7422008-09-04 15:10:53 +000010124 case IntToBlockPointer:
10125 DiagKind = diag::err_int_to_block_pointer;
10126 break;
10127 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +000010128 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +000010129 break;
Steve Naroff8afa9892008-10-14 22:18:38 +000010130 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +000010131 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +000010132 // it can give a more specific diagnostic.
10133 DiagKind = diag::warn_incompatible_qualified_id;
10134 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +000010135 case IncompatibleVectors:
10136 DiagKind = diag::warn_incompatible_vectors;
10137 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +000010138 case Incompatible:
10139 DiagKind = diag::err_typecheck_convert_incompatible;
10140 isInvalid = true;
10141 break;
10142 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000010143
Douglas Gregorc68e1402010-04-09 00:35:39 +000010144 QualType FirstType, SecondType;
10145 switch (Action) {
10146 case AA_Assigning:
10147 case AA_Initializing:
10148 // The destination type comes first.
10149 FirstType = DstType;
10150 SecondType = SrcType;
10151 break;
Alexis Huntc46382e2010-04-28 23:02:27 +000010152
Douglas Gregorc68e1402010-04-09 00:35:39 +000010153 case AA_Returning:
10154 case AA_Passing:
10155 case AA_Converting:
10156 case AA_Sending:
10157 case AA_Casting:
10158 // The source type comes first.
10159 FirstType = SrcType;
10160 SecondType = DstType;
10161 break;
10162 }
Alexis Huntc46382e2010-04-28 23:02:27 +000010163
Douglas Gregorc68e1402010-04-09 00:35:39 +000010164 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +000010165 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor33823722011-06-11 01:09:30 +000010166 if (CheckInferredResultType)
10167 EmitRelatedResultTypeNote(SrcExpr);
10168
Douglas Gregor4f4946a2010-04-22 00:20:18 +000010169 if (Complained)
10170 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +000010171 return isInvalid;
10172}
Anders Carlssone54e8a12008-11-30 19:50:32 +000010173
Chris Lattnerc71d08b2009-04-25 21:59:05 +000010174bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +000010175 llvm::APSInt ICEResult;
10176 if (E->isIntegerConstantExpr(ICEResult, Context)) {
10177 if (Result)
10178 *Result = ICEResult;
10179 return false;
10180 }
10181
Anders Carlssone54e8a12008-11-30 19:50:32 +000010182 Expr::EvalResult EvalResult;
10183
Mike Stump4e1f26a2009-02-19 03:04:26 +000010184 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +000010185 EvalResult.HasSideEffects) {
10186 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
10187
10188 if (EvalResult.Diag) {
10189 // We only show the note if it's not the usual "invalid subexpression"
10190 // or if it's actually in a subexpression.
10191 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
10192 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
10193 Diag(EvalResult.DiagLoc, EvalResult.Diag);
10194 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000010195
Anders Carlssone54e8a12008-11-30 19:50:32 +000010196 return true;
10197 }
10198
Eli Friedmanbb967cc2009-04-25 22:26:58 +000010199 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
10200 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +000010201
Eli Friedmanbb967cc2009-04-25 22:26:58 +000010202 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +000010203 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
10204 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +000010205 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +000010206
Anders Carlssone54e8a12008-11-30 19:50:32 +000010207 if (Result)
10208 *Result = EvalResult.Val.getInt();
10209 return false;
10210}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010211
Douglas Gregorff790f12009-11-26 00:44:06 +000010212void
Mike Stump11289f42009-09-09 15:08:12 +000010213Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +000010214 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +000010215 ExpressionEvaluationContextRecord(NewContext,
10216 ExprTemporaries.size(),
10217 ExprNeedsCleanups));
10218 ExprNeedsCleanups = false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010219}
10220
Mike Stump11289f42009-09-09 15:08:12 +000010221void
Douglas Gregorff790f12009-11-26 00:44:06 +000010222Sema::PopExpressionEvaluationContext() {
10223 // Pop the current expression evaluation context off the stack.
10224 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
10225 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010226
Douglas Gregorfab31f42009-12-12 07:57:52 +000010227 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
10228 if (Rec.PotentiallyReferenced) {
10229 // Mark any remaining declarations in the current position of the stack
10230 // as "referenced". If they were not meant to be referenced, semantic
10231 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010232 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +000010233 I = Rec.PotentiallyReferenced->begin(),
10234 IEnd = Rec.PotentiallyReferenced->end();
10235 I != IEnd; ++I)
10236 MarkDeclarationReferenced(I->first, I->second);
10237 }
10238
10239 if (Rec.PotentiallyDiagnosed) {
10240 // Emit any pending diagnostics.
10241 for (PotentiallyEmittedDiagnostics::iterator
10242 I = Rec.PotentiallyDiagnosed->begin(),
10243 IEnd = Rec.PotentiallyDiagnosed->end();
10244 I != IEnd; ++I)
10245 Diag(I->first, I->second);
10246 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010247 }
Douglas Gregorff790f12009-11-26 00:44:06 +000010248
10249 // When are coming out of an unevaluated context, clear out any
10250 // temporaries that we may have created as part of the evaluation of
10251 // the expression in that context: they aren't relevant because they
10252 // will never be constructed.
John McCall31168b02011-06-15 23:02:42 +000010253 if (Rec.Context == Unevaluated) {
Douglas Gregorff790f12009-11-26 00:44:06 +000010254 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
10255 ExprTemporaries.end());
John McCall31168b02011-06-15 23:02:42 +000010256 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
10257
10258 // Otherwise, merge the contexts together.
10259 } else {
10260 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
10261 }
Douglas Gregorff790f12009-11-26 00:44:06 +000010262
10263 // Destroy the popped expression evaluation record.
10264 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010265}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010266
John McCall31168b02011-06-15 23:02:42 +000010267void Sema::DiscardCleanupsInEvaluationContext() {
10268 ExprTemporaries.erase(
10269 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
10270 ExprTemporaries.end());
10271 ExprNeedsCleanups = false;
10272}
10273
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010274/// \brief Note that the given declaration was referenced in the source code.
10275///
10276/// This routine should be invoke whenever a given declaration is referenced
10277/// in the source code, and where that reference occurred. If this declaration
10278/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
10279/// C99 6.9p3), then the declaration will be marked as used.
10280///
10281/// \param Loc the location where the declaration was referenced.
10282///
10283/// \param D the declaration that has been referenced by the source code.
10284void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
10285 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +000010286
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +000010287 D->setReferenced();
10288
Douglas Gregorebada0772010-06-17 23:14:26 +000010289 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +000010290 return;
Mike Stump11289f42009-09-09 15:08:12 +000010291
Douglas Gregor3beaf9b2009-10-08 21:35:42 +000010292 // Mark a parameter or variable declaration "used", regardless of whether we're in a
10293 // template or not. The reason for this is that unevaluated expressions
10294 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
10295 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010296 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +000010297 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +000010298 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +000010299 return;
10300 }
Alexis Huntc46382e2010-04-28 23:02:27 +000010301
Douglas Gregorfd27fed2010-04-07 20:29:57 +000010302 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
10303 return;
Alexis Huntc46382e2010-04-28 23:02:27 +000010304
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010305 // Do not mark anything as "used" within a dependent context; wait for
10306 // an instantiation.
10307 if (CurContext->isDependentContext())
10308 return;
Mike Stump11289f42009-09-09 15:08:12 +000010309
Douglas Gregorff790f12009-11-26 00:44:06 +000010310 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010311 case Unevaluated:
10312 // We are in an expression that is not potentially evaluated; do nothing.
10313 return;
Mike Stump11289f42009-09-09 15:08:12 +000010314
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010315 case PotentiallyEvaluated:
10316 // We are in a potentially-evaluated expression, so this declaration is
10317 // "used"; handle this below.
10318 break;
Mike Stump11289f42009-09-09 15:08:12 +000010319
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010320 case PotentiallyPotentiallyEvaluated:
10321 // We are in an expression that may be potentially evaluated; queue this
10322 // declaration reference until we know whether the expression is
10323 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +000010324 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010325 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010326
10327 case PotentiallyEvaluatedIfUsed:
10328 // Referenced declarations will only be used if the construct in the
10329 // containing expression is used.
10330 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010331 }
Mike Stump11289f42009-09-09 15:08:12 +000010332
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010333 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +000010334 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Alexis Huntf92197c2011-05-12 03:51:51 +000010335 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor()) {
10336 if (Constructor->isTrivial())
Chandler Carruthc9262402010-08-23 07:55:51 +000010337 return;
10338 if (!Constructor->isUsed(false))
10339 DefineImplicitDefaultConstructor(Loc, Constructor);
Alexis Hunt22b5b132011-05-14 18:20:50 +000010340 } else if (Constructor->isDefaulted() &&
Alexis Hunt913820d2011-05-13 06:10:58 +000010341 Constructor->isCopyConstructor()) {
Douglas Gregorebada0772010-06-17 23:14:26 +000010342 if (!Constructor->isUsed(false))
Alexis Hunt913820d2011-05-13 06:10:58 +000010343 DefineImplicitCopyConstructor(Loc, Constructor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010344 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010345
Douglas Gregor88d292c2010-05-13 16:44:06 +000010346 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010347 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Alexis Huntf91729462011-05-12 22:46:25 +000010348 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010349 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010350 if (Destructor->isVirtual())
10351 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010352 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Alexis Huntc9a55732011-05-14 05:23:28 +000010353 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010354 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +000010355 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +000010356 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010357 } else if (MethodDecl->isVirtual())
10358 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010359 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +000010360 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +000010361 // Recursive functions should be marked when used from another function.
10362 if (CurContext == Function) return;
10363
Mike Stump11289f42009-09-09 15:08:12 +000010364 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +000010365 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +000010366 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +000010367 bool AlreadyInstantiated = false;
10368 if (FunctionTemplateSpecializationInfo *SpecInfo
10369 = Function->getTemplateSpecializationInfo()) {
10370 if (SpecInfo->getPointOfInstantiation().isInvalid())
10371 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010372 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +000010373 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +000010374 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010375 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +000010376 = Function->getMemberSpecializationInfo()) {
10377 if (MSInfo->getPointOfInstantiation().isInvalid())
10378 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010379 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +000010380 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +000010381 AlreadyInstantiated = true;
10382 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010383
Douglas Gregor7f792cf2010-01-16 22:29:39 +000010384 if (!AlreadyInstantiated) {
10385 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
10386 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
10387 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
10388 Loc));
10389 else
Chandler Carruth54080172010-08-25 08:44:16 +000010390 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +000010391 }
John McCall83779672011-02-19 02:53:41 +000010392 } else {
10393 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +000010394 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
10395 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +000010396 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +000010397 MarkDeclarationReferenced(Loc, *i);
10398 }
John McCall83779672011-02-19 02:53:41 +000010399 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010400
John McCall83779672011-02-19 02:53:41 +000010401 // Keep track of used but undefined functions.
10402 if (!Function->isPure() && !Function->hasBody() &&
10403 Function->getLinkage() != ExternalLinkage) {
10404 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
10405 if (old.isInvalid()) old = Loc;
10406 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +000010407
John McCall83779672011-02-19 02:53:41 +000010408 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010409 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +000010410 }
Mike Stump11289f42009-09-09 15:08:12 +000010411
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010412 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +000010413 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +000010414 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +000010415 Var->getInstantiatedFromStaticDataMember()) {
10416 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10417 assert(MSInfo && "Missing member specialization information?");
10418 if (MSInfo->getPointOfInstantiation().isInvalid() &&
10419 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
10420 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redl2ac2c722011-04-29 08:19:30 +000010421 // This is a modification of an existing AST node. Notify listeners.
10422 if (ASTMutationListener *L = getASTMutationListener())
10423 L->StaticDataMemberInstantiated(Var);
Chandler Carruth54080172010-08-25 08:44:16 +000010424 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +000010425 }
10426 }
Mike Stump11289f42009-09-09 15:08:12 +000010427
John McCall15dd4042011-02-21 19:25:48 +000010428 // Keep track of used but undefined variables. We make a hole in
10429 // the warning for static const data members with in-line
10430 // initializers.
John McCall83779672011-02-19 02:53:41 +000010431 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +000010432 && Var->getLinkage() != ExternalLinkage
10433 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +000010434 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
10435 if (old.isInvalid()) old = Loc;
10436 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +000010437
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010438 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +000010439 return;
Sam Weinigbae69142009-09-11 03:29:30 +000010440 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010441}
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010442
Douglas Gregor5597ab42010-05-07 23:12:07 +000010443namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +000010444 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +000010445 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +000010446 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +000010447 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10448 Sema &S;
10449 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010450
Douglas Gregor5597ab42010-05-07 23:12:07 +000010451 public:
10452 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010453
Douglas Gregor5597ab42010-05-07 23:12:07 +000010454 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010455
10456 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10457 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010458 };
10459}
10460
Chandler Carruthaf80f662010-06-09 08:17:30 +000010461bool MarkReferencedDecls::TraverseTemplateArgument(
10462 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010463 if (Arg.getKind() == TemplateArgument::Declaration) {
10464 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
10465 }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010466
10467 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010468}
10469
Chandler Carruthaf80f662010-06-09 08:17:30 +000010470bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010471 if (ClassTemplateSpecializationDecl *Spec
10472 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10473 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +000010474 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +000010475 }
10476
Chandler Carruthc65667c2010-06-10 10:31:57 +000010477 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +000010478}
10479
10480void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10481 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000010482 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000010483}
10484
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010485namespace {
10486 /// \brief Helper class that marks all of the declarations referenced by
10487 /// potentially-evaluated subexpressions as "referenced".
10488 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10489 Sema &S;
10490
10491 public:
10492 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10493
10494 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
10495
10496 void VisitDeclRefExpr(DeclRefExpr *E) {
10497 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10498 }
10499
10500 void VisitMemberExpr(MemberExpr *E) {
10501 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010502 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010503 }
10504
10505 void VisitCXXNewExpr(CXXNewExpr *E) {
10506 if (E->getConstructor())
10507 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
10508 if (E->getOperatorNew())
10509 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
10510 if (E->getOperatorDelete())
10511 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010512 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010513 }
10514
10515 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10516 if (E->getOperatorDelete())
10517 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000010518 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10519 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10520 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10521 S.MarkDeclarationReferenced(E->getLocStart(),
10522 S.LookupDestructor(Record));
10523 }
10524
Douglas Gregor32b3de52010-09-11 23:32:50 +000010525 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010526 }
10527
10528 void VisitCXXConstructExpr(CXXConstructExpr *E) {
10529 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010530 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010531 }
10532
10533 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
10534 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10535 }
Douglas Gregorf0873f42010-10-19 17:17:35 +000010536
10537 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10538 Visit(E->getExpr());
10539 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010540 };
10541}
10542
10543/// \brief Mark any declarations that appear within this expression or any
10544/// potentially-evaluated subexpressions as "referenced".
10545void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
10546 EvaluatedExprMarker(*this).Visit(E);
10547}
10548
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010549/// \brief Emit a diagnostic that describes an effect on the run-time behavior
10550/// of the program being compiled.
10551///
10552/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010553/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010554/// possibility that the code will actually be executable. Code in sizeof()
10555/// expressions, code used only during overload resolution, etc., are not
10556/// potentially evaluated. This routine will suppress such diagnostics or,
10557/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010558/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010559/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010560///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010561/// This routine should be used for all diagnostics that describe the run-time
10562/// behavior of a program, such as passing a non-POD value through an ellipsis.
10563/// Failure to do so will likely result in spurious diagnostics or failures
10564/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +000010565bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010566 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +000010567 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010568 case Unevaluated:
10569 // The argument will never be evaluated, so don't complain.
10570 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010571
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010572 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010573 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +000010574 if (stmt && getCurFunctionOrMethodDecl()) {
10575 FunctionScopes.back()->PossiblyUnreachableDiags.
10576 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
10577 }
10578 else
10579 Diag(Loc, PD);
10580
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010581 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010582
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010583 case PotentiallyPotentiallyEvaluated:
10584 ExprEvalContexts.back().addDiagnostic(Loc, PD);
10585 break;
10586 }
10587
10588 return false;
10589}
10590
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010591bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
10592 CallExpr *CE, FunctionDecl *FD) {
10593 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
10594 return false;
10595
10596 PartialDiagnostic Note =
10597 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
10598 << FD->getDeclName() : PDiag();
10599 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010600
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010601 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010602 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010603 PDiag(diag::err_call_function_incomplete_return)
10604 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010605 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010606 << CE->getSourceRange(),
10607 std::make_pair(NoteLoc, Note)))
10608 return true;
10609
10610 return false;
10611}
10612
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010613// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000010614// will prevent this condition from triggering, which is what we want.
10615void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
10616 SourceLocation Loc;
10617
John McCall0506e4a2009-11-11 02:41:58 +000010618 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010619 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000010620
John McCalld5707ab2009-10-12 21:59:07 +000010621 if (isa<BinaryOperator>(E)) {
10622 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010623 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000010624 return;
10625
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010626 IsOrAssign = Op->getOpcode() == BO_OrAssign;
10627
John McCallb0e419e2009-11-12 00:06:05 +000010628 // Greylist some idioms by putting them into a warning subcategory.
10629 if (ObjCMessageExpr *ME
10630 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
10631 Selector Sel = ME->getSelector();
10632
John McCallb0e419e2009-11-12 00:06:05 +000010633 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000010634 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +000010635 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10636
10637 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000010638 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000010639 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10640 }
John McCall0506e4a2009-11-11 02:41:58 +000010641
John McCalld5707ab2009-10-12 21:59:07 +000010642 Loc = Op->getOperatorLoc();
10643 } else if (isa<CXXOperatorCallExpr>(E)) {
10644 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010645 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000010646 return;
10647
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010648 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000010649 Loc = Op->getOperatorLoc();
10650 } else {
10651 // Not an assignment.
10652 return;
10653 }
10654
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000010655 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010656
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000010657 SourceLocation Open = E->getSourceRange().getBegin();
10658 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
10659 Diag(Loc, diag::note_condition_assign_silence)
10660 << FixItHint::CreateInsertion(Open, "(")
10661 << FixItHint::CreateInsertion(Close, ")");
10662
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010663 if (IsOrAssign)
10664 Diag(Loc, diag::note_condition_or_assign_to_comparison)
10665 << FixItHint::CreateReplacement(Loc, "!=");
10666 else
10667 Diag(Loc, diag::note_condition_assign_to_comparison)
10668 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +000010669}
10670
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010671/// \brief Redundant parentheses over an equality comparison can indicate
10672/// that the user intended an assignment used as condition.
10673void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010674 // Don't warn if the parens came from a macro.
10675 SourceLocation parenLoc = parenE->getLocStart();
10676 if (parenLoc.isInvalid() || parenLoc.isMacroID())
10677 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000010678 // Don't warn for dependent expressions.
10679 if (parenE->isTypeDependent())
10680 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010681
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010682 Expr *E = parenE->IgnoreParens();
10683
10684 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000010685 if (opE->getOpcode() == BO_EQ &&
10686 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
10687 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010688 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000010689
Ted Kremenekae022092011-02-02 02:20:30 +000010690 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +000010691 Diag(Loc, diag::note_equality_comparison_silence)
10692 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
10693 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000010694 Diag(Loc, diag::note_equality_comparison_to_assign)
10695 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010696 }
10697}
10698
John Wiegley01296292011-04-08 18:41:53 +000010699ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000010700 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010701 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
10702 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000010703
John McCall0009fcc2011-04-26 20:42:42 +000010704 ExprResult result = CheckPlaceholderExpr(E);
10705 if (result.isInvalid()) return ExprError();
10706 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000010707
John McCall0009fcc2011-04-26 20:42:42 +000010708 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +000010709 if (getLangOptions().CPlusPlus)
10710 return CheckCXXBooleanCondition(E); // C++ 6.4p4
10711
John Wiegley01296292011-04-08 18:41:53 +000010712 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
10713 if (ERes.isInvalid())
10714 return ExprError();
10715 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +000010716
10717 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000010718 if (!T->isScalarType()) { // C99 6.8.4.1p1
10719 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
10720 << T << E->getSourceRange();
10721 return ExprError();
10722 }
John McCalld5707ab2009-10-12 21:59:07 +000010723 }
10724
John Wiegley01296292011-04-08 18:41:53 +000010725 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +000010726}
Douglas Gregore60e41a2010-05-06 17:25:47 +000010727
John McCalldadc5752010-08-24 06:29:42 +000010728ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
10729 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +000010730 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +000010731 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010732
10733 return CheckBooleanCondition(Sub, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000010734}
John McCall36e7fe32010-10-12 00:20:44 +000010735
John McCall31996342011-04-07 08:22:57 +000010736namespace {
John McCall2979fe02011-04-12 00:42:48 +000010737 /// A visitor for rebuilding a call to an __unknown_any expression
10738 /// to have an appropriate type.
10739 struct RebuildUnknownAnyFunction
10740 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
10741
10742 Sema &S;
10743
10744 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
10745
10746 ExprResult VisitStmt(Stmt *S) {
10747 llvm_unreachable("unexpected statement!");
10748 return ExprError();
10749 }
10750
10751 ExprResult VisitExpr(Expr *expr) {
10752 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
10753 << expr->getSourceRange();
10754 return ExprError();
10755 }
10756
10757 /// Rebuild an expression which simply semantically wraps another
10758 /// expression which it shares the type and value kind of.
10759 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10760 ExprResult subResult = Visit(expr->getSubExpr());
10761 if (subResult.isInvalid()) return ExprError();
10762
10763 Expr *subExpr = subResult.take();
10764 expr->setSubExpr(subExpr);
10765 expr->setType(subExpr->getType());
10766 expr->setValueKind(subExpr->getValueKind());
10767 assert(expr->getObjectKind() == OK_Ordinary);
10768 return expr;
10769 }
10770
10771 ExprResult VisitParenExpr(ParenExpr *paren) {
10772 return rebuildSugarExpr(paren);
10773 }
10774
10775 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10776 return rebuildSugarExpr(op);
10777 }
10778
10779 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10780 ExprResult subResult = Visit(op->getSubExpr());
10781 if (subResult.isInvalid()) return ExprError();
10782
10783 Expr *subExpr = subResult.take();
10784 op->setSubExpr(subExpr);
10785 op->setType(S.Context.getPointerType(subExpr->getType()));
10786 assert(op->getValueKind() == VK_RValue);
10787 assert(op->getObjectKind() == OK_Ordinary);
10788 return op;
10789 }
10790
10791 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
10792 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
10793
10794 expr->setType(decl->getType());
10795
10796 assert(expr->getValueKind() == VK_RValue);
10797 if (S.getLangOptions().CPlusPlus &&
10798 !(isa<CXXMethodDecl>(decl) &&
10799 cast<CXXMethodDecl>(decl)->isInstance()))
10800 expr->setValueKind(VK_LValue);
10801
10802 return expr;
10803 }
10804
10805 ExprResult VisitMemberExpr(MemberExpr *mem) {
10806 return resolveDecl(mem, mem->getMemberDecl());
10807 }
10808
10809 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
10810 return resolveDecl(ref, ref->getDecl());
10811 }
10812 };
10813}
10814
10815/// Given a function expression of unknown-any type, try to rebuild it
10816/// to have a function type.
10817static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
10818 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
10819 if (result.isInvalid()) return ExprError();
10820 return S.DefaultFunctionArrayConversion(result.take());
10821}
10822
10823namespace {
John McCall2d2e8702011-04-11 07:02:50 +000010824 /// A visitor for rebuilding an expression of type __unknown_anytype
10825 /// into one which resolves the type directly on the referring
10826 /// expression. Strict preservation of the original source
10827 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000010828 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000010829 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000010830
10831 Sema &S;
10832
10833 /// The current destination type.
10834 QualType DestType;
10835
10836 RebuildUnknownAnyExpr(Sema &S, QualType castType)
10837 : S(S), DestType(castType) {}
10838
John McCall39439732011-04-09 22:50:59 +000010839 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000010840 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +000010841 return ExprError();
John McCall31996342011-04-07 08:22:57 +000010842 }
10843
John McCall2d2e8702011-04-11 07:02:50 +000010844 ExprResult VisitExpr(Expr *expr) {
10845 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10846 << expr->getSourceRange();
10847 return ExprError();
John McCall31996342011-04-07 08:22:57 +000010848 }
10849
John McCall2d2e8702011-04-11 07:02:50 +000010850 ExprResult VisitCallExpr(CallExpr *call);
10851 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
10852
John McCall39439732011-04-09 22:50:59 +000010853 /// Rebuild an expression which simply semantically wraps another
10854 /// expression which it shares the type and value kind of.
10855 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10856 ExprResult subResult = Visit(expr->getSubExpr());
John McCall2979fe02011-04-12 00:42:48 +000010857 if (subResult.isInvalid()) return ExprError();
John McCall39439732011-04-09 22:50:59 +000010858 Expr *subExpr = subResult.take();
10859 expr->setSubExpr(subExpr);
10860 expr->setType(subExpr->getType());
10861 expr->setValueKind(subExpr->getValueKind());
10862 assert(expr->getObjectKind() == OK_Ordinary);
10863 return expr;
10864 }
John McCall31996342011-04-07 08:22:57 +000010865
John McCall39439732011-04-09 22:50:59 +000010866 ExprResult VisitParenExpr(ParenExpr *paren) {
10867 return rebuildSugarExpr(paren);
10868 }
10869
10870 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10871 return rebuildSugarExpr(op);
10872 }
10873
John McCall2979fe02011-04-12 00:42:48 +000010874 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10875 const PointerType *ptr = DestType->getAs<PointerType>();
10876 if (!ptr) {
10877 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
10878 << op->getSourceRange();
10879 return ExprError();
10880 }
10881 assert(op->getValueKind() == VK_RValue);
10882 assert(op->getObjectKind() == OK_Ordinary);
10883 op->setType(DestType);
10884
10885 // Build the sub-expression as if it were an object of the pointee type.
10886 DestType = ptr->getPointeeType();
10887 ExprResult subResult = Visit(op->getSubExpr());
10888 if (subResult.isInvalid()) return ExprError();
10889 op->setSubExpr(subResult.take());
10890 return op;
10891 }
10892
John McCall2d2e8702011-04-11 07:02:50 +000010893 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCall39439732011-04-09 22:50:59 +000010894
John McCall2979fe02011-04-12 00:42:48 +000010895 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCall39439732011-04-09 22:50:59 +000010896
John McCall2979fe02011-04-12 00:42:48 +000010897 ExprResult VisitMemberExpr(MemberExpr *mem) {
10898 return resolveDecl(mem, mem->getMemberDecl());
10899 }
John McCall39439732011-04-09 22:50:59 +000010900
10901 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall2d2e8702011-04-11 07:02:50 +000010902 return resolveDecl(ref, ref->getDecl());
John McCall31996342011-04-07 08:22:57 +000010903 }
10904 };
10905}
10906
John McCall2d2e8702011-04-11 07:02:50 +000010907/// Rebuilds a call expression which yielded __unknown_anytype.
10908ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
10909 Expr *callee = call->getCallee();
10910
10911 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +000010912 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +000010913 FK_FunctionPointer,
10914 FK_BlockPointer
10915 };
10916
10917 FnKind kind;
10918 QualType type = callee->getType();
John McCall4adb38c2011-04-27 00:36:17 +000010919 if (type == S.Context.BoundMemberTy) {
10920 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
10921 kind = FK_MemberFunction;
10922 type = Expr::findBoundMemberType(callee);
John McCall2d2e8702011-04-11 07:02:50 +000010923 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
10924 type = ptr->getPointeeType();
10925 kind = FK_FunctionPointer;
10926 } else {
10927 type = type->castAs<BlockPointerType>()->getPointeeType();
10928 kind = FK_BlockPointer;
10929 }
10930 const FunctionType *fnType = type->castAs<FunctionType>();
10931
10932 // Verify that this is a legal result type of a function.
10933 if (DestType->isArrayType() || DestType->isFunctionType()) {
10934 unsigned diagID = diag::err_func_returning_array_function;
10935 if (kind == FK_BlockPointer)
10936 diagID = diag::err_block_returning_array_function;
10937
10938 S.Diag(call->getExprLoc(), diagID)
10939 << DestType->isFunctionType() << DestType;
10940 return ExprError();
10941 }
10942
10943 // Otherwise, go ahead and set DestType as the call's result.
10944 call->setType(DestType.getNonLValueExprType(S.Context));
10945 call->setValueKind(Expr::getValueKindForType(DestType));
10946 assert(call->getObjectKind() == OK_Ordinary);
10947
10948 // Rebuild the function type, replacing the result type with DestType.
10949 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
10950 DestType = S.Context.getFunctionType(DestType,
10951 proto->arg_type_begin(),
10952 proto->getNumArgs(),
10953 proto->getExtProtoInfo());
10954 else
10955 DestType = S.Context.getFunctionNoProtoType(DestType,
10956 fnType->getExtInfo());
10957
10958 // Rebuild the appropriate pointer-to-function type.
10959 switch (kind) {
John McCall4adb38c2011-04-27 00:36:17 +000010960 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +000010961 // Nothing to do.
10962 break;
10963
10964 case FK_FunctionPointer:
10965 DestType = S.Context.getPointerType(DestType);
10966 break;
10967
10968 case FK_BlockPointer:
10969 DestType = S.Context.getBlockPointerType(DestType);
10970 break;
10971 }
10972
10973 // Finally, we can recurse.
10974 ExprResult calleeResult = Visit(callee);
10975 if (!calleeResult.isUsable()) return ExprError();
10976 call->setCallee(calleeResult.take());
10977
10978 // Bind a temporary if necessary.
10979 return S.MaybeBindToTemporary(call);
10980}
10981
10982ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall2979fe02011-04-12 00:42:48 +000010983 ObjCMethodDecl *method = msg->getMethodDecl();
10984 assert(method && "__unknown_anytype message without result type?");
John McCall2d2e8702011-04-11 07:02:50 +000010985
John McCall2979fe02011-04-12 00:42:48 +000010986 // Verify that this is a legal result type of a call.
10987 if (DestType->isArrayType() || DestType->isFunctionType()) {
10988 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
10989 << DestType->isFunctionType() << DestType;
10990 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010991 }
10992
John McCall2979fe02011-04-12 00:42:48 +000010993 assert(method->getResultType() == S.Context.UnknownAnyTy);
10994 method->setResultType(DestType);
10995
John McCall2d2e8702011-04-11 07:02:50 +000010996 // Change the type of the message.
John McCall2979fe02011-04-12 00:42:48 +000010997 msg->setType(DestType.getNonReferenceType());
10998 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000010999
John McCall2979fe02011-04-12 00:42:48 +000011000 return S.MaybeBindToTemporary(msg);
John McCall2d2e8702011-04-11 07:02:50 +000011001}
11002
11003ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall2979fe02011-04-12 00:42:48 +000011004 // The only case we should ever see here is a function-to-pointer decay.
John McCall2d2e8702011-04-11 07:02:50 +000011005 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall2d2e8702011-04-11 07:02:50 +000011006 assert(ice->getValueKind() == VK_RValue);
11007 assert(ice->getObjectKind() == OK_Ordinary);
11008
John McCall2979fe02011-04-12 00:42:48 +000011009 ice->setType(DestType);
11010
John McCall2d2e8702011-04-11 07:02:50 +000011011 // Rebuild the sub-expression as the pointee (function) type.
11012 DestType = DestType->castAs<PointerType>()->getPointeeType();
11013
11014 ExprResult result = Visit(ice->getSubExpr());
11015 if (!result.isUsable()) return ExprError();
11016
11017 ice->setSubExpr(result.take());
11018 return S.Owned(ice);
11019}
11020
John McCall2979fe02011-04-12 00:42:48 +000011021ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall2d2e8702011-04-11 07:02:50 +000011022 ExprValueKind valueKind = VK_LValue;
John McCall2d2e8702011-04-11 07:02:50 +000011023 QualType type = DestType;
11024
11025 // We know how to make this work for certain kinds of decls:
11026
11027 // - functions
John McCall2979fe02011-04-12 00:42:48 +000011028 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCall2d2e8702011-04-11 07:02:50 +000011029 // This is true because FunctionDecls must always have function
11030 // type, so we can't be resolving the entire thing at once.
11031 assert(type->isFunctionType());
11032
John McCall4adb38c2011-04-27 00:36:17 +000011033 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
11034 if (method->isInstance()) {
11035 valueKind = VK_RValue;
11036 type = S.Context.BoundMemberTy;
11037 }
11038
John McCall2d2e8702011-04-11 07:02:50 +000011039 // Function references aren't l-values in C.
11040 if (!S.getLangOptions().CPlusPlus)
11041 valueKind = VK_RValue;
11042
11043 // - variables
11044 } else if (isa<VarDecl>(decl)) {
John McCall2979fe02011-04-12 00:42:48 +000011045 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
11046 type = refTy->getPointeeType();
John McCall2d2e8702011-04-11 07:02:50 +000011047 } else if (type->isFunctionType()) {
John McCall2979fe02011-04-12 00:42:48 +000011048 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
11049 << decl << expr->getSourceRange();
11050 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011051 }
11052
11053 // - nothing else
11054 } else {
11055 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11056 << decl << expr->getSourceRange();
11057 return ExprError();
11058 }
11059
John McCall2979fe02011-04-12 00:42:48 +000011060 decl->setType(DestType);
11061 expr->setType(type);
11062 expr->setValueKind(valueKind);
11063 return S.Owned(expr);
John McCall2d2e8702011-04-11 07:02:50 +000011064}
11065
John McCall31996342011-04-07 08:22:57 +000011066/// Check a cast of an unknown-any type. We intentionally only
11067/// trigger this for C-style casts.
John Wiegley01296292011-04-08 18:41:53 +000011068ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
11069 Expr *castExpr, CastKind &castKind,
11070 ExprValueKind &VK, CXXCastPath &path) {
John McCall31996342011-04-07 08:22:57 +000011071 // Rewrite the casted expression from scratch.
John McCall39439732011-04-09 22:50:59 +000011072 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
11073 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000011074
John McCall39439732011-04-09 22:50:59 +000011075 castExpr = result.take();
11076 VK = castExpr->getValueKind();
11077 castKind = CK_NoOp;
11078
11079 return castExpr;
John McCall31996342011-04-07 08:22:57 +000011080}
11081
11082static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
11083 Expr *orig = e;
John McCall2d2e8702011-04-11 07:02:50 +000011084 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000011085 while (true) {
11086 e = e->IgnoreParenImpCasts();
John McCall2d2e8702011-04-11 07:02:50 +000011087 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall31996342011-04-07 08:22:57 +000011088 e = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011089 diagID = diag::err_uncasted_call_of_unknown_any;
11090 } else {
John McCall31996342011-04-07 08:22:57 +000011091 break;
John McCall2d2e8702011-04-11 07:02:50 +000011092 }
John McCall31996342011-04-07 08:22:57 +000011093 }
11094
John McCall2d2e8702011-04-11 07:02:50 +000011095 SourceLocation loc;
11096 NamedDecl *d;
11097 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11098 loc = ref->getLocation();
11099 d = ref->getDecl();
11100 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
11101 loc = mem->getMemberLoc();
11102 d = mem->getMemberDecl();
11103 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
11104 diagID = diag::err_uncasted_call_of_unknown_any;
11105 loc = msg->getSelectorLoc();
11106 d = msg->getMethodDecl();
11107 assert(d && "unknown method returning __unknown_any?");
11108 } else {
11109 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11110 << e->getSourceRange();
11111 return ExprError();
11112 }
11113
11114 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000011115
11116 // Never recoverable.
11117 return ExprError();
11118}
11119
John McCall36e7fe32010-10-12 00:20:44 +000011120/// Check for operands with placeholder types and complain if found.
11121/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000011122ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +000011123 // Placeholder types are always *exactly* the appropriate builtin type.
11124 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +000011125
John McCall31996342011-04-07 08:22:57 +000011126 // Overloaded expressions.
11127 if (type == Context.OverloadTy)
11128 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +000011129 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +000011130 QualType(),
11131 diag::err_ovl_unresolvable);
11132
John McCall0009fcc2011-04-26 20:42:42 +000011133 // Bound member functions.
11134 if (type == Context.BoundMemberTy) {
11135 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
11136 << E->getSourceRange();
11137 return ExprError();
11138 }
11139
John McCall31996342011-04-07 08:22:57 +000011140 // Expressions of unknown type.
11141 if (type == Context.UnknownAnyTy)
11142 return diagnoseUnknownAnyExpr(*this, E);
11143
11144 assert(!type->isPlaceholderType());
11145 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +000011146}
Richard Trieu2c850c02011-04-21 21:44:26 +000011147
11148bool Sema::CheckCaseExpression(Expr *expr) {
11149 if (expr->isTypeDependent())
11150 return true;
11151 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
11152 return expr->getType()->isIntegralOrEnumerationType();
11153 return false;
11154}