blob: fe11c7e4fea1ecd79634381ee9beaf06bd9272da [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) {
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000442 ExprResult ExprRes = CheckPlaceholderExpr(E);
443 if (ExprRes.isInvalid())
444 return ExprError();
445
446 ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000447 if (ExprRes.isInvalid())
448 return ExprError();
449 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000450
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000451 // __builtin_va_start takes the second argument as a "varargs" argument, but
452 // it doesn't actually do anything with it. It doesn't need to be non-pod
453 // etc.
454 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
John Wiegley01296292011-04-08 18:41:53 +0000455 return Owned(E);
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000456
Douglas Gregor347e0f22011-05-21 19:26:31 +0000457 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000458 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000459 DiagRuntimeBehavior(E->getLocStart(), 0,
460 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
461 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000462 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000463
John McCall31168b02011-06-15 23:02:42 +0000464 if (!E->getType().isPODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000465 // C++0x [expr.call]p7:
466 // Passing a potentially-evaluated argument of class type (Clause 9)
467 // having a non-trivial copy constructor, a non-trivial move constructor,
468 // or a non-trivial destructor, with no corresponding parameter,
469 // is conditionally-supported with implementation-defined semantics.
470 bool TrivialEnough = false;
471 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
472 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
473 if (Record->hasTrivialCopyConstructor() &&
474 Record->hasTrivialMoveConstructor() &&
475 Record->hasTrivialDestructor())
476 TrivialEnough = true;
477 }
478 }
John McCall31168b02011-06-15 23:02:42 +0000479
480 if (!TrivialEnough &&
481 getLangOptions().ObjCAutoRefCount &&
482 E->getType()->isObjCLifetimeType())
483 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000484
485 if (TrivialEnough) {
486 // Nothing to diagnose. This is okay.
487 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000488 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor253cadf2011-05-21 16:27:21 +0000489 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000490 << CT)) {
491 // Turn this into a trap.
492 CXXScopeSpec SS;
493 UnqualifiedId Name;
494 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
495 E->getLocStart());
496 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
497 if (TrapFn.isInvalid())
498 return ExprError();
499
500 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
501 MultiExprArg(), E->getLocEnd());
502 if (Call.isInvalid())
503 return ExprError();
504
505 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
506 Call.get(), E);
507 if (Comma.isInvalid())
508 return ExprError();
509
510 E = Comma.get();
511 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000512 }
513
John Wiegley01296292011-04-08 18:41:53 +0000514 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000515}
516
Chris Lattner513165e2008-07-25 21:10:04 +0000517/// UsualArithmeticConversions - Performs various conversions that are common to
518/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000519/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000520/// responsible for emitting appropriate error diagnostics.
521/// FIXME: verify the conversion rules for "complex int" are consistent with
522/// GCC.
John Wiegley01296292011-04-08 18:41:53 +0000523QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr, ExprResult &rhsExpr,
Chris Lattner513165e2008-07-25 21:10:04 +0000524 bool isCompAssign) {
John Wiegley01296292011-04-08 18:41:53 +0000525 if (!isCompAssign) {
526 lhsExpr = UsualUnaryConversions(lhsExpr.take());
527 if (lhsExpr.isInvalid())
528 return QualType();
529 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000530
John Wiegley01296292011-04-08 18:41:53 +0000531 rhsExpr = UsualUnaryConversions(rhsExpr.take());
532 if (rhsExpr.isInvalid())
533 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000534
Mike Stump11289f42009-09-09 15:08:12 +0000535 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000536 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000537 QualType lhs =
John Wiegley01296292011-04-08 18:41:53 +0000538 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000539 QualType rhs =
John Wiegley01296292011-04-08 18:41:53 +0000540 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000541
542 // If both types are identical, no conversion is needed.
543 if (lhs == rhs)
544 return lhs;
545
546 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
547 // The caller can deal with this (e.g. pointer + int).
548 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
549 return lhs;
550
John McCalld005ac92010-11-13 08:17:45 +0000551 // Apply unary and bitfield promotions to the LHS's type.
552 QualType lhs_unpromoted = lhs;
553 if (lhs->isPromotableIntegerType())
554 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley01296292011-04-08 18:41:53 +0000555 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000556 if (!LHSBitfieldPromoteTy.isNull())
557 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000558 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000559 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000560
John McCalld005ac92010-11-13 08:17:45 +0000561 // If both types are identical, no conversion is needed.
562 if (lhs == rhs)
563 return lhs;
564
565 // At this point, we have two different arithmetic types.
566
567 // Handle complex types first (C99 6.3.1.8p1).
568 bool LHSComplexFloat = lhs->isComplexType();
569 bool RHSComplexFloat = rhs->isComplexType();
570 if (LHSComplexFloat || RHSComplexFloat) {
571 // if we have an integer operand, the result is the complex type.
572
John McCallc5e62b42010-11-13 09:02:35 +0000573 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
574 if (rhs->isIntegerType()) {
575 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000576 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
577 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000578 } else {
579 assert(rhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000580 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000581 }
John McCalld005ac92010-11-13 08:17:45 +0000582 return lhs;
583 }
584
John McCallc5e62b42010-11-13 09:02:35 +0000585 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
586 if (!isCompAssign) {
587 // int -> float -> _Complex float
588 if (lhs->isIntegerType()) {
589 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000590 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_IntegralToFloating);
591 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000592 } else {
593 assert(lhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000594 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000595 }
596 }
John McCalld005ac92010-11-13 08:17:45 +0000597 return rhs;
598 }
599
600 // This handles complex/complex, complex/float, or float/complex.
601 // When both operands are complex, the shorter operand is converted to the
602 // type of the longer, and that is the type of the result. This corresponds
603 // to what is done when combining two real floating-point operands.
604 // The fun begins when size promotion occur across type domains.
605 // From H&S 6.3.4: When one operand is complex and the other is a real
606 // floating-point type, the less precise type is converted, within it's
607 // real or complex domain, to the precision of the other type. For example,
608 // when combining a "long double" with a "double _Complex", the
609 // "double _Complex" is promoted to "long double _Complex".
610 int order = Context.getFloatingTypeOrder(lhs, rhs);
611
612 // If both are complex, just cast to the more precise type.
613 if (LHSComplexFloat && RHSComplexFloat) {
614 if (order > 0) {
615 // _Complex float -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000616 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000617 return lhs;
618
619 } else if (order < 0) {
620 // _Complex float -> _Complex double
621 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000622 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000623 return rhs;
624 }
625 return lhs;
626 }
627
628 // If just the LHS is complex, the RHS needs to be converted,
629 // and the LHS might need to be promoted.
630 if (LHSComplexFloat) {
631 if (order > 0) { // LHS is wider
632 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000633 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000634 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
635 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000636 return lhs;
637 }
638
639 // RHS is at least as wide. Find its corresponding complex type.
640 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
641
642 // double -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000643 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000644
645 // _Complex float -> _Complex double
646 if (!isCompAssign && order < 0)
John Wiegley01296292011-04-08 18:41:53 +0000647 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000648
649 return result;
650 }
651
652 // Just the RHS is complex, so the LHS needs to be converted
653 // and the RHS might need to be promoted.
654 assert(RHSComplexFloat);
655
656 if (order < 0) { // RHS is wider
657 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000658 if (!isCompAssign) {
Argyrios Kyrtzidise84389b2011-01-18 18:49:33 +0000659 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000660 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
661 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000662 }
John McCalld005ac92010-11-13 08:17:45 +0000663 return rhs;
664 }
665
666 // LHS is at least as wide. Find its corresponding complex type.
667 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
668
669 // double -> _Complex double
670 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000671 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000672
673 // _Complex float -> _Complex double
674 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +0000675 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000676
677 return result;
678 }
679
680 // Now handle "real" floating types (i.e. float, double, long double).
681 bool LHSFloat = lhs->isRealFloatingType();
682 bool RHSFloat = rhs->isRealFloatingType();
683 if (LHSFloat || RHSFloat) {
684 // If we have two real floating types, convert the smaller operand
685 // to the bigger result.
686 if (LHSFloat && RHSFloat) {
687 int order = Context.getFloatingTypeOrder(lhs, rhs);
688 if (order > 0) {
John Wiegley01296292011-04-08 18:41:53 +0000689 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000690 return lhs;
691 }
692
693 assert(order < 0 && "illegal float comparison");
694 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000695 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000696 return rhs;
697 }
698
699 // If we have an integer operand, the result is the real floating type.
700 if (LHSFloat) {
701 if (rhs->isIntegerType()) {
702 // Convert rhs to the lhs floating point type.
John Wiegley01296292011-04-08 18:41:53 +0000703 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000704 return lhs;
705 }
706
707 // Convert both sides to the appropriate complex float.
708 assert(rhs->isComplexIntegerType());
709 QualType result = Context.getComplexType(lhs);
710
711 // _Complex int -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000712 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000713
714 // float -> _Complex float
715 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000716 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000717
718 return result;
719 }
720
721 assert(RHSFloat);
722 if (lhs->isIntegerType()) {
723 // Convert lhs to the rhs floating point type.
724 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000725 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000726 return rhs;
727 }
728
729 // Convert both sides to the appropriate complex float.
730 assert(lhs->isComplexIntegerType());
731 QualType result = Context.getComplexType(rhs);
732
733 // _Complex int -> _Complex float
734 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000735 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000736
737 // float -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000738 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000739
740 return result;
741 }
742
743 // Handle GCC complex int extension.
744 // FIXME: if the operands are (int, _Complex long), we currently
745 // don't promote the complex. Also, signedness?
746 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
747 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
748 if (lhsComplexInt && rhsComplexInt) {
749 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
750 rhsComplexInt->getElementType());
751 assert(order && "inequal types with equal element ordering");
752 if (order > 0) {
753 // _Complex int -> _Complex long
John Wiegley01296292011-04-08 18:41:53 +0000754 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000755 return lhs;
756 }
757
758 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000759 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000760 return rhs;
761 } else if (lhsComplexInt) {
762 // int -> _Complex int
John Wiegley01296292011-04-08 18:41:53 +0000763 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000764 return lhs;
765 } else if (rhsComplexInt) {
766 // int -> _Complex int
767 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000768 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000769 return rhs;
770 }
771
772 // Finally, we have two differing integer types.
773 // The rules for this case are in C99 6.3.1.8
774 int compare = Context.getIntegerTypeOrder(lhs, rhs);
775 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
776 rhsSigned = rhs->hasSignedIntegerRepresentation();
777 if (lhsSigned == rhsSigned) {
778 // Same signedness; use the higher-ranked type
779 if (compare >= 0) {
John Wiegley01296292011-04-08 18:41:53 +0000780 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000781 return lhs;
782 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000783 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000784 return rhs;
785 } else if (compare != (lhsSigned ? 1 : -1)) {
786 // The unsigned type has greater than or equal rank to the
787 // signed type, so use the unsigned type
788 if (rhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000789 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000790 return lhs;
791 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000792 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000793 return rhs;
794 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
795 // The two types are different widths; if we are here, that
796 // means the signed type is larger than the unsigned type, so
797 // use the signed type.
798 if (lhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000799 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000800 return lhs;
801 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000802 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000803 return rhs;
804 } else {
805 // The signed type is higher-ranked than the unsigned type,
806 // but isn't actually any bigger (like unsigned int and long
807 // on most 32-bit systems). Use the unsigned type corresponding
808 // to the signed type.
809 QualType result =
810 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley01296292011-04-08 18:41:53 +0000811 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000812 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000813 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000814 return result;
815 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000816}
817
Chris Lattner513165e2008-07-25 21:10:04 +0000818//===----------------------------------------------------------------------===//
819// Semantic Analysis for various Expression Types
820//===----------------------------------------------------------------------===//
821
822
Peter Collingbourne91147592011-04-15 00:35:48 +0000823ExprResult
824Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
825 SourceLocation DefaultLoc,
826 SourceLocation RParenLoc,
827 Expr *ControllingExpr,
828 MultiTypeArg types,
829 MultiExprArg exprs) {
830 unsigned NumAssocs = types.size();
831 assert(NumAssocs == exprs.size());
832
833 ParsedType *ParsedTypes = types.release();
834 Expr **Exprs = exprs.release();
835
836 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
837 for (unsigned i = 0; i < NumAssocs; ++i) {
838 if (ParsedTypes[i])
839 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
840 else
841 Types[i] = 0;
842 }
843
844 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
845 ControllingExpr, Types, Exprs,
846 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000847 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000848 return ER;
849}
850
851ExprResult
852Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
853 SourceLocation DefaultLoc,
854 SourceLocation RParenLoc,
855 Expr *ControllingExpr,
856 TypeSourceInfo **Types,
857 Expr **Exprs,
858 unsigned NumAssocs) {
859 bool TypeErrorFound = false,
860 IsResultDependent = ControllingExpr->isTypeDependent(),
861 ContainsUnexpandedParameterPack
862 = ControllingExpr->containsUnexpandedParameterPack();
863
864 for (unsigned i = 0; i < NumAssocs; ++i) {
865 if (Exprs[i]->containsUnexpandedParameterPack())
866 ContainsUnexpandedParameterPack = true;
867
868 if (Types[i]) {
869 if (Types[i]->getType()->containsUnexpandedParameterPack())
870 ContainsUnexpandedParameterPack = true;
871
872 if (Types[i]->getType()->isDependentType()) {
873 IsResultDependent = true;
874 } else {
875 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
876 // complete object type other than a variably modified type."
877 unsigned D = 0;
878 if (Types[i]->getType()->isIncompleteType())
879 D = diag::err_assoc_type_incomplete;
880 else if (!Types[i]->getType()->isObjectType())
881 D = diag::err_assoc_type_nonobject;
882 else if (Types[i]->getType()->isVariablyModifiedType())
883 D = diag::err_assoc_type_variably_modified;
884
885 if (D != 0) {
886 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
887 << Types[i]->getTypeLoc().getSourceRange()
888 << Types[i]->getType();
889 TypeErrorFound = true;
890 }
891
892 // C1X 6.5.1.1p2 "No two generic associations in the same generic
893 // selection shall specify compatible types."
894 for (unsigned j = i+1; j < NumAssocs; ++j)
895 if (Types[j] && !Types[j]->getType()->isDependentType() &&
896 Context.typesAreCompatible(Types[i]->getType(),
897 Types[j]->getType())) {
898 Diag(Types[j]->getTypeLoc().getBeginLoc(),
899 diag::err_assoc_compatible_types)
900 << Types[j]->getTypeLoc().getSourceRange()
901 << Types[j]->getType()
902 << Types[i]->getType();
903 Diag(Types[i]->getTypeLoc().getBeginLoc(),
904 diag::note_compat_assoc)
905 << Types[i]->getTypeLoc().getSourceRange()
906 << Types[i]->getType();
907 TypeErrorFound = true;
908 }
909 }
910 }
911 }
912 if (TypeErrorFound)
913 return ExprError();
914
915 // If we determined that the generic selection is result-dependent, don't
916 // try to compute the result expression.
917 if (IsResultDependent)
918 return Owned(new (Context) GenericSelectionExpr(
919 Context, KeyLoc, ControllingExpr,
920 Types, Exprs, NumAssocs, DefaultLoc,
921 RParenLoc, ContainsUnexpandedParameterPack));
922
923 llvm::SmallVector<unsigned, 1> CompatIndices;
924 unsigned DefaultIndex = -1U;
925 for (unsigned i = 0; i < NumAssocs; ++i) {
926 if (!Types[i])
927 DefaultIndex = i;
928 else if (Context.typesAreCompatible(ControllingExpr->getType(),
929 Types[i]->getType()))
930 CompatIndices.push_back(i);
931 }
932
933 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
934 // type compatible with at most one of the types named in its generic
935 // association list."
936 if (CompatIndices.size() > 1) {
937 // We strip parens here because the controlling expression is typically
938 // parenthesized in macro definitions.
939 ControllingExpr = ControllingExpr->IgnoreParens();
940 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
941 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
942 << (unsigned) CompatIndices.size();
943 for (llvm::SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
944 E = CompatIndices.end(); I != E; ++I) {
945 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
946 diag::note_compat_assoc)
947 << Types[*I]->getTypeLoc().getSourceRange()
948 << Types[*I]->getType();
949 }
950 return ExprError();
951 }
952
953 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
954 // its controlling expression shall have type compatible with exactly one of
955 // the types named in its generic association list."
956 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
957 // We strip parens here because the controlling expression is typically
958 // parenthesized in macro definitions.
959 ControllingExpr = ControllingExpr->IgnoreParens();
960 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
961 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
962 return ExprError();
963 }
964
965 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
966 // type name that is compatible with the type of the controlling expression,
967 // then the result expression of the generic selection is the expression
968 // in that generic association. Otherwise, the result expression of the
969 // generic selection is the expression in the default generic association."
970 unsigned ResultIndex =
971 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
972
973 return Owned(new (Context) GenericSelectionExpr(
974 Context, KeyLoc, ControllingExpr,
975 Types, Exprs, NumAssocs, DefaultLoc,
976 RParenLoc, ContainsUnexpandedParameterPack,
977 ResultIndex));
978}
979
Steve Naroff83895f72007-09-16 03:34:24 +0000980/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000981/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
982/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
983/// multiple tokens. However, the common case is that StringToks points to one
984/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000985///
John McCalldadc5752010-08-24 06:29:42 +0000986ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +0000987Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000988 assert(NumStringToks && "Must have at least one string!");
989
Chris Lattner8a24e582009-01-16 18:51:42 +0000990 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000991 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000992 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000993
Chris Lattner23b7eb62007-06-15 23:05:46 +0000994 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000995 for (unsigned i = 0; i != NumStringToks; ++i)
996 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000997
Chris Lattner36fc8792008-02-11 00:02:17 +0000998 QualType StrTy = Context.CharTy;
Anders Carlsson6b06e182011-04-06 18:42:48 +0000999 if (Literal.AnyWide)
1000 StrTy = Context.getWCharType();
1001 else if (Literal.Pascal)
1002 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001003
1004 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +00001005 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001006 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001007
Chris Lattner36fc8792008-02-11 00:02:17 +00001008 // Get an array type for the string, according to C99 6.4.5. This includes
1009 // the nul terminator character as well as the string length for pascal
1010 // strings.
1011 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001012 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001013 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001014
Chris Lattner5b183d82006-11-10 05:03:26 +00001015 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +00001016 return Owned(StringLiteral::Create(Context, Literal.GetString(),
1017 Literal.GetStringLength(),
Anders Carlsson75245402011-04-14 00:40:03 +00001018 Literal.AnyWide, Literal.Pascal, StrTy,
Alexis Hunt3b791862010-08-30 17:47:05 +00001019 &StringTokLocs[0],
1020 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +00001021}
1022
John McCallc63de662011-02-02 13:00:07 +00001023enum CaptureResult {
1024 /// No capture is required.
1025 CR_NoCapture,
1026
1027 /// A capture is required.
1028 CR_Capture,
1029
John McCall351762c2011-02-07 10:33:21 +00001030 /// A by-ref capture is required.
1031 CR_CaptureByRef,
1032
John McCallc63de662011-02-02 13:00:07 +00001033 /// An error occurred when trying to capture the given variable.
1034 CR_Error
1035};
1036
1037/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +00001038///
John McCallc63de662011-02-02 13:00:07 +00001039/// \param var - the variable referenced
1040/// \param DC - the context which we couldn't capture through
1041static CaptureResult
John McCall351762c2011-02-07 10:33:21 +00001042diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001043 VarDecl *var, DeclContext *DC) {
1044 switch (S.ExprEvalContexts.back().Context) {
1045 case Sema::Unevaluated:
1046 // The argument will never be evaluated, so don't complain.
1047 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +00001048
John McCallc63de662011-02-02 13:00:07 +00001049 case Sema::PotentiallyEvaluated:
1050 case Sema::PotentiallyEvaluatedIfUsed:
1051 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +00001052
John McCallc63de662011-02-02 13:00:07 +00001053 case Sema::PotentiallyPotentiallyEvaluated:
1054 // FIXME: delay these!
1055 break;
Chris Lattner497d7b02009-04-21 22:26:47 +00001056 }
Mike Stump11289f42009-09-09 15:08:12 +00001057
John McCallc63de662011-02-02 13:00:07 +00001058 // Don't diagnose about capture if we're not actually in code right
1059 // now; in general, there are more appropriate places that will
1060 // diagnose this.
1061 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1062
John McCall92d627e2011-03-22 23:15:50 +00001063 // Certain madnesses can happen with parameter declarations, which
1064 // we want to ignore.
1065 if (isa<ParmVarDecl>(var)) {
1066 // - If the parameter still belongs to the translation unit, then
1067 // we're actually just using one parameter in the declaration of
1068 // the next. This is useful in e.g. VLAs.
1069 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1070 return CR_NoCapture;
1071
1072 // - This particular madness can happen in ill-formed default
1073 // arguments; claim it's okay and let downstream code handle it.
1074 if (S.CurContext == var->getDeclContext()->getParent())
1075 return CR_NoCapture;
1076 }
John McCallc63de662011-02-02 13:00:07 +00001077
1078 DeclarationName functionName;
1079 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1080 functionName = fn->getDeclName();
1081 // FIXME: variable from enclosing block that we couldn't capture from!
1082
1083 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1084 << var->getIdentifier() << functionName;
1085 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1086 << var->getIdentifier();
1087
1088 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +00001089}
1090
John McCall351762c2011-02-07 10:33:21 +00001091/// There is a well-formed capture at a particular scope level;
1092/// propagate it through all the nested blocks.
1093static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1094 const BlockDecl::Capture &capture) {
1095 VarDecl *var = capture.getVariable();
1096
1097 // Update all the inner blocks with the capture information.
1098 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1099 i != e; ++i) {
1100 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1101 innerBlock->Captures.push_back(
1102 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1103 /*nested*/ true, capture.getCopyExpr()));
1104 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1105 }
1106
1107 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1108}
1109
1110/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +00001111/// given value in the current context requires a variable capture.
1112///
1113/// This also keeps the captures set in the BlockScopeInfo records
1114/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +00001115static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001116 ValueDecl *value) {
1117 // Only variables ever require capture.
1118 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +00001119 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +00001120
1121 // Fast path: variables from the current context never require capture.
1122 DeclContext *DC = S.CurContext;
1123 if (var->getDeclContext() == DC) return CR_NoCapture;
1124
1125 // Only variables with local storage require capture.
1126 // FIXME: What about 'const' variables in C++?
1127 if (!var->hasLocalStorage()) return CR_NoCapture;
1128
1129 // Otherwise, we need to capture.
1130
1131 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +00001132 do {
1133 // Only blocks (and eventually C++0x closures) can capture; other
1134 // scopes don't work.
1135 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +00001136 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +00001137
1138 BlockScopeInfo *blockScope =
1139 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1140 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1141
John McCall351762c2011-02-07 10:33:21 +00001142 // Check whether we've already captured it in this block. If so,
1143 // we're done.
1144 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1145 return propagateCapture(S, functionScopesIndex,
1146 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +00001147
1148 functionScopesIndex--;
1149 DC = cast<BlockDecl>(DC)->getDeclContext();
1150 } while (var->getDeclContext() != DC);
1151
John McCall351762c2011-02-07 10:33:21 +00001152 // Okay, we descended all the way to the block that defines the variable.
1153 // Actually try to capture it.
1154 QualType type = var->getType();
1155
1156 // Prohibit variably-modified types.
1157 if (type->isVariablyModifiedType()) {
1158 S.Diag(loc, diag::err_ref_vm_type);
1159 S.Diag(var->getLocation(), diag::note_declared_at);
1160 return CR_Error;
1161 }
1162
1163 // Prohibit arrays, even in __block variables, but not references to
1164 // them.
1165 if (type->isArrayType()) {
1166 S.Diag(loc, diag::err_ref_array_type);
1167 S.Diag(var->getLocation(), diag::note_declared_at);
1168 return CR_Error;
1169 }
1170
1171 S.MarkDeclarationReferenced(loc, var);
1172
1173 // The BlocksAttr indicates the variable is bound by-reference.
1174 bool byRef = var->hasAttr<BlocksAttr>();
1175
1176 // Build a copy expression.
1177 Expr *copyExpr = 0;
John McCalla85af562011-04-28 02:15:35 +00001178 const RecordType *rtype;
1179 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1180 (rtype = type->getAs<RecordType>())) {
1181
1182 // The capture logic needs the destructor, so make sure we mark it.
1183 // Usually this is unnecessary because most local variables have
1184 // their destructors marked at declaration time, but parameters are
1185 // an exception because it's technically only the call site that
1186 // actually requires the destructor.
1187 if (isa<ParmVarDecl>(var))
1188 S.FinalizeVarWithDestructor(var, rtype);
1189
John McCall351762c2011-02-07 10:33:21 +00001190 // According to the blocks spec, the capture of a variable from
1191 // the stack requires a const copy constructor. This is not true
1192 // of the copy/move done to move a __block variable to the heap.
1193 type.addConst();
1194
1195 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1196 ExprResult result =
1197 S.PerformCopyInitialization(
1198 InitializedEntity::InitializeBlock(var->getLocation(),
1199 type, false),
1200 loc, S.Owned(declRef));
1201
1202 // Build a full-expression copy expression if initialization
1203 // succeeded and used a non-trivial constructor. Recover from
1204 // errors by pretending that the copy isn't necessary.
1205 if (!result.isInvalid() &&
1206 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1207 result = S.MaybeCreateExprWithCleanups(result);
1208 copyExpr = result.take();
1209 }
1210 }
1211
1212 // We're currently at the declarer; go back to the closure.
1213 functionScopesIndex++;
1214 BlockScopeInfo *blockScope =
1215 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1216
1217 // Build a valid capture in this scope.
1218 blockScope->Captures.push_back(
1219 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1220 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1221
1222 // Propagate that to inner captures if necessary.
1223 return propagateCapture(S, functionScopesIndex,
1224 blockScope->Captures.back());
1225}
1226
1227static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1228 const DeclarationNameInfo &NameInfo,
1229 bool byRef) {
1230 assert(isa<VarDecl>(vd) && "capturing non-variable");
1231
1232 VarDecl *var = cast<VarDecl>(vd);
1233 assert(var->hasLocalStorage() && "capturing non-local");
1234 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1235
1236 QualType exprType = var->getType().getNonReferenceType();
1237
1238 BlockDeclRefExpr *BDRE;
1239 if (!byRef) {
1240 // The variable will be bound by copy; make it const within the
1241 // closure, but record that this was done in the expression.
1242 bool constAdded = !exprType.isConstQualified();
1243 exprType.addConst();
1244
1245 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1246 NameInfo.getLoc(), false,
1247 constAdded);
1248 } else {
1249 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1250 NameInfo.getLoc(), true);
1251 }
1252
1253 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001254}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001255
John McCalldadc5752010-08-24 06:29:42 +00001256ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001257Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001258 SourceLocation Loc,
1259 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001260 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001261 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001262}
1263
John McCallf4cd4f92011-02-09 01:13:10 +00001264/// BuildDeclRefExpr - Build an expression that references a
1265/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001266ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001267Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001268 const DeclarationNameInfo &NameInfo,
1269 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001270 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001271
John McCall086a4642010-11-24 05:12:34 +00001272 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001273 SS? SS->getWithLocInContext(Context)
1274 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001275 D, NameInfo, Ty, VK);
1276
1277 // Just in case we're building an illegal pointer-to-member.
1278 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1279 E->setObjectKind(OK_BitField);
1280
1281 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001282}
1283
John McCallfeb624a2010-11-23 20:48:44 +00001284static ExprResult
1285BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1286 const CXXScopeSpec &SS, FieldDecl *Field,
1287 DeclAccessPair FoundDecl,
1288 const DeclarationNameInfo &MemberNameInfo);
1289
John McCalldadc5752010-08-24 06:29:42 +00001290ExprResult
John McCallf3a88602011-02-03 08:15:49 +00001291Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
1292 SourceLocation loc,
1293 IndirectFieldDecl *indirectField,
1294 Expr *baseObjectExpr,
1295 SourceLocation opLoc) {
1296 // First, build the expression that refers to the base object.
1297
1298 bool baseObjectIsPointer = false;
1299 Qualifiers baseQuals;
1300
1301 // Case 1: the base of the indirect field is not a field.
1302 VarDecl *baseVariable = indirectField->getVarDecl();
Douglas Gregore10f36d2011-02-18 02:44:58 +00001303 CXXScopeSpec EmptySS;
John McCallf3a88602011-02-03 08:15:49 +00001304 if (baseVariable) {
1305 assert(baseVariable->getType()->isRecordType());
1306
1307 // In principle we could have a member access expression that
1308 // accesses an anonymous struct/union that's a static member of
1309 // the base object's class. However, under the current standard,
1310 // static data members cannot be anonymous structs or unions.
1311 // Supporting this is as easy as building a MemberExpr here.
1312 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1313
1314 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1315
1316 ExprResult result =
Douglas Gregore10f36d2011-02-18 02:44:58 +00001317 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
John McCallf3a88602011-02-03 08:15:49 +00001318 if (result.isInvalid()) return ExprError();
1319
1320 baseObjectExpr = result.take();
1321 baseObjectIsPointer = false;
1322 baseQuals = baseObjectExpr->getType().getQualifiers();
1323
1324 // Case 2: the base of the indirect field is a field and the user
1325 // wrote a member expression.
1326 } else if (baseObjectExpr) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001327 // The caller provided the base object expression. Determine
1328 // whether its a pointer and whether it adds any qualifiers to the
1329 // anonymous struct/union fields we're looking into.
John McCallf3a88602011-02-03 08:15:49 +00001330 QualType objectType = baseObjectExpr->getType();
1331
1332 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1333 baseObjectIsPointer = true;
1334 objectType = ptr->getPointeeType();
1335 } else {
1336 baseObjectIsPointer = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001337 }
John McCallf3a88602011-02-03 08:15:49 +00001338 baseQuals = objectType.getQualifiers();
1339
1340 // Case 3: the base of the indirect field is a field and we should
1341 // build an implicit member access.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001342 } else {
1343 // We've found a member of an anonymous struct/union that is
1344 // inside a non-anonymous struct/union, so in a well-formed
1345 // program our base object expression is "this".
Richard Smith938f40b2011-06-11 17:19:42 +00001346 QualType ThisTy = getAndCaptureCurrentThisType();
1347 if (ThisTy.isNull()) {
John McCallf3a88602011-02-03 08:15:49 +00001348 Diag(loc, diag::err_invalid_member_use_in_static_method)
1349 << indirectField->getDeclName();
1350 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001351 }
1352
John McCallf3a88602011-02-03 08:15:49 +00001353 // Our base object expression is "this".
1354 baseObjectExpr =
Richard Smith938f40b2011-06-11 17:19:42 +00001355 new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
John McCallf3a88602011-02-03 08:15:49 +00001356 baseObjectIsPointer = true;
Richard Smith938f40b2011-06-11 17:19:42 +00001357 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001358 }
1359
1360 // Build the implicit member references to the field of the
1361 // anonymous struct/union.
John McCallf3a88602011-02-03 08:15:49 +00001362 Expr *result = baseObjectExpr;
1363 IndirectFieldDecl::chain_iterator
1364 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCallfeb624a2010-11-23 20:48:44 +00001365
John McCallf3a88602011-02-03 08:15:49 +00001366 // Build the first member access in the chain with full information.
1367 if (!baseVariable) {
1368 FieldDecl *field = cast<FieldDecl>(*FI);
John McCallfeb624a2010-11-23 20:48:44 +00001369
John McCallf3a88602011-02-03 08:15:49 +00001370 // FIXME: use the real found-decl info!
1371 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall8ccfcb52009-09-24 19:53:00 +00001372
John McCallf3a88602011-02-03 08:15:49 +00001373 // Make a nameInfo that properly uses the anonymous name.
1374 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall8ccfcb52009-09-24 19:53:00 +00001375
John McCallf3a88602011-02-03 08:15:49 +00001376 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001377 EmptySS, field, foundDecl,
John McCallf3a88602011-02-03 08:15:49 +00001378 memberNameInfo).take();
1379 baseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +00001380
John McCallf3a88602011-02-03 08:15:49 +00001381 // FIXME: check qualified member access
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001382 }
1383
John McCallf3a88602011-02-03 08:15:49 +00001384 // In all cases, we should now skip the first declaration in the chain.
1385 ++FI;
1386
Douglas Gregore10f36d2011-02-18 02:44:58 +00001387 while (FI != FEnd) {
1388 FieldDecl *field = cast<FieldDecl>(*FI++);
John McCallf3a88602011-02-03 08:15:49 +00001389
1390 // FIXME: these are somewhat meaningless
1391 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1392 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCallf3a88602011-02-03 08:15:49 +00001393
1394 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001395 (FI == FEnd? SS : EmptySS), field,
1396 foundDecl, memberNameInfo)
John McCallf3a88602011-02-03 08:15:49 +00001397 .take();
1398 }
1399
1400 return Owned(result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001401}
1402
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001403/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001404/// possibly a list of template arguments.
1405///
1406/// If this produces template arguments, it is permitted to call
1407/// DecomposeTemplateName.
1408///
1409/// This actually loses a lot of source location information for
1410/// non-standard name kinds; we should consider preserving that in
1411/// some way.
1412static void DecomposeUnqualifiedId(Sema &SemaRef,
1413 const UnqualifiedId &Id,
1414 TemplateArgumentListInfo &Buffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001415 DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00001416 const TemplateArgumentListInfo *&TemplateArgs) {
1417 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1418 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1419 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1420
1421 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1422 Id.TemplateId->getTemplateArgs(),
1423 Id.TemplateId->NumArgs);
1424 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1425 TemplateArgsPtr.release();
1426
John McCall3e56fd42010-08-23 07:28:44 +00001427 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001428 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1429 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001430 TemplateArgs = &Buffer;
1431 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001432 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001433 TemplateArgs = 0;
1434 }
1435}
1436
John McCall2d74de92009-12-01 22:10:20 +00001437/// Determines if the given class is provably not derived from all of
1438/// the prospective base classes.
1439static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1440 CXXRecordDecl *Record,
1441 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +00001442 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +00001443 return false;
1444
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001445 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +00001446 if (!RD) return false;
1447 Record = cast<CXXRecordDecl>(RD);
1448
John McCall2d74de92009-12-01 22:10:20 +00001449 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1450 E = Record->bases_end(); I != E; ++I) {
1451 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1452 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1453 if (!BaseRT) return false;
1454
1455 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +00001456 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1457 return false;
1458 }
1459
1460 return true;
1461}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001462
John McCall2d74de92009-12-01 22:10:20 +00001463enum IMAKind {
1464 /// The reference is definitely not an instance member access.
1465 IMA_Static,
1466
1467 /// The reference may be an implicit instance member access.
1468 IMA_Mixed,
1469
1470 /// The reference may be to an instance member, but it is invalid if
1471 /// so, because the context is not an instance method.
1472 IMA_Mixed_StaticContext,
1473
1474 /// The reference may be to an instance member, but it is invalid if
1475 /// so, because the context is from an unrelated class.
1476 IMA_Mixed_Unrelated,
1477
1478 /// The reference is definitely an implicit instance member access.
1479 IMA_Instance,
1480
1481 /// The reference may be to an unresolved using declaration.
1482 IMA_Unresolved,
1483
1484 /// The reference may be to an unresolved using declaration and the
1485 /// context is not an instance method.
1486 IMA_Unresolved_StaticContext,
1487
John McCall2d74de92009-12-01 22:10:20 +00001488 /// All possible referrents are instance members and the current
1489 /// context is not an instance method.
1490 IMA_Error_StaticContext,
1491
1492 /// All possible referrents are instance members of an unrelated
1493 /// class.
1494 IMA_Error_Unrelated
1495};
1496
1497/// The given lookup names class member(s) and is not being used for
1498/// an address-of-member expression. Classify the type of access
1499/// according to whether it's possible that this reference names an
1500/// instance member. This is best-effort; it is okay to
1501/// conservatively answer "yes", in which case some errors will simply
1502/// not be caught until template-instantiation.
1503static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
Richard Smith938f40b2011-06-11 17:19:42 +00001504 Scope *CurScope,
John McCall2d74de92009-12-01 22:10:20 +00001505 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +00001506 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +00001507
John McCall87fe5d52010-05-20 01:18:31 +00001508 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
Richard Smith938f40b2011-06-11 17:19:42 +00001509
John McCall2d74de92009-12-01 22:10:20 +00001510 bool isStaticContext =
John McCall87fe5d52010-05-20 01:18:31 +00001511 (!isa<CXXMethodDecl>(DC) ||
1512 cast<CXXMethodDecl>(DC)->isStatic());
John McCall2d74de92009-12-01 22:10:20 +00001513
Richard Smith938f40b2011-06-11 17:19:42 +00001514 // C++0x [expr.prim]p4:
1515 // Otherwise, if a member-declarator declares a non-static data member
1516 // of a class X, the expression this is a prvalue of type "pointer to X"
1517 // within the optional brace-or-equal-initializer.
1518 if (CurScope->getFlags() & Scope::ThisScope)
1519 isStaticContext = false;
1520
John McCall2d74de92009-12-01 22:10:20 +00001521 if (R.isUnresolvableResult())
1522 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1523
1524 // Collect all the declaring classes of instance members we find.
1525 bool hasNonInstance = false;
Sebastian Redl34620312010-11-26 16:28:07 +00001526 bool hasField = false;
John McCall2d74de92009-12-01 22:10:20 +00001527 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1528 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCalla8ae2222010-04-06 21:38:20 +00001529 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00001530
John McCalla8ae2222010-04-06 21:38:20 +00001531 if (D->isCXXInstanceMember()) {
Sebastian Redl34620312010-11-26 16:28:07 +00001532 if (dyn_cast<FieldDecl>(D))
1533 hasField = true;
1534
John McCall2d74de92009-12-01 22:10:20 +00001535 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCall2d74de92009-12-01 22:10:20 +00001536 Classes.insert(R->getCanonicalDecl());
1537 }
1538 else
1539 hasNonInstance = true;
1540 }
1541
1542 // If we didn't find any instance members, it can't be an implicit
1543 // member reference.
1544 if (Classes.empty())
1545 return IMA_Static;
1546
1547 // If the current context is not an instance method, it can't be
1548 // an implicit member reference.
Sebastian Redl34620312010-11-26 16:28:07 +00001549 if (isStaticContext) {
1550 if (hasNonInstance)
1551 return IMA_Mixed_StaticContext;
1552
1553 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1554 // C++0x [expr.prim.general]p10:
1555 // An id-expression that denotes a non-static data member or non-static
1556 // member function of a class can only be used:
1557 // (...)
John McCall31168b02011-06-15 23:02:42 +00001558 // - if that id-expression denotes a non-static data member and it
1559 // appears in an unevaluated operand.
1560 const Sema::ExpressionEvaluationContextRecord& record
1561 = SemaRef.ExprEvalContexts.back();
1562 bool isUnevaluatedExpression = (record.Context == Sema::Unevaluated);
Sebastian Redl34620312010-11-26 16:28:07 +00001563 if (isUnevaluatedExpression)
1564 return IMA_Mixed_StaticContext;
1565 }
1566
1567 return IMA_Error_StaticContext;
1568 }
John McCall2d74de92009-12-01 22:10:20 +00001569
Richard Smith938f40b2011-06-11 17:19:42 +00001570 CXXRecordDecl *contextClass;
1571 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
1572 contextClass = MD->getParent()->getCanonicalDecl();
1573 else
1574 contextClass = cast<CXXRecordDecl>(DC);
Argyrios Kyrtzidis36e4ae32011-04-14 00:46:47 +00001575
1576 // [class.mfct.non-static]p3:
1577 // ...is used in the body of a non-static member function of class X,
1578 // if name lookup (3.4.1) resolves the name in the id-expression to a
1579 // non-static non-type member of some class C [...]
1580 // ...if C is not X or a base class of X, the class member access expression
1581 // is ill-formed.
1582 if (R.getNamingClass() &&
1583 contextClass != R.getNamingClass()->getCanonicalDecl() &&
1584 contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
1585 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1586
John McCall2d74de92009-12-01 22:10:20 +00001587 // If we can prove that the current context is unrelated to all the
1588 // declaring classes, it can't be an implicit member reference (in
1589 // which case it's an error if any of those members are selected).
Argyrios Kyrtzidis36e4ae32011-04-14 00:46:47 +00001590 if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
John McCall2d74de92009-12-01 22:10:20 +00001591 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1592
1593 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1594}
1595
1596/// Diagnose a reference to a field with no object available.
1597static void DiagnoseInstanceReference(Sema &SemaRef,
1598 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00001599 NamedDecl *rep,
1600 const DeclarationNameInfo &nameInfo) {
1601 SourceLocation Loc = nameInfo.getLoc();
John McCall2d74de92009-12-01 22:10:20 +00001602 SourceRange Range(Loc);
1603 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1604
John McCallf3a88602011-02-03 08:15:49 +00001605 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCall2d74de92009-12-01 22:10:20 +00001606 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1607 if (MD->isStatic()) {
1608 // "invalid use of member 'x' in static member function"
1609 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCallf3a88602011-02-03 08:15:49 +00001610 << Range << nameInfo.getName();
John McCall2d74de92009-12-01 22:10:20 +00001611 return;
1612 }
1613 }
1614
1615 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCallf3a88602011-02-03 08:15:49 +00001616 << nameInfo.getName() << Range;
John McCall2d74de92009-12-01 22:10:20 +00001617 return;
1618 }
1619
1620 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +00001621}
1622
John McCalld681c392009-12-16 08:11:27 +00001623/// Diagnose an empty lookup.
1624///
1625/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001626bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1627 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001628 DeclarationName Name = R.getLookupName();
1629
John McCalld681c392009-12-16 08:11:27 +00001630 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001631 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001632 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1633 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001634 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001635 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001636 diagnostic_suggest = diag::err_undeclared_use_suggest;
1637 }
John McCalld681c392009-12-16 08:11:27 +00001638
Douglas Gregor598b08f2009-12-31 05:20:13 +00001639 // If the original lookup was an unqualified lookup, fake an
1640 // unqualified lookup. This is useful when (for example) the
1641 // original lookup would not have found something because it was a
1642 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001643 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001644 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001645 if (isa<CXXRecordDecl>(DC)) {
1646 LookupQualifiedName(R, DC);
1647
1648 if (!R.empty()) {
1649 // Don't give errors about ambiguities in this lookup.
1650 R.suppressDiagnostics();
1651
1652 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1653 bool isInstance = CurMethod &&
1654 CurMethod->isInstance() &&
1655 DC == CurMethod->getParent();
1656
1657 // Give a code modification hint to insert 'this->'.
1658 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1659 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001660 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001661 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1662 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001663 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001664 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001665 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001666 Diag(R.getNameLoc(), diagnostic) << Name
1667 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1668 QualType DepThisType = DepMethod->getThisType(Context);
1669 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1670 R.getNameLoc(), DepThisType, false);
1671 TemplateArgumentListInfo TList;
1672 if (ULE->hasExplicitTemplateArgs())
1673 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001674
Douglas Gregore16af532011-02-28 18:50:33 +00001675 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001676 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001677 CXXDependentScopeMemberExpr *DepExpr =
1678 CXXDependentScopeMemberExpr::Create(
1679 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001680 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyfe712382010-08-20 20:54:15 +00001681 R.getLookupNameInfo(), &TList);
1682 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001683 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001684 // FIXME: we should be able to handle this case too. It is correct
1685 // to add this-> here. This is a workaround for PR7947.
1686 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001687 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001688 } else {
John McCalld681c392009-12-16 08:11:27 +00001689 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001690 }
John McCalld681c392009-12-16 08:11:27 +00001691
1692 // Do we really want to note all of these?
1693 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1694 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1695
1696 // Tell the callee to try to recover.
1697 return false;
1698 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001699
1700 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001701 }
1702 }
1703
Douglas Gregor598b08f2009-12-31 05:20:13 +00001704 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001705 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +00001706 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001707 if (!R.empty()) {
1708 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1709 if (SS.isEmpty())
1710 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1711 << FixItHint::CreateReplacement(R.getNameLoc(),
1712 R.getLookupName().getAsString());
1713 else
1714 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1715 << Name << computeDeclContext(SS, false) << R.getLookupName()
1716 << SS.getRange()
1717 << FixItHint::CreateReplacement(R.getNameLoc(),
1718 R.getLookupName().getAsString());
1719 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1720 Diag(ND->getLocation(), diag::note_previous_decl)
1721 << ND->getDeclName();
1722
1723 // Tell the callee to try to recover.
1724 return false;
1725 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001726
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001727 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1728 // FIXME: If we ended up with a typo for a type name or
1729 // Objective-C class name, we're in trouble because the parser
1730 // is in the wrong place to recover. Suggest the typo
1731 // correction, but don't make it a fix-it since we're not going
1732 // to recover well anyway.
1733 if (SS.isEmpty())
1734 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1735 else
1736 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1737 << Name << computeDeclContext(SS, false) << R.getLookupName()
1738 << SS.getRange();
1739
1740 // Don't try to recover; it won't work.
1741 return true;
1742 }
1743 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001744 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001745 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001746 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001747 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001748 else
Douglas Gregor25363982010-01-01 00:15:04 +00001749 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001750 << Name << computeDeclContext(SS, false) << Corrected
1751 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001752 return true;
1753 }
Douglas Gregor25363982010-01-01 00:15:04 +00001754 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001755 }
1756
1757 // Emit a special diagnostic for failed member lookups.
1758 // FIXME: computing the declaration context might fail here (?)
1759 if (!SS.isEmpty()) {
1760 Diag(R.getNameLoc(), diag::err_no_member)
1761 << Name << computeDeclContext(SS, false)
1762 << SS.getRange();
1763 return true;
1764 }
1765
John McCalld681c392009-12-16 08:11:27 +00001766 // Give up, we can't recover.
1767 Diag(R.getNameLoc(), diagnostic) << Name;
1768 return true;
1769}
1770
Douglas Gregor05fcf842010-11-02 20:36:02 +00001771ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1772 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001773 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1774 if (!IDecl)
1775 return 0;
1776 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1777 if (!ClassImpDecl)
1778 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001779 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001780 if (!property)
1781 return 0;
1782 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001783 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1784 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001785 return 0;
1786 return property;
1787}
1788
Douglas Gregor05fcf842010-11-02 20:36:02 +00001789bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1790 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1791 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1792 if (!IDecl)
1793 return false;
1794 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1795 if (!ClassImpDecl)
1796 return false;
1797 if (ObjCPropertyImplDecl *PIDecl
1798 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1799 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1800 PIDecl->getPropertyIvarDecl())
1801 return false;
1802
1803 return true;
1804}
1805
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001806ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1807 IdentifierInfo *II,
1808 SourceLocation NameLoc) {
1809 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001810 bool LookForIvars;
1811 if (Lookup.empty())
1812 LookForIvars = true;
1813 else if (CurMeth->isClassMethod())
1814 LookForIvars = false;
1815 else
1816 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001817 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1818 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001819 if (!LookForIvars)
1820 return 0;
1821
Fariborz Jahanian18722982010-07-17 00:59:30 +00001822 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1823 if (!IDecl)
1824 return 0;
1825 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001826 if (!ClassImpDecl)
1827 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001828 bool DynamicImplSeen = false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001829 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian18722982010-07-17 00:59:30 +00001830 if (!property)
1831 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001832 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001833 DynamicImplSeen =
1834 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001835 // property implementation has a designated ivar. No need to assume a new
1836 // one.
1837 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1838 return 0;
1839 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001840 if (!DynamicImplSeen) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001841 QualType PropType = Context.getCanonicalType(property->getType());
1842 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001843 NameLoc, NameLoc,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001844 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001845 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001846 (Expr *)0, true);
1847 ClassImpDecl->addDecl(Ivar);
1848 IDecl->makeDeclVisibleInContext(Ivar, false);
1849 property->setPropertyIvarDecl(Ivar);
1850 return Ivar;
1851 }
1852 return 0;
1853}
1854
John McCalldadc5752010-08-24 06:29:42 +00001855ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001856 CXXScopeSpec &SS,
1857 UnqualifiedId &Id,
1858 bool HasTrailingLParen,
1859 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001860 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1861 "cannot be direct & operand and have a trailing lparen");
1862
1863 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001864 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001865
John McCall10eae182009-11-30 22:42:35 +00001866 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001867
1868 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001869 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001870 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001871 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001872
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001873 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001874 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001875 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001876
John McCalle66edc12009-11-24 19:00:30 +00001877 // C++ [temp.dep.expr]p3:
1878 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001879 // -- an identifier that was declared with a dependent type,
1880 // (note: handled after lookup)
1881 // -- a template-id that is dependent,
1882 // (note: handled in BuildTemplateIdExpr)
1883 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001884 // -- a nested-name-specifier that contains a class-name that
1885 // names a dependent type.
1886 // Determine whether this is a member of an unknown specialization;
1887 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001888 bool DependentID = false;
1889 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1890 Name.getCXXNameType()->isDependentType()) {
1891 DependentID = true;
1892 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001893 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001894 if (RequireCompleteDeclContext(SS, DC))
1895 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001896 } else {
1897 DependentID = true;
1898 }
1899 }
1900
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001901 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001902 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001903 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001904
Fariborz Jahanian86151342010-07-22 23:33:21 +00001905 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001906 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001907 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001908 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001909 // Lookup the template name again to correctly establish the context in
1910 // which it was found. This is really unfortunate as we already did the
1911 // lookup to determine that it was a template name in the first place. If
1912 // this becomes a performance hit, we can work harder to preserve those
1913 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001914 bool MemberOfUnknownSpecialization;
1915 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1916 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001917
1918 if (MemberOfUnknownSpecialization ||
1919 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1920 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1921 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001922 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001923 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001924 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001925
Douglas Gregora5226932011-02-04 13:35:07 +00001926 // If the result might be in a dependent base class, this is a dependent
1927 // id-expression.
1928 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1929 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1930 TemplateArgs);
1931
John McCalle66edc12009-11-24 19:00:30 +00001932 // If this reference is in an Objective-C method, then we need to do
1933 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001934 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001935 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001936 if (E.isInvalid())
1937 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001938
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001939 if (Expr *Ex = E.takeAs<Expr>())
1940 return Owned(Ex);
1941
1942 // Synthesize ivars lazily.
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001943 if (getLangOptions().ObjCDefaultSynthProperties &&
1944 getLangOptions().ObjCNonFragileABI2) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001945 if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001946 if (const ObjCPropertyDecl *Property =
1947 canSynthesizeProvisionalIvar(II)) {
1948 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1949 Diag(Property->getLocation(), diag::note_property_declare);
1950 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001951 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1952 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001953 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001954 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001955 // for further use, this must be set to false if in class method.
1956 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001957 }
Chris Lattner59a25942008-03-31 00:36:02 +00001958 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001959
John McCalle66edc12009-11-24 19:00:30 +00001960 if (R.isAmbiguous())
1961 return ExprError();
1962
Douglas Gregor171c45a2009-02-18 21:56:37 +00001963 // Determine whether this name might be a candidate for
1964 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001965 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001966
John McCalle66edc12009-11-24 19:00:30 +00001967 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001968 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001969 // in C90, extension in C99, forbidden in C++).
1970 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1971 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1972 if (D) R.addDecl(D);
1973 }
1974
1975 // If this name wasn't predeclared and if this is not a function
1976 // call, diagnose the problem.
1977 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001978 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001979 return ExprError();
1980
1981 assert(!R.empty() &&
1982 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001983
1984 // If we found an Objective-C instance variable, let
1985 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001986 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001987 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1988 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001989 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001990 assert(E.isInvalid() || E.get());
1991 return move(E);
1992 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001993 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001994 }
Mike Stump11289f42009-09-09 15:08:12 +00001995
John McCalle66edc12009-11-24 19:00:30 +00001996 // This is guaranteed from this point on.
1997 assert(!R.empty() || ADL);
1998
John McCall2d74de92009-12-01 22:10:20 +00001999 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00002000 // C++ [class.mfct.non-static]p3:
2001 // When an id-expression that is not part of a class member access
2002 // syntax and not used to form a pointer to member is used in the
2003 // body of a non-static member function of class X, if name lookup
2004 // resolves the name in the id-expression to a non-static non-type
2005 // member of some class C, the id-expression is transformed into a
2006 // class member access expression using (*this) as the
2007 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00002008 //
2009 // But we don't actually need to do this for '&' operands if R
2010 // resolved to a function or overloaded function set, because the
2011 // expression is ill-formed if it actually works out to be a
2012 // non-static member function:
2013 //
2014 // C++ [expr.ref]p4:
2015 // Otherwise, if E1.E2 refers to a non-static member function. . .
2016 // [t]he expression can be used only as the left-hand operand of a
2017 // member function call.
2018 //
2019 // There are other safeguards against such uses, but it's important
2020 // to get this right here so that we don't end up making a
2021 // spuriously dependent expression if we're inside a dependent
2022 // instance method.
John McCall57500772009-12-16 12:17:52 +00002023 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00002024 bool MightBeImplicitMember;
2025 if (!isAddressOfOperand)
2026 MightBeImplicitMember = true;
2027 else if (!SS.isEmpty())
2028 MightBeImplicitMember = false;
2029 else if (R.isOverloadedResult())
2030 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00002031 else if (R.isUnresolvableResult())
2032 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00002033 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00002034 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2035 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00002036
2037 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00002038 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00002039 }
2040
John McCalle66edc12009-11-24 19:00:30 +00002041 if (TemplateArgs)
2042 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00002043
John McCalle66edc12009-11-24 19:00:30 +00002044 return BuildDeclarationNameExpr(SS, R, ADL);
2045}
2046
John McCall57500772009-12-16 12:17:52 +00002047/// Builds an expression which might be an implicit member expression.
John McCalldadc5752010-08-24 06:29:42 +00002048ExprResult
John McCall57500772009-12-16 12:17:52 +00002049Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
2050 LookupResult &R,
2051 const TemplateArgumentListInfo *TemplateArgs) {
Richard Smith938f40b2011-06-11 17:19:42 +00002052 switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
John McCall57500772009-12-16 12:17:52 +00002053 case IMA_Instance:
2054 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
2055
John McCall57500772009-12-16 12:17:52 +00002056 case IMA_Mixed:
2057 case IMA_Mixed_Unrelated:
2058 case IMA_Unresolved:
2059 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
2060
2061 case IMA_Static:
2062 case IMA_Mixed_StaticContext:
2063 case IMA_Unresolved_StaticContext:
2064 if (TemplateArgs)
2065 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
2066 return BuildDeclarationNameExpr(SS, R, false);
2067
2068 case IMA_Error_StaticContext:
2069 case IMA_Error_Unrelated:
John McCallf3a88602011-02-03 08:15:49 +00002070 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
2071 R.getLookupNameInfo());
John McCall57500772009-12-16 12:17:52 +00002072 return ExprError();
2073 }
2074
2075 llvm_unreachable("unexpected instance member access kind");
2076 return ExprError();
2077}
2078
John McCall10eae182009-11-30 22:42:35 +00002079/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2080/// declaration name, generally during template instantiation.
2081/// There's a large number of things which don't need to be done along
2082/// this path.
John McCalldadc5752010-08-24 06:29:42 +00002083ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002084Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002085 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00002086 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00002087 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002088 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00002089
John McCall0b66eb32010-05-01 00:40:08 +00002090 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00002091 return ExprError();
2092
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002093 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00002094 LookupQualifiedName(R, DC);
2095
2096 if (R.isAmbiguous())
2097 return ExprError();
2098
2099 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002100 Diag(NameInfo.getLoc(), diag::err_no_member)
2101 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002102 return ExprError();
2103 }
2104
2105 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
2106}
2107
2108/// LookupInObjCMethod - The parser has read a name in, and Sema has
2109/// detected that we're currently inside an ObjC method. Perform some
2110/// additional lookup.
2111///
2112/// Ideally, most of this would be done by lookup, but there's
2113/// actually quite a lot of extra work involved.
2114///
2115/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00002116ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002117Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00002118 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00002119 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00002120 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00002121
John McCalle66edc12009-11-24 19:00:30 +00002122 // There are two cases to handle here. 1) scoped lookup could have failed,
2123 // in which case we should look for an ivar. 2) scoped lookup could have
2124 // found a decl, but that decl is outside the current instance method (i.e.
2125 // a global variable). In these two cases, we do a lookup for an ivar with
2126 // this name, if the lookup sucedes, we replace it our current decl.
2127
2128 // If we're in a class method, we don't normally want to look for
2129 // ivars. But if we don't find anything else, and there's an
2130 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00002131 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00002132
2133 bool LookForIvars;
2134 if (Lookup.empty())
2135 LookForIvars = true;
2136 else if (IsClassMethod)
2137 LookForIvars = false;
2138 else
2139 LookForIvars = (Lookup.isSingleResult() &&
2140 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00002141 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00002142 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00002143 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00002144 ObjCInterfaceDecl *ClassDeclared;
2145 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2146 // Diagnose using an ivar in a class method.
2147 if (IsClassMethod)
2148 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2149 << IV->getDeclName());
2150
2151 // If we're referencing an invalid decl, just return this as a silent
2152 // error node. The error diagnostic was already emitted on the decl.
2153 if (IV->isInvalidDecl())
2154 return ExprError();
2155
2156 // Check if referencing a field with __attribute__((deprecated)).
2157 if (DiagnoseUseOfDecl(IV, Loc))
2158 return ExprError();
2159
2160 // Diagnose the use of an ivar outside of the declaring class.
2161 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2162 ClassDeclared != IFace)
2163 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2164
2165 // FIXME: This should use a new expr for a direct reference, don't
2166 // turn this into Self->ivar, just return a BareIVarExpr or something.
2167 IdentifierInfo &II = Context.Idents.get("self");
2168 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002169 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00002170 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00002171 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00002172 SelfName, false, false);
2173 if (SelfExpr.isInvalid())
2174 return ExprError();
2175
John Wiegley01296292011-04-08 18:41:53 +00002176 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2177 if (SelfExpr.isInvalid())
2178 return ExprError();
John McCall27584242010-12-06 20:48:59 +00002179
John McCalle66edc12009-11-24 19:00:30 +00002180 MarkDeclarationReferenced(Loc, IV);
Fariborz Jahanian82bc4362011-04-12 23:39:33 +00002181 Expr *base = SelfExpr.take();
2182 base = base->IgnoreParenImpCasts();
2183 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(base)) {
2184 const NamedDecl *ND = DE->getDecl();
2185 if (!isa<ImplicitParamDecl>(ND)) {
Fariborz Jahanian66a6c062011-04-15 17:04:42 +00002186 // relax the rule such that it is allowed to have a shadow 'self'
2187 // where stand-alone ivar can be found in this 'self' object.
2188 // This is to match gcc's behavior.
2189 ObjCInterfaceDecl *selfIFace = 0;
2190 if (const ObjCObjectPointerType *OPT =
2191 base->getType()->getAsObjCInterfacePointerType())
2192 selfIFace = OPT->getInterfaceDecl();
2193 if (!selfIFace ||
2194 !selfIFace->lookupInstanceVariable(IV->getIdentifier())) {
Fariborz Jahanian82bc4362011-04-12 23:39:33 +00002195 Diag(Loc, diag::error_implicit_ivar_access)
2196 << IV->getDeclName();
2197 Diag(ND->getLocation(), diag::note_declared_at);
2198 return ExprError();
2199 }
Fariborz Jahanian66a6c062011-04-15 17:04:42 +00002200 }
Fariborz Jahanian82bc4362011-04-12 23:39:33 +00002201 }
John McCalle66edc12009-11-24 19:00:30 +00002202 return Owned(new (Context)
2203 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00002204 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00002205 }
Chris Lattner87313662010-04-12 05:10:17 +00002206 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00002207 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00002208 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00002209 ObjCInterfaceDecl *ClassDeclared;
2210 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2211 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2212 IFace == ClassDeclared)
2213 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2214 }
2215 }
2216
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002217 if (Lookup.empty() && II && AllowBuiltinCreation) {
2218 // FIXME. Consolidate this with similar code in LookupName.
2219 if (unsigned BuiltinID = II->getBuiltinID()) {
2220 if (!(getLangOptions().CPlusPlus &&
2221 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2222 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2223 S, Lookup.isForRedeclaration(),
2224 Lookup.getNameLoc());
2225 if (D) Lookup.addDecl(D);
2226 }
2227 }
2228 }
John McCalle66edc12009-11-24 19:00:30 +00002229 // Sentinel value saying that we didn't do anything special.
2230 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00002231}
John McCalld14a8642009-11-21 08:51:07 +00002232
John McCall16df1e52010-03-30 21:47:33 +00002233/// \brief Cast a base object to a member's actual type.
2234///
2235/// Logically this happens in three phases:
2236///
2237/// * First we cast from the base type to the naming class.
2238/// The naming class is the class into which we were looking
2239/// when we found the member; it's the qualifier type if a
2240/// qualifier was provided, and otherwise it's the base type.
2241///
2242/// * Next we cast from the naming class to the declaring class.
2243/// If the member we found was brought into a class's scope by
2244/// a using declaration, this is that class; otherwise it's
2245/// the class declaring the member.
2246///
2247/// * Finally we cast from the declaring class to the "true"
2248/// declaring class of the member. This conversion does not
2249/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00002250ExprResult
2251Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002252 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002253 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002254 NamedDecl *Member) {
2255 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2256 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00002257 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002258
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002259 QualType DestRecordType;
2260 QualType DestType;
2261 QualType FromRecordType;
2262 QualType FromType = From->getType();
2263 bool PointerConversions = false;
2264 if (isa<FieldDecl>(Member)) {
2265 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002266
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002267 if (FromType->getAs<PointerType>()) {
2268 DestType = Context.getPointerType(DestRecordType);
2269 FromRecordType = FromType->getPointeeType();
2270 PointerConversions = true;
2271 } else {
2272 DestType = DestRecordType;
2273 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002274 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002275 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2276 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00002277 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002278
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002279 DestType = Method->getThisType(Context);
2280 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002281
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002282 if (FromType->getAs<PointerType>()) {
2283 FromRecordType = FromType->getPointeeType();
2284 PointerConversions = true;
2285 } else {
2286 FromRecordType = FromType;
2287 DestType = DestRecordType;
2288 }
2289 } else {
2290 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00002291 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002292 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002293
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002294 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002295 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002296
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002297 // If the unqualified types are the same, no conversion is necessary.
2298 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002299 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002300
John McCall16df1e52010-03-30 21:47:33 +00002301 SourceRange FromRange = From->getSourceRange();
2302 SourceLocation FromLoc = FromRange.getBegin();
2303
John McCall2536c6d2010-08-25 10:28:54 +00002304 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002305
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002306 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002307 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002308 // class name.
2309 //
2310 // If the member was a qualified name and the qualified referred to a
2311 // specific base subobject type, we'll cast to that intermediate type
2312 // first and then to the object in which the member is declared. That allows
2313 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2314 //
2315 // class Base { public: int x; };
2316 // class Derived1 : public Base { };
2317 // class Derived2 : public Base { };
2318 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2319 //
2320 // void VeryDerived::f() {
2321 // x = 17; // error: ambiguous base subobjects
2322 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2323 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002324 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002325 QualType QType = QualType(Qualifier->getAsType(), 0);
2326 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2327 assert(QType->isRecordType() && "lookup done with non-record type");
2328
2329 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2330
2331 // In C++98, the qualifier type doesn't actually have to be a base
2332 // type of the object type, in which case we just ignore it.
2333 // Otherwise build the appropriate casts.
2334 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002335 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002336 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002337 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002338 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002339
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002340 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002341 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002342 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2343 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002344
2345 FromType = QType;
2346 FromRecordType = QRecordType;
2347
2348 // If the qualifier type was the same as the destination type,
2349 // we're done.
2350 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002351 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002352 }
2353 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002354
John McCall16df1e52010-03-30 21:47:33 +00002355 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002356
John McCall16df1e52010-03-30 21:47:33 +00002357 // If we actually found the member through a using declaration, cast
2358 // down to the using declaration's type.
2359 //
2360 // Pointer equality is fine here because only one declaration of a
2361 // class ever has member declarations.
2362 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2363 assert(isa<UsingShadowDecl>(FoundDecl));
2364 QualType URecordType = Context.getTypeDeclType(
2365 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2366
2367 // We only need to do this if the naming-class to declaring-class
2368 // conversion is non-trivial.
2369 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2370 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002371 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002372 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002373 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002374 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002375
John McCall16df1e52010-03-30 21:47:33 +00002376 QualType UType = URecordType;
2377 if (PointerConversions)
2378 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002379 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2380 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002381 FromType = UType;
2382 FromRecordType = URecordType;
2383 }
2384
2385 // We don't do access control for the conversion from the
2386 // declaring class to the true declaring class.
2387 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002388 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002389
John McCallcf142162010-08-07 06:22:56 +00002390 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002391 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2392 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002393 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002394 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002395
John Wiegley01296292011-04-08 18:41:53 +00002396 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2397 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002398}
Douglas Gregor3256d042009-06-30 15:47:41 +00002399
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002400/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00002401static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00002402 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00002403 DeclAccessPair FoundDecl,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002404 const DeclarationNameInfo &MemberNameInfo,
2405 QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +00002406 ExprValueKind VK, ExprObjectKind OK,
John McCalle66edc12009-11-24 19:00:30 +00002407 const TemplateArgumentListInfo *TemplateArgs = 0) {
Douglas Gregorea972d32011-02-28 21:54:11 +00002408 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002409 Member, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002410 TemplateArgs, Ty, VK, OK);
Douglas Gregorc1905232009-08-26 22:36:53 +00002411}
2412
John McCallfeb624a2010-11-23 20:48:44 +00002413static ExprResult
2414BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2415 const CXXScopeSpec &SS, FieldDecl *Field,
2416 DeclAccessPair FoundDecl,
2417 const DeclarationNameInfo &MemberNameInfo) {
2418 // x.a is an l-value if 'a' has a reference type. Otherwise:
2419 // x.a is an l-value/x-value/pr-value if the base is (and note
2420 // that *x is always an l-value), except that if the base isn't
2421 // an ordinary object then we must have an rvalue.
2422 ExprValueKind VK = VK_LValue;
2423 ExprObjectKind OK = OK_Ordinary;
2424 if (!IsArrow) {
2425 if (BaseExpr->getObjectKind() == OK_Ordinary)
2426 VK = BaseExpr->getValueKind();
2427 else
2428 VK = VK_RValue;
2429 }
2430 if (VK != VK_RValue && Field->isBitField())
2431 OK = OK_BitField;
2432
2433 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2434 QualType MemberType = Field->getType();
2435 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2436 MemberType = Ref->getPointeeType();
2437 VK = VK_LValue;
2438 } else {
2439 QualType BaseType = BaseExpr->getType();
2440 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2441
2442 Qualifiers BaseQuals = BaseType.getQualifiers();
2443
2444 // GC attributes are never picked up by members.
2445 BaseQuals.removeObjCGCAttr();
2446
2447 // CVR attributes from the base are picked up by members,
2448 // except that 'mutable' members don't pick up 'const'.
2449 if (Field->isMutable()) BaseQuals.removeConst();
2450
2451 Qualifiers MemberQuals
2452 = S.Context.getCanonicalType(MemberType).getQualifiers();
2453
2454 // TR 18037 does not allow fields to be declared with address spaces.
2455 assert(!MemberQuals.hasAddressSpace());
2456
2457 Qualifiers Combined = BaseQuals + MemberQuals;
2458 if (Combined != MemberQuals)
2459 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2460 }
2461
2462 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
John Wiegley01296292011-04-08 18:41:53 +00002463 ExprResult Base =
2464 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2465 FoundDecl, Field);
2466 if (Base.isInvalid())
John McCallfeb624a2010-11-23 20:48:44 +00002467 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00002468 return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
John McCallfeb624a2010-11-23 20:48:44 +00002469 Field, FoundDecl, MemberNameInfo,
2470 MemberType, VK, OK));
2471}
2472
John McCall2d74de92009-12-01 22:10:20 +00002473/// Builds an implicit member access expression. The current context
2474/// is known to be an instance method, and the given unqualified lookup
2475/// set is known to contain only instance members, at least one of which
2476/// is from an appropriate type.
John McCalldadc5752010-08-24 06:29:42 +00002477ExprResult
John McCall2d74de92009-12-01 22:10:20 +00002478Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2479 LookupResult &R,
2480 const TemplateArgumentListInfo *TemplateArgs,
2481 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00002482 assert(!R.empty() && !R.isAmbiguous());
2483
John McCallf3a88602011-02-03 08:15:49 +00002484 SourceLocation loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00002485
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002486 // We may have found a field within an anonymous union or struct
2487 // (C++ [class.union]).
John McCalle66edc12009-11-24 19:00:30 +00002488 // FIXME: template-ids inside anonymous structs?
Francois Pichet783dd6e2010-11-21 06:08:52 +00002489 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCallf3a88602011-02-03 08:15:49 +00002490 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002491
John McCallf3a88602011-02-03 08:15:49 +00002492 // If this is known to be an instance access, go ahead and build an
2493 // implicit 'this' expression now.
John McCall2d74de92009-12-01 22:10:20 +00002494 // 'this' expression now.
Richard Smith938f40b2011-06-11 17:19:42 +00002495 QualType ThisTy = getAndCaptureCurrentThisType();
2496 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
John McCallf3a88602011-02-03 08:15:49 +00002497
John McCallf3a88602011-02-03 08:15:49 +00002498 Expr *baseExpr = 0; // null signifies implicit access
John McCall2d74de92009-12-01 22:10:20 +00002499 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00002500 SourceLocation Loc = R.getNameLoc();
2501 if (SS.getRange().isValid())
2502 Loc = SS.getRange().getBegin();
Richard Smith938f40b2011-06-11 17:19:42 +00002503 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002504 }
2505
Richard Smith938f40b2011-06-11 17:19:42 +00002506 return BuildMemberReferenceExpr(baseExpr, ThisTy,
John McCall2d74de92009-12-01 22:10:20 +00002507 /*OpLoc*/ SourceLocation(),
2508 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00002509 SS,
2510 /*FirstQualifierInScope*/ 0,
2511 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00002512}
2513
John McCalle66edc12009-11-24 19:00:30 +00002514bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002515 const LookupResult &R,
2516 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002517 // Only when used directly as the postfix-expression of a call.
2518 if (!HasTrailingLParen)
2519 return false;
2520
2521 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002522 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002523 return false;
2524
2525 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002526 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002527 return false;
2528
2529 // Turn off ADL when we find certain kinds of declarations during
2530 // normal lookup:
2531 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2532 NamedDecl *D = *I;
2533
2534 // C++0x [basic.lookup.argdep]p3:
2535 // -- a declaration of a class member
2536 // Since using decls preserve this property, we check this on the
2537 // original decl.
John McCall57500772009-12-16 12:17:52 +00002538 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002539 return false;
2540
2541 // C++0x [basic.lookup.argdep]p3:
2542 // -- a block-scope function declaration that is not a
2543 // using-declaration
2544 // NOTE: we also trigger this for function templates (in fact, we
2545 // don't check the decl type at all, since all other decl types
2546 // turn off ADL anyway).
2547 if (isa<UsingShadowDecl>(D))
2548 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2549 else if (D->getDeclContext()->isFunctionOrMethod())
2550 return false;
2551
2552 // C++0x [basic.lookup.argdep]p3:
2553 // -- a declaration that is neither a function or a function
2554 // template
2555 // And also for builtin functions.
2556 if (isa<FunctionDecl>(D)) {
2557 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2558
2559 // But also builtin functions.
2560 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2561 return false;
2562 } else if (!isa<FunctionTemplateDecl>(D))
2563 return false;
2564 }
2565
2566 return true;
2567}
2568
2569
John McCalld14a8642009-11-21 08:51:07 +00002570/// Diagnoses obvious problems with the use of the given declaration
2571/// as an expression. This is only actually called for lookups that
2572/// were not overloaded, and it doesn't promise that the declaration
2573/// will in fact be used.
2574static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002575 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002576 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2577 return true;
2578 }
2579
2580 if (isa<ObjCInterfaceDecl>(D)) {
2581 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2582 return true;
2583 }
2584
2585 if (isa<NamespaceDecl>(D)) {
2586 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2587 return true;
2588 }
2589
2590 return false;
2591}
2592
John McCalldadc5752010-08-24 06:29:42 +00002593ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002594Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002595 LookupResult &R,
2596 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002597 // If this is a single, fully-resolved result and we don't need ADL,
2598 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002599 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002600 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2601 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002602
2603 // We only need to check the declaration if there's exactly one
2604 // result, because in the overloaded case the results can only be
2605 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002606 if (R.isSingleResult() &&
2607 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002608 return ExprError();
2609
John McCall58cc69d2010-01-27 01:50:18 +00002610 // Otherwise, just build an unresolved lookup expression. Suppress
2611 // any lookup-related diagnostics; we'll hash these out later, when
2612 // we've picked a target.
2613 R.suppressDiagnostics();
2614
John McCalld14a8642009-11-21 08:51:07 +00002615 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002616 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002617 SS.getWithLocInContext(Context),
2618 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002619 NeedsADL, R.isOverloadedResult(),
2620 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002621
2622 return Owned(ULE);
2623}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002624
John McCalld14a8642009-11-21 08:51:07 +00002625/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002626ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002627Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002628 const DeclarationNameInfo &NameInfo,
2629 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002630 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002631 assert(!isa<FunctionTemplateDecl>(D) &&
2632 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002633
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002634 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002635 if (CheckDeclInExpr(*this, Loc, D))
2636 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002637
Douglas Gregore7488b92009-12-01 16:58:18 +00002638 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2639 // Specifically diagnose references to class templates that are missing
2640 // a template argument list.
2641 Diag(Loc, diag::err_template_decl_ref)
2642 << Template << SS.getRange();
2643 Diag(Template->getLocation(), diag::note_template_decl_here);
2644 return ExprError();
2645 }
2646
2647 // Make sure that we're referring to a value.
2648 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2649 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002650 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002651 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002652 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002653 return ExprError();
2654 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002655
Douglas Gregor171c45a2009-02-18 21:56:37 +00002656 // Check whether this declaration can be used. Note that we suppress
2657 // this check when we're going to perform argument-dependent lookup
2658 // on this function name, because this might not be the function
2659 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002660 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002661 return ExprError();
2662
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002663 // Only create DeclRefExpr's for valid Decl's.
2664 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002665 return ExprError();
2666
John McCallf3a88602011-02-03 08:15:49 +00002667 // Handle members of anonymous structs and unions. If we got here,
2668 // and the reference is to a class member indirect field, then this
2669 // must be the subject of a pointer-to-member expression.
2670 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2671 if (!indirectField->isCXXClassMember())
2672 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2673 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002674
Chris Lattner2a9d9892008-10-20 05:16:36 +00002675 // If the identifier reference is inside a block, and it refers to a value
2676 // that is outside the block, create a BlockDeclRefExpr instead of a
2677 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2678 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002679 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002680 // We do not do this for things like enum constants, global variables, etc,
2681 // as they do not get snapshotted.
2682 //
John McCall351762c2011-02-07 10:33:21 +00002683 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002684 case CR_Error:
2685 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002686
John McCallc63de662011-02-02 13:00:07 +00002687 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002688 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2689 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2690
2691 case CR_CaptureByRef:
2692 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2693 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002694
2695 case CR_NoCapture: {
2696 // If this reference is not in a block or if the referenced
2697 // variable is within the block, create a normal DeclRefExpr.
2698
2699 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002700 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002701
2702 switch (D->getKind()) {
2703 // Ignore all the non-ValueDecl kinds.
2704#define ABSTRACT_DECL(kind)
2705#define VALUE(type, base)
2706#define DECL(type, base) \
2707 case Decl::type:
2708#include "clang/AST/DeclNodes.inc"
2709 llvm_unreachable("invalid value decl kind");
2710 return ExprError();
2711
2712 // These shouldn't make it here.
2713 case Decl::ObjCAtDefsField:
2714 case Decl::ObjCIvar:
2715 llvm_unreachable("forming non-member reference to ivar?");
2716 return ExprError();
2717
2718 // Enum constants are always r-values and never references.
2719 // Unresolved using declarations are dependent.
2720 case Decl::EnumConstant:
2721 case Decl::UnresolvedUsingValue:
2722 valueKind = VK_RValue;
2723 break;
2724
2725 // Fields and indirect fields that got here must be for
2726 // pointer-to-member expressions; we just call them l-values for
2727 // internal consistency, because this subexpression doesn't really
2728 // exist in the high-level semantics.
2729 case Decl::Field:
2730 case Decl::IndirectField:
2731 assert(getLangOptions().CPlusPlus &&
2732 "building reference to field in C?");
2733
2734 // These can't have reference type in well-formed programs, but
2735 // for internal consistency we do this anyway.
2736 type = type.getNonReferenceType();
2737 valueKind = VK_LValue;
2738 break;
2739
2740 // Non-type template parameters are either l-values or r-values
2741 // depending on the type.
2742 case Decl::NonTypeTemplateParm: {
2743 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2744 type = reftype->getPointeeType();
2745 valueKind = VK_LValue; // even if the parameter is an r-value reference
2746 break;
2747 }
2748
2749 // For non-references, we need to strip qualifiers just in case
2750 // the template parameter was declared as 'const int' or whatever.
2751 valueKind = VK_RValue;
2752 type = type.getUnqualifiedType();
2753 break;
2754 }
2755
2756 case Decl::Var:
2757 // In C, "extern void blah;" is valid and is an r-value.
2758 if (!getLangOptions().CPlusPlus &&
2759 !type.hasQualifiers() &&
2760 type->isVoidType()) {
2761 valueKind = VK_RValue;
2762 break;
2763 }
2764 // fallthrough
2765
2766 case Decl::ImplicitParam:
2767 case Decl::ParmVar:
2768 // These are always l-values.
2769 valueKind = VK_LValue;
2770 type = type.getNonReferenceType();
2771 break;
2772
2773 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002774 const FunctionType *fty = type->castAs<FunctionType>();
2775
2776 // If we're referring to a function with an __unknown_anytype
2777 // result type, make the entire expression __unknown_anytype.
2778 if (fty->getResultType() == Context.UnknownAnyTy) {
2779 type = Context.UnknownAnyTy;
2780 valueKind = VK_RValue;
2781 break;
2782 }
2783
John McCallf4cd4f92011-02-09 01:13:10 +00002784 // Functions are l-values in C++.
2785 if (getLangOptions().CPlusPlus) {
2786 valueKind = VK_LValue;
2787 break;
2788 }
2789
2790 // C99 DR 316 says that, if a function type comes from a
2791 // function definition (without a prototype), that type is only
2792 // used for checking compatibility. Therefore, when referencing
2793 // the function, we pretend that we don't have the full function
2794 // type.
John McCall2979fe02011-04-12 00:42:48 +00002795 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2796 isa<FunctionProtoType>(fty))
2797 type = Context.getFunctionNoProtoType(fty->getResultType(),
2798 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002799
2800 // Functions are r-values in C.
2801 valueKind = VK_RValue;
2802 break;
2803 }
2804
2805 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002806 // If we're referring to a method with an __unknown_anytype
2807 // result type, make the entire expression __unknown_anytype.
2808 // This should only be possible with a type written directly.
2809 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(VD->getType()))
2810 if (proto->getResultType() == Context.UnknownAnyTy) {
2811 type = Context.UnknownAnyTy;
2812 valueKind = VK_RValue;
2813 break;
2814 }
2815
John McCallf4cd4f92011-02-09 01:13:10 +00002816 // C++ methods are l-values if static, r-values if non-static.
2817 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2818 valueKind = VK_LValue;
2819 break;
2820 }
2821 // fallthrough
2822
2823 case Decl::CXXConversion:
2824 case Decl::CXXDestructor:
2825 case Decl::CXXConstructor:
2826 valueKind = VK_RValue;
2827 break;
2828 }
2829
2830 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2831 }
2832
John McCallc63de662011-02-02 13:00:07 +00002833 }
John McCall7decc9e2010-11-18 06:31:45 +00002834
John McCall351762c2011-02-07 10:33:21 +00002835 llvm_unreachable("unknown capture result");
2836 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002837}
Chris Lattnere168f762006-11-10 05:29:30 +00002838
John McCall2979fe02011-04-12 00:42:48 +00002839ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002840 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002841
Chris Lattnere168f762006-11-10 05:29:30 +00002842 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002843 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002844 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2845 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2846 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002847 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002848
Chris Lattnera81a0272008-01-12 08:14:25 +00002849 // Pre-defined identifiers are of type char[x], where x is the length of the
2850 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002851
Anders Carlsson2fb08242009-09-08 18:24:21 +00002852 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002853 if (!currentDecl && getCurBlock())
2854 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002855 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002856 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002857 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002858 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002859
Anders Carlsson0b209a82009-09-11 01:22:35 +00002860 QualType ResTy;
2861 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2862 ResTy = Context.DependentTy;
2863 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002864 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002865
Anders Carlsson0b209a82009-09-11 01:22:35 +00002866 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002867 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002868 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2869 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002870 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002871}
2872
John McCalldadc5752010-08-24 06:29:42 +00002873ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002874 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002875 bool Invalid = false;
2876 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2877 if (Invalid)
2878 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002879
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002880 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2881 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002882 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002883 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002884
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002885 QualType Ty;
2886 if (!getLangOptions().CPlusPlus)
2887 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2888 else if (Literal.isWide())
2889 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002890 else if (Literal.isMultiChar())
2891 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002892 else
2893 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002894
Sebastian Redl20614a72009-01-20 22:23:13 +00002895 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2896 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002897 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002898}
2899
John McCalldadc5752010-08-24 06:29:42 +00002900ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002901 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002902 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2903 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002904 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002905 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002906 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002907 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002908 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002909
Chris Lattner23b7eb62007-06-15 23:05:46 +00002910 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002911 // Add padding so that NumericLiteralParser can overread by one character.
2912 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002913 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002914
Chris Lattner67ca9252007-05-21 01:08:44 +00002915 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002916 bool Invalid = false;
2917 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2918 if (Invalid)
2919 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002920
Mike Stump11289f42009-09-09 15:08:12 +00002921 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002922 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002923 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002924 return ExprError();
2925
Chris Lattner1c20a172007-08-26 03:42:43 +00002926 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002927
Chris Lattner1c20a172007-08-26 03:42:43 +00002928 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002929 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002930 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002931 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002932 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002933 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002934 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002935 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002936
2937 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2938
John McCall53b93a02009-12-24 09:08:04 +00002939 using llvm::APFloat;
2940 APFloat Val(Format);
2941
2942 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002943
2944 // Overflow is always an error, but underflow is only an error if
2945 // we underflowed to zero (APFloat reports denormals as underflow).
2946 if ((result & APFloat::opOverflow) ||
2947 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002948 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002949 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002950 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002951 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002952 APFloat::getLargest(Format).toString(buffer);
2953 } else {
John McCall62abc942010-02-26 23:35:57 +00002954 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002955 APFloat::getSmallest(Format).toString(buffer);
2956 }
2957
2958 Diag(Tok.getLocation(), diagnostic)
2959 << Ty
2960 << llvm::StringRef(buffer.data(), buffer.size());
2961 }
2962
2963 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002964 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002965
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002966 if (Ty == Context.DoubleTy) {
2967 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002968 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002969 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2970 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002971 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002972 }
2973 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002974 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002975 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002976 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002977 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002978
Neil Boothac582c52007-08-29 22:00:19 +00002979 // long long is a C99 feature.
2980 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002981 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002982 Diag(Tok.getLocation(), diag::ext_longlong);
2983
Chris Lattner67ca9252007-05-21 01:08:44 +00002984 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002985 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002986
Chris Lattner67ca9252007-05-21 01:08:44 +00002987 if (Literal.GetIntegerValue(ResultVal)) {
2988 // If this value didn't fit into uintmax_t, warn and force to ull.
2989 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002990 Ty = Context.UnsignedLongLongTy;
2991 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002992 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002993 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002994 // If this value fits into a ULL, try to figure out what else it fits into
2995 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002996
Chris Lattner67ca9252007-05-21 01:08:44 +00002997 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2998 // be an unsigned int.
2999 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3000
3001 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00003002 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00003003 if (!Literal.isLong && !Literal.isLongLong) {
3004 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00003005 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003006
Chris Lattner67ca9252007-05-21 01:08:44 +00003007 // Does it fit in a unsigned int?
3008 if (ResultVal.isIntN(IntSize)) {
3009 // Does it fit in a signed int?
3010 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003011 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00003012 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003013 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00003014 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00003015 }
Chris Lattner67ca9252007-05-21 01:08:44 +00003016 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003017
Chris Lattner67ca9252007-05-21 01:08:44 +00003018 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003019 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00003020 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003021
Chris Lattner67ca9252007-05-21 01:08:44 +00003022 // Does it fit in a unsigned long?
3023 if (ResultVal.isIntN(LongSize)) {
3024 // Does it fit in a signed long?
3025 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003026 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00003027 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003028 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00003029 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00003030 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003031 }
3032
Chris Lattner67ca9252007-05-21 01:08:44 +00003033 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003034 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00003035 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003036
Chris Lattner67ca9252007-05-21 01:08:44 +00003037 // Does it fit in a unsigned long long?
3038 if (ResultVal.isIntN(LongLongSize)) {
3039 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00003040 // To be compatible with MSVC, hex integer literals ending with the
3041 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00003042 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3043 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003044 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00003045 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003046 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00003047 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00003048 }
3049 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003050
Chris Lattner67ca9252007-05-21 01:08:44 +00003051 // If we still couldn't decide a type, we probably have something that
3052 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003053 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00003054 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003055 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00003056 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00003057 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003058
Chris Lattner55258cf2008-05-09 05:59:00 +00003059 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00003060 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00003061 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003062 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00003063 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003064
Chris Lattner1c20a172007-08-26 03:42:43 +00003065 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3066 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00003067 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00003068 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00003069
3070 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00003071}
3072
John McCalldadc5752010-08-24 06:29:42 +00003073ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00003074 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003075 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00003076 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00003077}
3078
Chandler Carruth62da79c2011-05-26 08:53:12 +00003079static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3080 SourceLocation Loc,
3081 SourceRange ArgRange) {
3082 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3083 // scalar or vector data type argument..."
3084 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3085 // type (C99 6.2.5p18) or void.
3086 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3087 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3088 << T << ArgRange;
3089 return true;
3090 }
3091
3092 assert((T->isVoidType() || !T->isIncompleteType()) &&
3093 "Scalar types should always be complete");
3094 return false;
3095}
3096
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003097static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3098 SourceLocation Loc,
3099 SourceRange ArgRange,
3100 UnaryExprOrTypeTrait TraitKind) {
3101 // C99 6.5.3.4p1:
3102 if (T->isFunctionType()) {
3103 // alignof(function) is allowed as an extension.
3104 if (TraitKind == UETT_SizeOf)
3105 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
3106 return false;
3107 }
3108
3109 // Allow sizeof(void)/alignof(void) as an extension.
3110 if (T->isVoidType()) {
3111 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
3112 return false;
3113 }
3114
3115 return true;
3116}
3117
3118static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3119 SourceLocation Loc,
3120 SourceRange ArgRange,
3121 UnaryExprOrTypeTrait TraitKind) {
3122 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
3123 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
3124 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3125 << T << (TraitKind == UETT_SizeOf)
3126 << ArgRange;
3127 return true;
3128 }
3129
3130 return false;
3131}
3132
Chandler Carruth14502c22011-05-26 08:53:10 +00003133/// \brief Check the constrains on expression operands to unary type expression
3134/// and type traits.
3135///
Chandler Carruth7c430c02011-05-27 01:33:31 +00003136/// Completes any types necessary and validates the constraints on the operand
3137/// expression. The logic mostly mirrors the type-based overload, but may modify
3138/// the expression as it completes the type for that expression through template
3139/// instantiation, etc.
Chandler Carruth14502c22011-05-26 08:53:10 +00003140bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op,
3141 UnaryExprOrTypeTrait ExprKind) {
Chandler Carruth7c430c02011-05-27 01:33:31 +00003142 QualType ExprTy = Op->getType();
3143
3144 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3145 // the result is the size of the referenced type."
3146 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3147 // result shall be the alignment of the referenced type."
3148 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3149 ExprTy = Ref->getPointeeType();
3150
3151 if (ExprKind == UETT_VecStep)
3152 return CheckVecStepTraitOperandType(*this, ExprTy, Op->getExprLoc(),
3153 Op->getSourceRange());
3154
3155 // Whitelist some types as extensions
3156 if (!CheckExtensionTraitOperandType(*this, ExprTy, Op->getExprLoc(),
3157 Op->getSourceRange(), ExprKind))
3158 return false;
3159
3160 if (RequireCompleteExprType(Op,
3161 PDiag(diag::err_sizeof_alignof_incomplete_type)
3162 << ExprKind << Op->getSourceRange(),
3163 std::make_pair(SourceLocation(), PDiag(0))))
3164 return true;
3165
3166 // Completeing the expression's type may have changed it.
3167 ExprTy = Op->getType();
3168 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3169 ExprTy = Ref->getPointeeType();
3170
3171 if (CheckObjCTraitOperandConstraints(*this, ExprTy, Op->getExprLoc(),
3172 Op->getSourceRange(), ExprKind))
3173 return true;
3174
Nico Weber0870deb2011-06-15 02:47:03 +00003175 if (ExprKind == UETT_SizeOf) {
3176 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Op->IgnoreParens())) {
3177 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3178 QualType OType = PVD->getOriginalType();
3179 QualType Type = PVD->getType();
3180 if (Type->isPointerType() && OType->isArrayType()) {
3181 Diag(Op->getExprLoc(), diag::warn_sizeof_array_param)
3182 << Type << OType;
3183 Diag(PVD->getLocation(), diag::note_declared_at);
3184 }
3185 }
3186 }
3187 }
3188
Chandler Carruth7c430c02011-05-27 01:33:31 +00003189 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00003190}
3191
3192/// \brief Check the constraints on operands to unary expression and type
3193/// traits.
3194///
3195/// This will complete any types necessary, and validate the various constraints
3196/// on those operands.
3197///
Steve Naroff71b59a92007-06-04 22:22:31 +00003198/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00003199/// C99 6.3.2.1p[2-4] all state:
3200/// Except when it is the operand of the sizeof operator ...
3201///
3202/// C++ [expr.sizeof]p4
3203/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3204/// standard conversions are not applied to the operand of sizeof.
3205///
3206/// This policy is followed for all of the unary trait expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003207bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
3208 SourceLocation OpLoc,
3209 SourceRange ExprRange,
3210 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003211 if (exprType->isDependentType())
3212 return false;
3213
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003214 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3215 // the result is the size of the referenced type."
3216 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3217 // result shall be the alignment of the referenced type."
3218 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
3219 exprType = Ref->getPointeeType();
3220
Chandler Carruth62da79c2011-05-26 08:53:12 +00003221 if (ExprKind == UETT_VecStep)
3222 return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003223
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003224 // Whitelist some types as extensions
3225 if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange,
3226 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00003227 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003228
Chris Lattner62975a72009-04-24 00:30:45 +00003229 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00003230 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00003231 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00003232 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003233
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003234 if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange,
3235 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00003236 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003237
Chris Lattner62975a72009-04-24 00:30:45 +00003238 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00003239}
3240
Chandler Carruth14502c22011-05-26 08:53:10 +00003241static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00003242 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003243
Mike Stump11289f42009-09-09 15:08:12 +00003244 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00003245 if (isa<DeclRefExpr>(E))
3246 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003247
3248 // Cannot know anything else if the expression is dependent.
3249 if (E->isTypeDependent())
3250 return false;
3251
Douglas Gregor71235ec2009-05-02 02:18:30 +00003252 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003253 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3254 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003255 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00003256 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00003257
3258 // Alignment of a field access is always okay, so long as it isn't a
3259 // bit-field.
3260 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00003261 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003262 return false;
3263
Chandler Carruth14502c22011-05-26 08:53:10 +00003264 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003265}
3266
Chandler Carruth14502c22011-05-26 08:53:10 +00003267bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00003268 E = E->IgnoreParens();
3269
3270 // Cannot know anything else if the expression is dependent.
3271 if (E->isTypeDependent())
3272 return false;
3273
Chandler Carruth14502c22011-05-26 08:53:10 +00003274 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00003275}
3276
Douglas Gregor0950e412009-03-13 21:01:28 +00003277/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00003278ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003279Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3280 SourceLocation OpLoc,
3281 UnaryExprOrTypeTrait ExprKind,
3282 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00003283 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00003284 return ExprError();
3285
John McCallbcd03502009-12-07 02:54:59 +00003286 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00003287
Douglas Gregor0950e412009-03-13 21:01:28 +00003288 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00003289 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00003290 return ExprError();
3291
3292 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003293 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3294 Context.getSizeType(),
3295 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003296}
3297
3298/// \brief Build a sizeof or alignof expression given an expression
3299/// operand.
John McCalldadc5752010-08-24 06:29:42 +00003300ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00003301Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3302 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor0950e412009-03-13 21:01:28 +00003303 // Verify that the operand is valid.
3304 bool isInvalid = false;
3305 if (E->isTypeDependent()) {
3306 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003307 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003308 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003309 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003310 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00003311 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00003312 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00003313 isInvalid = true;
John McCall36226622010-10-12 02:09:17 +00003314 } else if (E->getType()->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00003315 ExprResult PE = CheckPlaceholderExpr(E);
John McCall36226622010-10-12 02:09:17 +00003316 if (PE.isInvalid()) return ExprError();
Chandler Carrutha923fb22011-05-29 07:32:14 +00003317 return CreateUnaryExprOrTypeTraitExpr(PE.take(), OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00003318 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00003319 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00003320 }
3321
3322 if (isInvalid)
3323 return ExprError();
3324
3325 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00003326 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00003327 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00003328 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003329}
3330
Peter Collingbournee190dee2011-03-11 19:24:49 +00003331/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3332/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00003333/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00003334ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003335Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3336 UnaryExprOrTypeTrait ExprKind, bool isType,
3337 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00003338 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003339 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00003340
Sebastian Redl6f282892008-11-11 17:56:53 +00003341 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00003342 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00003343 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003344 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00003345 }
Sebastian Redl6f282892008-11-11 17:56:53 +00003346
Douglas Gregor0950e412009-03-13 21:01:28 +00003347 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00003348 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00003349 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00003350}
3351
John Wiegley01296292011-04-08 18:41:53 +00003352static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall4bc41ae2010-11-18 19:01:18 +00003353 bool isReal) {
John Wiegley01296292011-04-08 18:41:53 +00003354 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00003355 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00003356
John McCall34376a62010-12-04 03:47:34 +00003357 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00003358 if (V.get()->getObjectKind() != OK_Ordinary) {
3359 V = S.DefaultLvalueConversion(V.take());
3360 if (V.isInvalid())
3361 return QualType();
3362 }
John McCall34376a62010-12-04 03:47:34 +00003363
Chris Lattnere267f5d2007-08-26 05:39:26 +00003364 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00003365 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00003366 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00003367
Chris Lattnere267f5d2007-08-26 05:39:26 +00003368 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00003369 if (V.get()->getType()->isArithmeticType())
3370 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003371
John McCall36226622010-10-12 02:09:17 +00003372 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00003373 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00003374 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003375 if (PR.get() != V.get()) {
3376 V = move(PR);
John McCall4bc41ae2010-11-18 19:01:18 +00003377 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00003378 }
3379
Chris Lattnere267f5d2007-08-26 05:39:26 +00003380 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003381 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00003382 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003383 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003384}
3385
3386
Chris Lattnere168f762006-11-10 05:29:30 +00003387
John McCalldadc5752010-08-24 06:29:42 +00003388ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003389Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003390 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003391 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003392 switch (Kind) {
3393 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003394 case tok::plusplus: Opc = UO_PostInc; break;
3395 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003396 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003397
John McCallb268a282010-08-23 23:25:46 +00003398 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003399}
3400
John McCall4bc41ae2010-11-18 19:01:18 +00003401/// Expressions of certain arbitrary types are forbidden by C from
3402/// having l-value type. These are:
3403/// - 'void', but not qualified void
3404/// - function types
3405///
3406/// The exact rule here is C99 6.3.2.1:
3407/// An lvalue is an expression with an object type or an incomplete
3408/// type other than void.
3409static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
3410 return ((T->isVoidType() && !T.hasQualifiers()) ||
3411 T->isFunctionType());
3412}
3413
John McCalldadc5752010-08-24 06:29:42 +00003414ExprResult
John McCallb268a282010-08-23 23:25:46 +00003415Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3416 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003417 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003418 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003419 if (Result.isInvalid()) return ExprError();
3420 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003421
John McCallb268a282010-08-23 23:25:46 +00003422 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003423
Douglas Gregor40412ac2008-11-19 17:17:41 +00003424 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003425 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003426 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003427 Context.DependentTy,
3428 VK_LValue, OK_Ordinary,
3429 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003430 }
3431
Mike Stump11289f42009-09-09 15:08:12 +00003432 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003433 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003434 LHSExp->getType()->isEnumeralType() ||
3435 RHSExp->getType()->isRecordType() ||
3436 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00003437 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003438 }
3439
John McCallb268a282010-08-23 23:25:46 +00003440 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003441}
3442
3443
John McCalldadc5752010-08-24 06:29:42 +00003444ExprResult
John McCallb268a282010-08-23 23:25:46 +00003445Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3446 Expr *Idx, SourceLocation RLoc) {
3447 Expr *LHSExp = Base;
3448 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003449
Chris Lattner36d572b2007-07-16 00:14:47 +00003450 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003451 if (!LHSExp->getType()->getAs<VectorType>()) {
3452 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3453 if (Result.isInvalid())
3454 return ExprError();
3455 LHSExp = Result.take();
3456 }
3457 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3458 if (Result.isInvalid())
3459 return ExprError();
3460 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003461
Chris Lattner36d572b2007-07-16 00:14:47 +00003462 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003463 ExprValueKind VK = VK_LValue;
3464 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003465
Steve Naroffc1aadb12007-03-28 21:49:40 +00003466 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003467 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003468 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003469 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003470 Expr *BaseExpr, *IndexExpr;
3471 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003472 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3473 BaseExpr = LHSExp;
3474 IndexExpr = RHSExp;
3475 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003476 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003477 BaseExpr = LHSExp;
3478 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003479 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003480 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003481 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003482 BaseExpr = RHSExp;
3483 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003484 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003485 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003486 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003487 BaseExpr = LHSExp;
3488 IndexExpr = RHSExp;
3489 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003490 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003491 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003492 // Handle the uncommon case of "123[Ptr]".
3493 BaseExpr = RHSExp;
3494 IndexExpr = LHSExp;
3495 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003496 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003497 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003498 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003499 VK = LHSExp->getValueKind();
3500 if (VK != VK_RValue)
3501 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003502
Chris Lattner36d572b2007-07-16 00:14:47 +00003503 // FIXME: need to deal with const...
3504 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003505 } else if (LHSTy->isArrayType()) {
3506 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003507 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003508 // wasn't promoted because of the C90 rule that doesn't
3509 // allow promoting non-lvalue arrays. Warn, then
3510 // force the promotion here.
3511 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3512 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003513 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3514 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003515 LHSTy = LHSExp->getType();
3516
3517 BaseExpr = LHSExp;
3518 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003519 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003520 } else if (RHSTy->isArrayType()) {
3521 // Same as previous, except for 123[f().a] case
3522 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3523 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003524 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3525 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003526 RHSTy = RHSExp->getType();
3527
3528 BaseExpr = RHSExp;
3529 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003530 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003531 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003532 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3533 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003534 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003535 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003536 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003537 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3538 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003539
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003540 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003541 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3542 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003543 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3544
Douglas Gregorac1fb652009-03-24 19:52:54 +00003545 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003546 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3547 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003548 // incomplete types are not object types.
3549 if (ResultType->isFunctionType()) {
3550 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3551 << ResultType << BaseExpr->getSourceRange();
3552 return ExprError();
3553 }
Mike Stump11289f42009-09-09 15:08:12 +00003554
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003555 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3556 // GNU extension: subscripting on pointer to void
3557 Diag(LLoc, diag::ext_gnu_void_ptr)
3558 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003559
3560 // C forbids expressions of unqualified void type from being l-values.
3561 // See IsCForbiddenLValueType.
3562 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003563 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003564 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003565 PDiag(diag::err_subscript_incomplete_type)
3566 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003567 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003568
Chris Lattner62975a72009-04-24 00:30:45 +00003569 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003570 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003571 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3572 << ResultType << BaseExpr->getSourceRange();
3573 return ExprError();
3574 }
Mike Stump11289f42009-09-09 15:08:12 +00003575
John McCall4bc41ae2010-11-18 19:01:18 +00003576 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3577 !IsCForbiddenLValueType(Context, ResultType));
3578
Mike Stump4e1f26a2009-02-19 03:04:26 +00003579 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003580 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003581}
3582
John McCall4bc41ae2010-11-18 19:01:18 +00003583/// Check an ext-vector component access expression.
3584///
3585/// VK should be set in advance to the value kind of the base
3586/// expression.
3587static QualType
3588CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3589 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00003590 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00003591 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3592 // see FIXME there.
3593 //
3594 // FIXME: This logic can be greatly simplified by splitting it along
3595 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00003596 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00003597
Steve Narofff8fd09e2007-07-27 22:15:19 +00003598 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003599 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003600
Mike Stump4e1f26a2009-02-19 03:04:26 +00003601 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00003602 // special names that indicate a subset of exactly half the elements are
3603 // to be selected.
3604 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003605
Nate Begemanbb70bf62009-01-18 01:47:54 +00003606 // This flag determines whether or not CompName has an 's' char prefix,
3607 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00003608 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00003609
John McCall4bc41ae2010-11-18 19:01:18 +00003610 bool HasRepeated = false;
3611 bool HasIndex[16] = {};
3612
3613 int Idx;
3614
Nate Begemanf322eab2008-05-09 06:41:27 +00003615 // Check that we've found one of the special components, or that the component
3616 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003617 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00003618 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3619 HalvingSwizzle = true;
John McCall4bc41ae2010-11-18 19:01:18 +00003620 } else if (!HexSwizzle &&
3621 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3622 do {
3623 if (HasIndex[Idx]) HasRepeated = true;
3624 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003625 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003626 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3627 } else {
3628 if (HexSwizzle) compStr++;
3629 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3630 if (HasIndex[Idx]) HasRepeated = true;
3631 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003632 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003633 }
Chris Lattner7e152db2007-08-02 22:33:49 +00003634 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00003635
Mike Stump4e1f26a2009-02-19 03:04:26 +00003636 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00003637 // We didn't get to the end of the string. This means the component names
3638 // didn't come from the same set *or* we encountered an illegal name.
John McCall4bc41ae2010-11-18 19:01:18 +00003639 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramere8394df2010-08-11 14:47:12 +00003640 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00003641 return QualType();
3642 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003643
Nate Begemanbb70bf62009-01-18 01:47:54 +00003644 // Ensure no component accessor exceeds the width of the vector type it
3645 // operates on.
3646 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003647 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003648
3649 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00003650 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00003651
3652 while (*compStr) {
3653 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall4bc41ae2010-11-18 19:01:18 +00003654 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begemanbb70bf62009-01-18 01:47:54 +00003655 << baseType << SourceRange(CompLoc);
3656 return QualType();
3657 }
3658 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00003659 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003660
Steve Narofff8fd09e2007-07-27 22:15:19 +00003661 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003662 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00003663 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00003664 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00003665 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00003666 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00003667 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003668 if (HexSwizzle)
3669 CompSize--;
3670
Steve Narofff8fd09e2007-07-27 22:15:19 +00003671 if (CompSize == 1)
3672 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003673
John McCall4bc41ae2010-11-18 19:01:18 +00003674 if (HasRepeated) VK = VK_RValue;
3675
3676 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003677 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00003678 // diagostics look bad. We want extended vector types to appear built-in.
John McCall4bc41ae2010-11-18 19:01:18 +00003679 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3680 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3681 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00003682 }
3683 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00003684}
3685
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003686static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00003687 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003688 const Selector &Sel,
3689 ASTContext &Context) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003690 if (Member)
3691 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3692 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003693 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003694 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00003695
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003696 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3697 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003698 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3699 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003700 return D;
3701 }
3702 return 0;
3703}
3704
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003705static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3706 IdentifierInfo *Member,
3707 const Selector &Sel,
3708 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003709 // Check protocols on qualified interfaces.
3710 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00003711 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003712 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003713 if (Member)
3714 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3715 GDecl = PD;
3716 break;
3717 }
3718 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003719 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003720 GDecl = OMD;
3721 break;
3722 }
3723 }
3724 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00003725 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003726 E = QIdTy->qual_end(); I != E; ++I) {
3727 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003728 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3729 Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003730 if (GDecl)
3731 return GDecl;
3732 }
3733 }
3734 return GDecl;
3735}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00003736
John McCalldadc5752010-08-24 06:29:42 +00003737ExprResult
John McCallb268a282010-08-23 23:25:46 +00003738Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCall2d74de92009-12-01 22:10:20 +00003739 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003740 const CXXScopeSpec &SS,
3741 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003742 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003743 const TemplateArgumentListInfo *TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00003744 // Even in dependent contexts, try to diagnose base expressions with
3745 // obviously wrong types, e.g.:
3746 //
3747 // T* t;
3748 // t.f;
3749 //
3750 // In Obj-C++, however, the above expression is valid, since it could be
3751 // accessing the 'f' property if T is an Obj-C interface. The extra check
3752 // allows this, while still reporting an error if T is a struct pointer.
3753 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00003754 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00003755 if (PT && (!getLangOptions().ObjC1 ||
3756 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00003757 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003758 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00003759 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00003760 return ExprError();
3761 }
3762 }
3763
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003764 assert(BaseType->isDependentType() ||
3765 NameInfo.getName().isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00003766 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00003767
3768 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3769 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00003770 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003771 IsArrow, OpLoc,
Douglas Gregore16af532011-02-28 18:50:33 +00003772 SS.getWithLocInContext(Context),
John McCall10eae182009-11-30 22:42:35 +00003773 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003774 NameInfo, TemplateArgs));
John McCall10eae182009-11-30 22:42:35 +00003775}
3776
3777/// We know that the given qualified member reference points only to
3778/// declarations which do not belong to the static type of the base
3779/// expression. Diagnose the problem.
3780static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3781 Expr *BaseExpr,
3782 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003783 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00003784 NamedDecl *rep,
3785 const DeclarationNameInfo &nameInfo) {
John McCallcd4b4772009-12-02 03:53:29 +00003786 // If this is an implicit member access, use a different set of
3787 // diagnostics.
3788 if (!BaseExpr)
John McCallf3a88602011-02-03 08:15:49 +00003789 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall10eae182009-11-30 22:42:35 +00003790
John McCallf3a88602011-02-03 08:15:49 +00003791 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3792 << SS.getRange() << rep << BaseType;
John McCall10eae182009-11-30 22:42:35 +00003793}
3794
3795// Check whether the declarations we found through a nested-name
3796// specifier in a member expression are actually members of the base
3797// type. The restriction here is:
3798//
3799// C++ [expr.ref]p2:
3800// ... In these cases, the id-expression shall name a
3801// member of the class or of one of its base classes.
3802//
3803// So it's perfectly legitimate for the nested-name specifier to name
3804// an unrelated class, and for us to find an overload set including
3805// decls from classes which are not superclasses, as long as the decl
3806// we actually pick through overload resolution is from a superclass.
3807bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3808 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003809 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003810 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00003811 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3812 if (!BaseRT) {
3813 // We can't check this yet because the base type is still
3814 // dependent.
3815 assert(BaseType->isDependentType());
3816 return false;
3817 }
3818 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00003819
3820 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00003821 // If this is an implicit member reference and we find a
3822 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00003823 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00003824 return false;
John McCall10eae182009-11-30 22:42:35 +00003825
John McCall2d74de92009-12-01 22:10:20 +00003826 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman75300492010-07-27 20:51:02 +00003827 DeclContext *DC = (*I)->getDeclContext();
3828 while (DC->isTransparentContext())
3829 DC = DC->getParent();
John McCall2d74de92009-12-01 22:10:20 +00003830
Douglas Gregora9c3e822010-07-28 22:27:52 +00003831 if (!DC->isRecord())
3832 continue;
3833
John McCall2d74de92009-12-01 22:10:20 +00003834 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman75300492010-07-27 20:51:02 +00003835 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCall2d74de92009-12-01 22:10:20 +00003836
3837 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3838 return false;
3839 }
3840
John McCallf3a88602011-02-03 08:15:49 +00003841 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3842 R.getRepresentativeDecl(),
3843 R.getLookupNameInfo());
John McCall2d74de92009-12-01 22:10:20 +00003844 return true;
3845}
3846
3847static bool
3848LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3849 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00003850 SourceLocation OpLoc, CXXScopeSpec &SS,
3851 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00003852 RecordDecl *RDecl = RTy->getDecl();
3853 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00003854 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00003855 << BaseRange))
3856 return true;
3857
John McCalle9cccd82010-06-16 08:42:20 +00003858 if (HasTemplateArgs) {
3859 // LookupTemplateName doesn't expect these both to exist simultaneously.
3860 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3861
3862 bool MOUS;
3863 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3864 return false;
3865 }
3866
John McCall2d74de92009-12-01 22:10:20 +00003867 DeclContext *DC = RDecl;
3868 if (SS.isSet()) {
3869 // If the member name was a qualified-id, look into the
3870 // nested-name-specifier.
3871 DC = SemaRef.computeDeclContext(SS, false);
3872
John McCall0b66eb32010-05-01 00:40:08 +00003873 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00003874 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3875 << SS.getRange() << DC;
3876 return true;
3877 }
3878
John McCall2d74de92009-12-01 22:10:20 +00003879 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003880
John McCall2d74de92009-12-01 22:10:20 +00003881 if (!isa<TypeDecl>(DC)) {
3882 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3883 << DC << SS.getRange();
3884 return true;
John McCall10eae182009-11-30 22:42:35 +00003885 }
3886 }
3887
John McCall2d74de92009-12-01 22:10:20 +00003888 // The record definition is complete, now look up the member.
3889 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00003890
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003891 if (!R.empty())
3892 return false;
3893
3894 // We didn't find anything with the given name, so try to correct
3895 // for typos.
3896 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00003897 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003898 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003899 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3900 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3901 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003902 << FixItHint::CreateReplacement(R.getNameLoc(),
3903 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003904 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3905 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3906 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003907 return false;
3908 } else {
3909 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003910 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003911 }
3912
John McCall10eae182009-11-30 22:42:35 +00003913 return false;
3914}
3915
John McCalldadc5752010-08-24 06:29:42 +00003916ExprResult
John McCallb268a282010-08-23 23:25:46 +00003917Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00003918 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003919 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003920 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003921 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003922 const TemplateArgumentListInfo *TemplateArgs) {
John McCallcd4b4772009-12-02 03:53:29 +00003923 if (BaseType->isDependentType() ||
3924 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallb268a282010-08-23 23:25:46 +00003925 return ActOnDependentMemberExpr(Base, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003926 IsArrow, OpLoc,
3927 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003928 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003929
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003930 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00003931
John McCall2d74de92009-12-01 22:10:20 +00003932 // Implicit member accesses.
3933 if (!Base) {
3934 QualType RecordTy = BaseType;
3935 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3936 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3937 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00003938 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00003939 return ExprError();
3940
3941 // Explicit member accesses.
3942 } else {
John Wiegley01296292011-04-08 18:41:53 +00003943 ExprResult BaseResult = Owned(Base);
John McCalldadc5752010-08-24 06:29:42 +00003944 ExprResult Result =
John Wiegley01296292011-04-08 18:41:53 +00003945 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCall48871652010-08-21 09:40:31 +00003946 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00003947
John Wiegley01296292011-04-08 18:41:53 +00003948 if (BaseResult.isInvalid())
3949 return ExprError();
3950 Base = BaseResult.take();
3951
John McCall2d74de92009-12-01 22:10:20 +00003952 if (Result.isInvalid()) {
3953 Owned(Base);
3954 return ExprError();
3955 }
3956
3957 if (Result.get())
3958 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00003959
3960 // LookupMemberExpr can modify Base, and thus change BaseType
3961 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00003962 }
3963
John McCallb268a282010-08-23 23:25:46 +00003964 return BuildMemberReferenceExpr(Base, BaseType,
John McCall38836f02010-01-15 08:34:02 +00003965 OpLoc, IsArrow, SS, FirstQualifierInScope,
3966 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003967}
3968
John McCalldadc5752010-08-24 06:29:42 +00003969ExprResult
John McCallb268a282010-08-23 23:25:46 +00003970Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCall2d74de92009-12-01 22:10:20 +00003971 SourceLocation OpLoc, bool IsArrow,
3972 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00003973 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00003974 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00003975 const TemplateArgumentListInfo *TemplateArgs,
3976 bool SuppressQualifierCheck) {
John McCall2d74de92009-12-01 22:10:20 +00003977 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00003978 if (IsArrow) {
3979 assert(BaseType->isPointerType());
3980 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3981 }
John McCalla8ae2222010-04-06 21:38:20 +00003982 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00003983
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003984 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3985 DeclarationName MemberName = MemberNameInfo.getName();
3986 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall10eae182009-11-30 22:42:35 +00003987
3988 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00003989 return ExprError();
3990
John McCall10eae182009-11-30 22:42:35 +00003991 if (R.empty()) {
3992 // Rederive where we looked up.
3993 DeclContext *DC = (SS.isSet()
3994 ? computeDeclContext(SS, false)
3995 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00003996
John McCall10eae182009-11-30 22:42:35 +00003997 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00003998 << MemberName << DC
3999 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00004000 return ExprError();
4001 }
4002
John McCall38836f02010-01-15 08:34:02 +00004003 // Diagnose lookups that find only declarations from a non-base
4004 // type. This is possible for either qualified lookups (which may
4005 // have been qualified with an unrelated type) or implicit member
4006 // expressions (which were found with unqualified lookup and thus
4007 // may have come from an enclosing scope). Note that it's okay for
4008 // lookup to find declarations from a non-base type as long as those
4009 // aren't the ones picked by overload resolution.
4010 if ((SS.isSet() || !BaseExpr ||
4011 (isa<CXXThisExpr>(BaseExpr) &&
4012 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00004013 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00004014 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00004015 return ExprError();
4016
4017 // Construct an unresolved result if we in fact got an unresolved
4018 // result.
4019 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall58cc69d2010-01-27 01:50:18 +00004020 // Suppress any lookup-related diagnostics; we'll do these when we
4021 // pick a member.
4022 R.suppressDiagnostics();
4023
John McCall10eae182009-11-30 22:42:35 +00004024 UnresolvedMemberExpr *MemExpr
Douglas Gregora6e053e2010-12-15 01:34:56 +00004025 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00004026 BaseExpr, BaseExprType,
4027 IsArrow, OpLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00004028 SS.getWithLocInContext(Context),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004029 MemberNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00004030 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00004031
4032 return Owned(MemExpr);
4033 }
4034
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004035 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00004036 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00004037 NamedDecl *MemberDecl = R.getFoundDecl();
4038
4039 // FIXME: diagnose the presence of template arguments now.
4040
4041 // If the decl being referenced had an error, return an error for this
4042 // sub-expr without emitting another error, in order to avoid cascading
4043 // error cases.
4044 if (MemberDecl->isInvalidDecl())
4045 return ExprError();
4046
John McCall2d74de92009-12-01 22:10:20 +00004047 // Handle the implicit-member-access case.
4048 if (!BaseExpr) {
4049 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00004050 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004051 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCall2d74de92009-12-01 22:10:20 +00004052
Douglas Gregorb15af892010-01-07 23:12:05 +00004053 SourceLocation Loc = R.getNameLoc();
4054 if (SS.getRange().isValid())
4055 Loc = SS.getRange().getBegin();
4056 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00004057 }
4058
John McCall10eae182009-11-30 22:42:35 +00004059 bool ShouldCheckUse = true;
4060 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
4061 // Don't diagnose the use of a virtual member function unless it's
4062 // explicitly qualified.
4063 if (MD->isVirtual() && !SS.isSet())
4064 ShouldCheckUse = false;
4065 }
4066
4067 // Check the use of this member.
4068 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
4069 Owned(BaseExpr);
4070 return ExprError();
4071 }
4072
John McCall34376a62010-12-04 03:47:34 +00004073 // Perform a property load on the base regardless of whether we
4074 // actually need it for the declaration.
John Wiegley01296292011-04-08 18:41:53 +00004075 if (BaseExpr->getObjectKind() == OK_ObjCProperty) {
4076 ExprResult Result = ConvertPropertyForRValue(BaseExpr);
4077 if (Result.isInvalid())
4078 return ExprError();
4079 BaseExpr = Result.take();
4080 }
John McCall34376a62010-12-04 03:47:34 +00004081
John McCallfeb624a2010-11-23 20:48:44 +00004082 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
4083 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
4084 SS, FD, FoundDecl, MemberNameInfo);
John McCall10eae182009-11-30 22:42:35 +00004085
Francois Pichet783dd6e2010-11-21 06:08:52 +00004086 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
4087 // We may have found a field within an anonymous union or struct
4088 // (C++ [class.union]).
John McCallf3a88602011-02-03 08:15:49 +00004089 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCall34376a62010-12-04 03:47:34 +00004090 BaseExpr, OpLoc);
Francois Pichet783dd6e2010-11-21 06:08:52 +00004091
John McCall10eae182009-11-30 22:42:35 +00004092 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
4093 MarkDeclarationReferenced(MemberLoc, Var);
4094 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004095 Var, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00004096 Var->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00004097 VK_LValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00004098 }
4099
John McCall7decc9e2010-11-18 06:31:45 +00004100 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall0009fcc2011-04-26 20:42:42 +00004101 ExprValueKind valueKind;
4102 QualType type;
4103 if (MemberFn->isInstance()) {
4104 valueKind = VK_RValue;
4105 type = Context.BoundMemberTy;
4106 } else {
4107 valueKind = VK_LValue;
4108 type = MemberFn->getType();
4109 }
4110
John McCall10eae182009-11-30 22:42:35 +00004111 MarkDeclarationReferenced(MemberLoc, MemberDecl);
4112 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004113 MemberFn, FoundDecl, MemberNameInfo,
John McCall0009fcc2011-04-26 20:42:42 +00004114 type, valueKind, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00004115 }
John McCall7decc9e2010-11-18 06:31:45 +00004116 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall10eae182009-11-30 22:42:35 +00004117
4118 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
4119 MarkDeclarationReferenced(MemberLoc, MemberDecl);
4120 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004121 Enum, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00004122 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00004123 }
4124
4125 Owned(BaseExpr);
4126
Douglas Gregor861eb802010-04-25 20:55:08 +00004127 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00004128 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004129 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregor861eb802010-04-25 20:55:08 +00004130 << MemberName << BaseType << int(IsArrow);
4131 else
4132 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
4133 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00004134
Douglas Gregor861eb802010-04-25 20:55:08 +00004135 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
4136 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00004137 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00004138 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00004139}
4140
John McCall68fc88ec2010-12-15 16:46:44 +00004141/// Given that normal member access failed on the given expression,
4142/// and given that the expression's type involves builtin-id or
4143/// builtin-Class, decide whether substituting in the redefinition
4144/// types would be profitable. The redefinition type is whatever
4145/// this translation unit tried to typedef to id/Class; we store
4146/// it to the side and then re-use it in places like this.
John Wiegley01296292011-04-08 18:41:53 +00004147static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
John McCall68fc88ec2010-12-15 16:46:44 +00004148 const ObjCObjectPointerType *opty
John Wiegley01296292011-04-08 18:41:53 +00004149 = base.get()->getType()->getAs<ObjCObjectPointerType>();
John McCall68fc88ec2010-12-15 16:46:44 +00004150 if (!opty) return false;
4151
4152 const ObjCObjectType *ty = opty->getObjectType();
4153
4154 QualType redef;
4155 if (ty->isObjCId()) {
4156 redef = S.Context.ObjCIdRedefinitionType;
4157 } else if (ty->isObjCClass()) {
4158 redef = S.Context.ObjCClassRedefinitionType;
4159 } else {
4160 return false;
4161 }
4162
4163 // Do the substitution as long as the redefinition type isn't just a
4164 // possibly-qualified pointer to builtin-id or builtin-Class again.
4165 opty = redef->getAs<ObjCObjectPointerType>();
4166 if (opty && !opty->getObjectType()->getInterface() != 0)
4167 return false;
4168
John Wiegley01296292011-04-08 18:41:53 +00004169 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
John McCall68fc88ec2010-12-15 16:46:44 +00004170 return true;
4171}
4172
John McCall10eae182009-11-30 22:42:35 +00004173/// Look up the given member of the given non-type-dependent
4174/// expression. This can return in one of two ways:
4175/// * If it returns a sentinel null-but-valid result, the caller will
4176/// assume that lookup was performed and the results written into
4177/// the provided structure. It will take over from there.
4178/// * Otherwise, the returned expression will be produced in place of
4179/// an ordinary member expression.
4180///
4181/// The ObjCImpDecl bit is a gross hack that will need to be properly
4182/// fixed for ObjC++.
John McCalldadc5752010-08-24 06:29:42 +00004183ExprResult
John Wiegley01296292011-04-08 18:41:53 +00004184Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00004185 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004186 CXXScopeSpec &SS,
John McCall48871652010-08-21 09:40:31 +00004187 Decl *ObjCImpDecl, bool HasTemplateArgs) {
John Wiegley01296292011-04-08 18:41:53 +00004188 assert(BaseExpr.get() && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00004189
Steve Naroffeaaae462007-12-16 21:42:28 +00004190 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00004191 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004192
John Wiegley01296292011-04-08 18:41:53 +00004193 if (IsArrow) {
4194 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4195 if (BaseExpr.isInvalid())
4196 return ExprError();
4197 }
4198
4199 QualType BaseType = BaseExpr.get()->getType();
John McCall10eae182009-11-30 22:42:35 +00004200 assert(!BaseType->isDependentType());
4201
4202 DeclarationName MemberName = R.getLookupName();
4203 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00004204
John McCall68fc88ec2010-12-15 16:46:44 +00004205 // For later type-checking purposes, turn arrow accesses into dot
4206 // accesses. The only access type we support that doesn't follow
4207 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
4208 // and those never use arrows, so this is unaffected.
4209 if (IsArrow) {
4210 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4211 BaseType = Ptr->getPointeeType();
4212 else if (const ObjCObjectPointerType *Ptr
4213 = BaseType->getAs<ObjCObjectPointerType>())
4214 BaseType = Ptr->getPointeeType();
4215 else if (BaseType->isRecordType()) {
4216 // Recover from arrow accesses to records, e.g.:
4217 // struct MyRecord foo;
4218 // foo->bar
4219 // This is actually well-formed in C++ if MyRecord has an
4220 // overloaded operator->, but that should have been dealt with
4221 // by now.
4222 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley01296292011-04-08 18:41:53 +00004223 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
John McCall68fc88ec2010-12-15 16:46:44 +00004224 << FixItHint::CreateReplacement(OpLoc, ".");
4225 IsArrow = false;
John McCall0009fcc2011-04-26 20:42:42 +00004226 } else if (BaseType == Context.BoundMemberTy) {
4227 goto fail;
John McCall68fc88ec2010-12-15 16:46:44 +00004228 } else {
4229 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
John Wiegley01296292011-04-08 18:41:53 +00004230 << BaseType << BaseExpr.get()->getSourceRange();
John McCall68fc88ec2010-12-15 16:46:44 +00004231 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00004232 }
4233 }
4234
John McCall68fc88ec2010-12-15 16:46:44 +00004235 // Handle field access to simple records.
4236 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John Wiegley01296292011-04-08 18:41:53 +00004237 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
John McCall68fc88ec2010-12-15 16:46:44 +00004238 RTy, OpLoc, SS, HasTemplateArgs))
4239 return ExprError();
4240
4241 // Returning valid-but-null is how we indicate to the caller that
4242 // the lookup result was filled in.
4243 return Owned((Expr*) 0);
David Chisnall9f57c292009-08-17 16:35:33 +00004244 }
John McCall10eae182009-11-30 22:42:35 +00004245
John McCall68fc88ec2010-12-15 16:46:44 +00004246 // Handle ivar access to Objective-C objects.
4247 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004248 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall68fc88ec2010-12-15 16:46:44 +00004249
4250 // There are three cases for the base type:
4251 // - builtin id (qualified or unqualified)
4252 // - builtin Class (qualified or unqualified)
4253 // - an interface
4254 ObjCInterfaceDecl *IDecl = OTy->getInterface();
4255 if (!IDecl) {
John McCall31168b02011-06-15 23:02:42 +00004256 if (getLangOptions().ObjCAutoRefCount &&
4257 (OTy->isObjCId() || OTy->isObjCClass()))
4258 goto fail;
John McCall68fc88ec2010-12-15 16:46:44 +00004259 // There's an implicit 'isa' ivar on all objects.
4260 // But we only actually find it this way on objects of type 'id',
4261 // apparently.
4262 if (OTy->isObjCId() && Member->isStr("isa"))
John Wiegley01296292011-04-08 18:41:53 +00004263 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
John McCall68fc88ec2010-12-15 16:46:44 +00004264 Context.getObjCClassType()));
4265
4266 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4267 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4268 ObjCImpDecl, HasTemplateArgs);
4269 goto fail;
4270 }
4271
4272 ObjCInterfaceDecl *ClassDeclared;
4273 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
4274
4275 if (!IV) {
4276 // Attempt to correct for typos in ivar names.
4277 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
4278 LookupMemberName);
4279 if (CorrectTypo(Res, 0, 0, IDecl, false,
4280 IsArrow ? CTC_ObjCIvarLookup
4281 : CTC_ObjCPropertyLookup) &&
4282 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
4283 Diag(R.getNameLoc(),
4284 diag::err_typecheck_member_reference_ivar_suggest)
4285 << IDecl->getDeclName() << MemberName << IV->getDeclName()
4286 << FixItHint::CreateReplacement(R.getNameLoc(),
4287 IV->getNameAsString());
4288 Diag(IV->getLocation(), diag::note_previous_decl)
4289 << IV->getDeclName();
4290 } else {
4291 Res.clear();
4292 Res.setLookupName(Member);
4293
4294 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
4295 << IDecl->getDeclName() << MemberName
John Wiegley01296292011-04-08 18:41:53 +00004296 << BaseExpr.get()->getSourceRange();
John McCall68fc88ec2010-12-15 16:46:44 +00004297 return ExprError();
4298 }
4299 }
4300
4301 // If the decl being referenced had an error, return an error for this
4302 // sub-expr without emitting another error, in order to avoid cascading
4303 // error cases.
4304 if (IV->isInvalidDecl())
4305 return ExprError();
4306
4307 // Check whether we can reference this field.
4308 if (DiagnoseUseOfDecl(IV, MemberLoc))
4309 return ExprError();
4310 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
4311 IV->getAccessControl() != ObjCIvarDecl::Package) {
4312 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
4313 if (ObjCMethodDecl *MD = getCurMethodDecl())
4314 ClassOfMethodDecl = MD->getClassInterface();
4315 else if (ObjCImpDecl && getCurFunctionDecl()) {
4316 // Case of a c-function declared inside an objc implementation.
4317 // FIXME: For a c-style function nested inside an objc implementation
4318 // class, there is no implementation context available, so we pass
4319 // down the context as argument to this routine. Ideally, this context
4320 // need be passed down in the AST node and somehow calculated from the
4321 // AST for a function decl.
4322 if (ObjCImplementationDecl *IMPD =
4323 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
4324 ClassOfMethodDecl = IMPD->getClassInterface();
4325 else if (ObjCCategoryImplDecl* CatImplClass =
4326 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
4327 ClassOfMethodDecl = CatImplClass->getClassInterface();
4328 }
4329
4330 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
4331 if (ClassDeclared != IDecl ||
4332 ClassOfMethodDecl != ClassDeclared)
4333 Diag(MemberLoc, diag::error_private_ivar_access)
4334 << IV->getDeclName();
4335 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
4336 // @protected
4337 Diag(MemberLoc, diag::error_protected_ivar_access)
4338 << IV->getDeclName();
4339 }
Fariborz Jahanian62c72d02011-06-16 17:29:56 +00004340 if (getLangOptions().ObjCAutoRefCount) {
4341 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
4342 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
4343 if (UO->getOpcode() == UO_Deref)
4344 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
4345
4346 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
4347 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4348 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
4349 }
John McCall68fc88ec2010-12-15 16:46:44 +00004350
4351 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
John Wiegley01296292011-04-08 18:41:53 +00004352 MemberLoc, BaseExpr.take(),
John McCall68fc88ec2010-12-15 16:46:44 +00004353 IsArrow));
4354 }
4355
4356 // Objective-C property access.
4357 const ObjCObjectPointerType *OPT;
4358 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
4359 // This actually uses the base as an r-value.
John Wiegley01296292011-04-08 18:41:53 +00004360 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4361 if (BaseExpr.isInvalid())
4362 return ExprError();
4363
4364 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
John McCall68fc88ec2010-12-15 16:46:44 +00004365
4366 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
4367
4368 const ObjCObjectType *OT = OPT->getObjectType();
4369
4370 // id, with and without qualifiers.
4371 if (OT->isObjCId()) {
4372 // Check protocols on qualified interfaces.
4373 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
4374 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
4375 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
4376 // Check the use of this declaration
4377 if (DiagnoseUseOfDecl(PD, MemberLoc))
4378 return ExprError();
4379
Douglas Gregor33823722011-06-11 01:09:30 +00004380 QualType T = PD->getType();
4381 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
4382 T = getMessageSendResultType(BaseType, Getter, false, false);
4383
4384 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCall68fc88ec2010-12-15 16:46:44 +00004385 VK_LValue,
4386 OK_ObjCProperty,
4387 MemberLoc,
John Wiegley01296292011-04-08 18:41:53 +00004388 BaseExpr.take()));
John McCall68fc88ec2010-12-15 16:46:44 +00004389 }
4390
4391 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
4392 // Check the use of this method.
4393 if (DiagnoseUseOfDecl(OMD, MemberLoc))
4394 return ExprError();
4395 Selector SetterSel =
4396 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4397 PP.getSelectorTable(), Member);
4398 ObjCMethodDecl *SMD = 0;
4399 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
4400 SetterSel, Context))
4401 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Douglas Gregor33823722011-06-11 01:09:30 +00004402 QualType PType = getMessageSendResultType(BaseType, OMD, false,
4403 false);
John McCall68fc88ec2010-12-15 16:46:44 +00004404
4405 ExprValueKind VK = VK_LValue;
4406 if (!getLangOptions().CPlusPlus &&
4407 IsCForbiddenLValueType(Context, PType))
4408 VK = VK_RValue;
4409 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4410
4411 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
4412 VK, OK,
John Wiegley01296292011-04-08 18:41:53 +00004413 MemberLoc, BaseExpr.take()));
John McCall68fc88ec2010-12-15 16:46:44 +00004414 }
4415 }
Fariborz Jahanianb03a4c22011-03-15 17:27:48 +00004416 // Use of id.member can only be for a property reference. Do not
4417 // use the 'id' redefinition in this case.
4418 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
John McCall68fc88ec2010-12-15 16:46:44 +00004419 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4420 ObjCImpDecl, HasTemplateArgs);
4421
4422 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
4423 << MemberName << BaseType);
4424 }
4425
4426 // 'Class', unqualified only.
4427 if (OT->isObjCClass()) {
4428 // Only works in a method declaration (??!).
4429 ObjCMethodDecl *MD = getCurMethodDecl();
4430 if (!MD) {
4431 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4432 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4433 ObjCImpDecl, HasTemplateArgs);
4434
4435 goto fail;
4436 }
4437
4438 // Also must look for a getter name which uses property syntax.
4439 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004440 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4441 ObjCMethodDecl *Getter;
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004442 if ((Getter = IFace->lookupClassMethod(Sel))) {
4443 // Check the use of this method.
4444 if (DiagnoseUseOfDecl(Getter, MemberLoc))
4445 return ExprError();
John McCall68fc88ec2010-12-15 16:46:44 +00004446 } else
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00004447 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004448 // If we found a getter then this may be a valid dot-reference, we
4449 // will look for the matching setter, in case it is needed.
4450 Selector SetterSel =
John McCall68fc88ec2010-12-15 16:46:44 +00004451 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4452 PP.getSelectorTable(), Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004453 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
4454 if (!Setter) {
4455 // If this reference is in an @implementation, also check for 'private'
4456 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00004457 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004458 }
4459 // Look through local category implementations associated with the class.
4460 if (!Setter)
4461 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004462
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004463 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
4464 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004465
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004466 if (Getter || Setter) {
4467 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004468
John McCall4bc41ae2010-11-18 19:01:18 +00004469 ExprValueKind VK = VK_LValue;
4470 if (Getter) {
Douglas Gregor33823722011-06-11 01:09:30 +00004471 PType = getMessageSendResultType(QualType(OT, 0), Getter, true,
4472 false);
John McCall4bc41ae2010-11-18 19:01:18 +00004473 if (!getLangOptions().CPlusPlus &&
4474 IsCForbiddenLValueType(Context, PType))
4475 VK = VK_RValue;
4476 } else {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004477 // Get the expression type from Setter's incoming parameter.
4478 PType = (*(Setter->param_end() -1))->getType();
John McCall4bc41ae2010-11-18 19:01:18 +00004479 }
4480 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4481
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004482 // FIXME: we must check that the setter has property type.
John McCallb7bd14f2010-12-02 01:19:52 +00004483 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
4484 PType, VK, OK,
John Wiegley01296292011-04-08 18:41:53 +00004485 MemberLoc, BaseExpr.take()));
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004486 }
John McCall68fc88ec2010-12-15 16:46:44 +00004487
4488 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4489 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4490 ObjCImpDecl, HasTemplateArgs);
4491
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004492 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall68fc88ec2010-12-15 16:46:44 +00004493 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004494 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004495
John McCall68fc88ec2010-12-15 16:46:44 +00004496 // Normal property access.
John Wiegley01296292011-04-08 18:41:53 +00004497 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), MemberName, MemberLoc,
John McCall68fc88ec2010-12-15 16:46:44 +00004498 SourceLocation(), QualType(), false);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004499 }
Alexis Huntc46382e2010-04-28 23:02:27 +00004500
Chris Lattnerb63a7452008-07-21 04:28:12 +00004501 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00004502 if (BaseType->isExtVectorType()) {
John McCall15317a22010-12-15 04:42:30 +00004503 // FIXME: this expr should store IsArrow.
Anders Carlssonf571c112009-08-26 18:25:21 +00004504 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John Wiegley01296292011-04-08 18:41:53 +00004505 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
John McCall4bc41ae2010-11-18 19:01:18 +00004506 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
4507 Member, MemberLoc);
Chris Lattnerb63a7452008-07-21 04:28:12 +00004508 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004509 return ExprError();
John McCall4bc41ae2010-11-18 19:01:18 +00004510
John Wiegley01296292011-04-08 18:41:53 +00004511 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
John McCall4bc41ae2010-11-18 19:01:18 +00004512 *Member, MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00004513 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004514
John McCall68fc88ec2010-12-15 16:46:44 +00004515 // Adjust builtin-sel to the appropriate redefinition type if that's
4516 // not just a pointer to builtin-sel again.
4517 if (IsArrow &&
4518 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
4519 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
John Wiegley01296292011-04-08 18:41:53 +00004520 BaseExpr = ImpCastExprToType(BaseExpr.take(), Context.ObjCSelRedefinitionType,
4521 CK_BitCast);
John McCall68fc88ec2010-12-15 16:46:44 +00004522 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4523 ObjCImpDecl, HasTemplateArgs);
4524 }
4525
4526 // Failure cases.
4527 fail:
4528
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004529 // Recover from dot accesses to pointers, e.g.:
4530 // type *foo;
4531 // foo.bar
4532 // This is actually well-formed in two cases:
4533 // - 'type' is an Objective C type
4534 // - 'bar' is a pseudo-destructor name which happens to refer to
4535 // the appropriate pointer type
John McCall68fc88ec2010-12-15 16:46:44 +00004536 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004537 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
4538 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
John McCall68fc88ec2010-12-15 16:46:44 +00004539 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley01296292011-04-08 18:41:53 +00004540 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004541 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall68fc88ec2010-12-15 16:46:44 +00004542
4543 // Recurse as an -> access.
4544 IsArrow = true;
4545 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4546 ObjCImpDecl, HasTemplateArgs);
4547 }
John McCall68fc88ec2010-12-15 16:46:44 +00004548 }
4549
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004550 // If the user is trying to apply -> or . to a function name, it's probably
4551 // because they forgot parentheses to call that function.
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00004552 QualType ZeroArgCallTy;
4553 UnresolvedSet<4> Overloads;
4554 if (isExprCallable(*BaseExpr.get(), ZeroArgCallTy, Overloads)) {
4555 if (ZeroArgCallTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +00004556 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00004557 << (Overloads.size() > 1) << 0 << BaseExpr.get()->getSourceRange();
4558 UnresolvedSet<2> PlausibleOverloads;
4559 for (OverloadExpr::decls_iterator It = Overloads.begin(),
4560 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
4561 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
4562 QualType OverloadResultTy = OverloadDecl->getResultType();
4563 if ((!IsArrow && OverloadResultTy->isRecordType()) ||
4564 (IsArrow && OverloadResultTy->isPointerType() &&
4565 OverloadResultTy->getPointeeType()->isRecordType()))
4566 PlausibleOverloads.addDecl(It.getDecl());
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004567 }
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00004568 NoteOverloads(PlausibleOverloads, BaseExpr.get()->getExprLoc());
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004569 return ExprError();
4570 }
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00004571 if ((!IsArrow && ZeroArgCallTy->isRecordType()) ||
4572 (IsArrow && ZeroArgCallTy->isPointerType() &&
4573 ZeroArgCallTy->getPointeeType()->isRecordType())) {
4574 // At this point, we know BaseExpr looks like it's potentially callable
4575 // with 0 arguments, and that it returns something of a reasonable type,
4576 // so we can emit a fixit and carry on pretending that BaseExpr was
4577 // actually a CallExpr.
4578 SourceLocation ParenInsertionLoc =
4579 PP.getLocForEndOfToken(BaseExpr.get()->getLocEnd());
4580 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
4581 << (Overloads.size() > 1) << 1 << BaseExpr.get()->getSourceRange()
4582 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4583 // FIXME: Try this before emitting the fixit, and suppress diagnostics
4584 // while doing so.
4585 ExprResult NewBase =
4586 ActOnCallExpr(0, BaseExpr.take(), ParenInsertionLoc,
4587 MultiExprArg(*this, 0, 0),
4588 ParenInsertionLoc.getFileLocWithOffset(1));
4589 if (NewBase.isInvalid())
4590 return ExprError();
4591 BaseExpr = NewBase;
4592 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
4593 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4594 ObjCImpDecl, HasTemplateArgs);
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004595 }
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004596 }
4597
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004598 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
John Wiegley01296292011-04-08 18:41:53 +00004599 << BaseType << BaseExpr.get()->getSourceRange();
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004600
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004601 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00004602}
4603
John McCall10eae182009-11-30 22:42:35 +00004604/// The main callback when the parser finds something like
4605/// expression . [nested-name-specifier] identifier
4606/// expression -> [nested-name-specifier] identifier
4607/// where 'identifier' encompasses a fairly broad spectrum of
4608/// possibilities, including destructor and operator references.
4609///
4610/// \param OpKind either tok::arrow or tok::period
4611/// \param HasTrailingLParen whether the next token is '(', which
4612/// is used to diagnose mis-uses of special members that can
4613/// only be called
4614/// \param ObjCImpDecl the current ObjC @implementation decl;
4615/// this is an ugly hack around the fact that ObjC @implementations
4616/// aren't properly put in the context chain
John McCalldadc5752010-08-24 06:29:42 +00004617ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall15317a22010-12-15 04:42:30 +00004618 SourceLocation OpLoc,
4619 tok::TokenKind OpKind,
4620 CXXScopeSpec &SS,
4621 UnqualifiedId &Id,
4622 Decl *ObjCImpDecl,
4623 bool HasTrailingLParen) {
John McCall10eae182009-11-30 22:42:35 +00004624 if (SS.isSet() && SS.isInvalid())
4625 return ExprError();
4626
Francois Pichet64225792011-01-18 05:04:39 +00004627 // Warn about the explicit constructor calls Microsoft extension.
4628 if (getLangOptions().Microsoft &&
4629 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4630 Diag(Id.getSourceRange().getBegin(),
4631 diag::ext_ms_explicit_constructor_call);
4632
John McCall10eae182009-11-30 22:42:35 +00004633 TemplateArgumentListInfo TemplateArgsBuffer;
4634
4635 // Decompose the name into its component parts.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004636 DeclarationNameInfo NameInfo;
John McCall10eae182009-11-30 22:42:35 +00004637 const TemplateArgumentListInfo *TemplateArgs;
4638 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004639 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004640
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004641 DeclarationName Name = NameInfo.getName();
John McCall10eae182009-11-30 22:42:35 +00004642 bool IsArrow = (OpKind == tok::arrow);
4643
4644 NamedDecl *FirstQualifierInScope
4645 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4646 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4647
4648 // This is a postfix expression, so get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004649 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00004650 if (Result.isInvalid()) return ExprError();
4651 Base = Result.take();
John McCall10eae182009-11-30 22:42:35 +00004652
Douglas Gregor41f90302010-04-12 20:54:26 +00004653 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4654 isDependentScopeSpecifier(SS)) {
John McCallb268a282010-08-23 23:25:46 +00004655 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00004656 IsArrow, OpLoc,
4657 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004658 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004659 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004660 LookupResult R(*this, NameInfo, LookupMemberName);
John Wiegley01296292011-04-08 18:41:53 +00004661 ExprResult BaseResult = Owned(Base);
4662 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCalle9cccd82010-06-16 08:42:20 +00004663 SS, ObjCImpDecl, TemplateArgs != 0);
John Wiegley01296292011-04-08 18:41:53 +00004664 if (BaseResult.isInvalid())
4665 return ExprError();
4666 Base = BaseResult.take();
Alexis Huntc46382e2010-04-28 23:02:27 +00004667
John McCalle9cccd82010-06-16 08:42:20 +00004668 if (Result.isInvalid()) {
4669 Owned(Base);
4670 return ExprError();
4671 }
John McCall10eae182009-11-30 22:42:35 +00004672
John McCalle9cccd82010-06-16 08:42:20 +00004673 if (Result.get()) {
4674 // The only way a reference to a destructor can be used is to
4675 // immediately call it, which falls into this case. If the
4676 // next token is not a '(', produce a diagnostic and build the
4677 // call now.
4678 if (!HasTrailingLParen &&
4679 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCallb268a282010-08-23 23:25:46 +00004680 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall10eae182009-11-30 22:42:35 +00004681
John McCalle9cccd82010-06-16 08:42:20 +00004682 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00004683 }
4684
John McCallb268a282010-08-23 23:25:46 +00004685 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00004686 OpLoc, IsArrow, SS, FirstQualifierInScope,
4687 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004688 }
4689
4690 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00004691}
4692
John McCalldadc5752010-08-24 06:29:42 +00004693ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00004694 FunctionDecl *FD,
4695 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00004696 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004697 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00004698 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00004699 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004700 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00004701 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004702 return ExprError();
4703 }
4704
4705 if (Param->hasUninstantiatedDefaultArg()) {
4706 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00004707
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004708 // Instantiate the expression.
4709 MultiLevelTemplateArgumentList ArgList
4710 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00004711
Nico Weber44887f62010-11-29 18:19:25 +00004712 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004713 = ArgList.getInnermost();
4714 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4715 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00004716
Nico Weber44887f62010-11-29 18:19:25 +00004717 ExprResult Result;
4718 {
4719 // C++ [dcl.fct.default]p5:
4720 // The names in the [default argument] expression are bound, and
4721 // the semantic constraints are checked, at the point where the
4722 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00004723 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00004724 Result = SubstExpr(UninstExpr, ArgList);
4725 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004726 if (Result.isInvalid())
4727 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004728
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004729 // Check the expression as an initializer for the parameter.
4730 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004731 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004732 InitializationKind Kind
4733 = InitializationKind::CreateCopy(Param->getLocation(),
4734 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4735 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00004736
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004737 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4738 Result = InitSeq.Perform(*this, Entity, Kind,
4739 MultiExprArg(*this, &ResultE, 1));
4740 if (Result.isInvalid())
4741 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004742
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004743 // Build the default argument expression.
4744 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4745 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00004746 }
4747
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004748 // If the default expression creates temporaries, we need to
4749 // push them to the current stack of expression temporaries so they'll
4750 // be properly destroyed.
4751 // FIXME: We should really be rebuilding the default argument with new
4752 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00004753 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4754 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4755 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4756 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4757 ExprTemporaries.push_back(Temporary);
John McCall31168b02011-06-15 23:02:42 +00004758 ExprNeedsCleanups = true;
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00004759 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004760
4761 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00004762 // Just mark all of the declarations in this potentially-evaluated expression
4763 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004764 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00004765 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00004766}
4767
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004768/// ConvertArgumentsForCall - Converts the arguments specified in
4769/// Args/NumArgs to the parameter types of the function FDecl with
4770/// function prototype Proto. Call is the call expression itself, and
4771/// Fn is the function expression. For a C++ member function, this
4772/// routine does not attempt to convert the object argument. Returns
4773/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004774bool
4775Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004776 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004777 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004778 Expr **Args, unsigned NumArgs,
4779 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00004780 // Bail out early if calling a builtin with custom typechecking.
4781 // We don't need to do this in the
4782 if (FDecl)
4783 if (unsigned ID = FDecl->getBuiltinID())
4784 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4785 return false;
4786
Mike Stump4e1f26a2009-02-19 03:04:26 +00004787 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004788 // assignment, to the types of the corresponding parameter, ...
4789 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00004790 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004791
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004792 // If too few arguments are available (and we don't have default
4793 // arguments for the remaining parameters), don't make the call.
4794 if (NumArgs < NumArgsInProto) {
4795 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4796 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004797 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00004798 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00004799 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004800 }
4801
4802 // If too many are passed and not variadic, error on the extras and drop
4803 // them.
4804 if (NumArgs > NumArgsInProto) {
4805 if (!Proto->isVariadic()) {
4806 Diag(Args[NumArgsInProto]->getLocStart(),
4807 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004808 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004809 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004810 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4811 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00004812
4813 // Emit the location of the prototype.
4814 if (FDecl && !FDecl->getBuiltinID())
4815 Diag(FDecl->getLocStart(),
4816 diag::note_typecheck_call_too_many_args)
4817 << FDecl;
4818
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004819 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00004820 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004821 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004822 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004823 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004824 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004825 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004826 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4827 if (Fn->getType()->isBlockPointerType())
4828 CallType = VariadicBlock; // Block
4829 else if (isa<MemberExpr>(Fn))
4830 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004831 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004832 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004833 if (Invalid)
4834 return true;
4835 unsigned TotalNumArgs = AllArgs.size();
4836 for (unsigned i = 0; i < TotalNumArgs; ++i)
4837 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004838
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004839 return false;
4840}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004841
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004842bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4843 FunctionDecl *FDecl,
4844 const FunctionProtoType *Proto,
4845 unsigned FirstProtoArg,
4846 Expr **Args, unsigned NumArgs,
4847 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004848 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004849 unsigned NumArgsInProto = Proto->getNumArgs();
4850 unsigned NumArgsToCheck = NumArgs;
4851 bool Invalid = false;
4852 if (NumArgs != NumArgsInProto)
4853 // Use default arguments for missing arguments
4854 NumArgsToCheck = NumArgsInProto;
4855 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004856 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004857 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004858 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004859
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004860 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004861 if (ArgIx < NumArgs) {
4862 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004863
Eli Friedman3164fb12009-03-22 22:00:50 +00004864 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4865 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00004866 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004867 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00004868 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004869
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004870 // Pass the argument
4871 ParmVarDecl *Param = 0;
4872 if (FDecl && i < FDecl->getNumParams())
4873 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00004874
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004875 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004876 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00004877 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
4878 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00004879 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00004880 SourceLocation(),
4881 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004882 if (ArgE.isInvalid())
4883 return true;
4884
4885 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004886 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00004887 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004888
John McCalldadc5752010-08-24 06:29:42 +00004889 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004890 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004891 if (ArgExpr.isInvalid())
4892 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004893
Anders Carlsson355933d2009-08-25 03:49:14 +00004894 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004895 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004896 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004897 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004898
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004899 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004900 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00004901
4902 // Assume that extern "C" functions with variadic arguments that
4903 // return __unknown_anytype aren't *really* variadic.
4904 if (Proto->getResultType() == Context.UnknownAnyTy &&
4905 FDecl && FDecl->isExternC()) {
4906 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4907 ExprResult arg;
4908 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
4909 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
4910 else
4911 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4912 Invalid |= arg.isInvalid();
4913 AllArgs.push_back(arg.take());
4914 }
4915
4916 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4917 } else {
4918 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4919 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4920 Invalid |= Arg.isInvalid();
4921 AllArgs.push_back(Arg.take());
4922 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004923 }
4924 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004925 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004926}
4927
John McCall2979fe02011-04-12 00:42:48 +00004928/// Given a function expression of unknown-any type, try to rebuild it
4929/// to have a function type.
4930static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4931
Steve Naroff83895f72007-09-16 03:34:24 +00004932/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00004933/// This provides the location of the left/right parens and a list of comma
4934/// locations.
John McCalldadc5752010-08-24 06:29:42 +00004935ExprResult
John McCallb268a282010-08-23 23:25:46 +00004936Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004937 MultiExprArg args, SourceLocation RParenLoc,
4938 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004939 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00004940
4941 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004942 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00004943 if (Result.isInvalid()) return ExprError();
4944 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00004945
John McCallb268a282010-08-23 23:25:46 +00004946 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00004947
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004948 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004949 // If this is a pseudo-destructor expression, build the call immediately.
4950 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4951 if (NumArgs > 0) {
4952 // Pseudo-destructor calls should not have any arguments.
4953 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00004954 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00004955 SourceRange(Args[0]->getLocStart(),
4956 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00004957
Douglas Gregorad8a3362009-09-04 17:36:40 +00004958 NumArgs = 0;
4959 }
Mike Stump11289f42009-09-09 15:08:12 +00004960
Douglas Gregorad8a3362009-09-04 17:36:40 +00004961 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00004962 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004963 }
Mike Stump11289f42009-09-09 15:08:12 +00004964
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004965 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00004966 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00004967 // FIXME: Will need to cache the results of name lookup (including ADL) in
4968 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004969 bool Dependent = false;
4970 if (Fn->isTypeDependent())
4971 Dependent = true;
4972 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4973 Dependent = true;
4974
Peter Collingbourne41f85462011-02-09 21:07:24 +00004975 if (Dependent) {
4976 if (ExecConfig) {
4977 return Owned(new (Context) CUDAKernelCallExpr(
4978 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4979 Context.DependentTy, VK_RValue, RParenLoc));
4980 } else {
4981 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4982 Context.DependentTy, VK_RValue,
4983 RParenLoc));
4984 }
4985 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004986
4987 // Determine whether this is a call to an object (C++ [over.call.object]).
4988 if (Fn->getType()->isRecordType())
4989 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004990 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004991
John McCall2979fe02011-04-12 00:42:48 +00004992 if (Fn->getType() == Context.UnknownAnyTy) {
4993 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4994 if (result.isInvalid()) return ExprError();
4995 Fn = result.take();
4996 }
4997
John McCall0009fcc2011-04-26 20:42:42 +00004998 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00004999 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00005000 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00005001 }
John McCall0009fcc2011-04-26 20:42:42 +00005002 }
John McCall10eae182009-11-30 22:42:35 +00005003
John McCall0009fcc2011-04-26 20:42:42 +00005004 // Check for overloaded calls. This can happen even in C due to extensions.
5005 if (Fn->getType() == Context.OverloadTy) {
5006 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5007
5008 // We aren't supposed to apply this logic if there's an '&' involved.
5009 if (!find.IsAddressOfOperand) {
5010 OverloadExpr *ovl = find.Expression;
5011 if (isa<UnresolvedLookupExpr>(ovl)) {
5012 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
5013 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
5014 RParenLoc, ExecConfig);
5015 } else {
John McCall2d74de92009-12-01 22:10:20 +00005016 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00005017 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00005018 }
5019 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005020 }
5021
Douglas Gregore254f902009-02-04 00:32:51 +00005022 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005023
Eli Friedmane14b1992009-12-26 03:35:45 +00005024 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00005025
John McCall57500772009-12-16 12:17:52 +00005026 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00005027 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
5028 if (UnOp->getOpcode() == UO_AddrOf)
5029 NakedFn = UnOp->getSubExpr()->IgnoreParens();
5030
John McCall57500772009-12-16 12:17:52 +00005031 if (isa<DeclRefExpr>(NakedFn))
5032 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00005033 else if (isa<MemberExpr>(NakedFn))
5034 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00005035
Peter Collingbourne41f85462011-02-09 21:07:24 +00005036 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
5037 ExecConfig);
5038}
5039
5040ExprResult
5041Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
5042 MultiExprArg execConfig, SourceLocation GGGLoc) {
5043 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
5044 if (!ConfigDecl)
5045 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
5046 << "cudaConfigureCall");
5047 QualType ConfigQTy = ConfigDecl->getType();
5048
5049 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
5050 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
5051
5052 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00005053}
5054
Tanya Lattner55808c12011-06-04 00:47:47 +00005055/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5056///
5057/// __builtin_astype( value, dst type )
5058///
5059ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty,
5060 SourceLocation BuiltinLoc,
5061 SourceLocation RParenLoc) {
5062 ExprValueKind VK = VK_RValue;
5063 ExprObjectKind OK = OK_Ordinary;
5064 QualType DstTy = GetTypeFromParser(destty);
5065 QualType SrcTy = expr->getType();
5066 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5067 return ExprError(Diag(BuiltinLoc,
5068 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00005069 << DstTy
5070 << SrcTy
Tanya Lattner55808c12011-06-04 00:47:47 +00005071 << expr->getSourceRange());
5072 return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc, RParenLoc));
5073}
5074
John McCall57500772009-12-16 12:17:52 +00005075/// BuildResolvedCallExpr - Build a call to a resolved expression,
5076/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00005077/// unary-convert to an expression of function-pointer or
5078/// block-pointer type.
5079///
5080/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00005081ExprResult
John McCall2d74de92009-12-01 22:10:20 +00005082Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5083 SourceLocation LParenLoc,
5084 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00005085 SourceLocation RParenLoc,
5086 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00005087 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5088
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005089 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00005090 ExprResult Result = UsualUnaryConversions(Fn);
5091 if (Result.isInvalid())
5092 return ExprError();
5093 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005094
Chris Lattner08464942007-12-28 05:29:59 +00005095 // Make the call expr early, before semantic checks. This guarantees cleanup
5096 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00005097 CallExpr *TheCall;
5098 if (Config) {
5099 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5100 cast<CallExpr>(Config),
5101 Args, NumArgs,
5102 Context.BoolTy,
5103 VK_RValue,
5104 RParenLoc);
5105 } else {
5106 TheCall = new (Context) CallExpr(Context, Fn,
5107 Args, NumArgs,
5108 Context.BoolTy,
5109 VK_RValue,
5110 RParenLoc);
5111 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005112
John McCallbebede42011-02-26 05:39:39 +00005113 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5114
5115 // Bail out early if calling a builtin with custom typechecking.
5116 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5117 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
5118
John McCall31996342011-04-07 08:22:57 +00005119 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005120 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00005121 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005122 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5123 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00005124 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00005125 if (FuncT == 0)
5126 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5127 << Fn->getType() << Fn->getSourceRange());
5128 } else if (const BlockPointerType *BPT =
5129 Fn->getType()->getAs<BlockPointerType>()) {
5130 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5131 } else {
John McCall31996342011-04-07 08:22:57 +00005132 // Handle calls to expressions of unknown-any type.
5133 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00005134 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00005135 if (rewrite.isInvalid()) return ExprError();
5136 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00005137 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00005138 goto retry;
5139 }
5140
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005141 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5142 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00005143 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005144
Peter Collingbourne4b66c472011-02-23 01:53:29 +00005145 if (getLangOptions().CUDA) {
5146 if (Config) {
5147 // CUDA: Kernel calls must be to global functions
5148 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5149 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5150 << FDecl->getName() << Fn->getSourceRange());
5151
5152 // CUDA: Kernel function must have 'void' return type
5153 if (!FuncT->getResultType()->isVoidType())
5154 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5155 << Fn->getType() << Fn->getSourceRange());
5156 }
5157 }
5158
Eli Friedman3164fb12009-03-22 22:00:50 +00005159 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005160 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00005161 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00005162 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00005163 return ExprError();
5164
Chris Lattner08464942007-12-28 05:29:59 +00005165 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00005166 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00005167 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005168
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005169 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00005170 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005171 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005172 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00005173 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005174 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005175
Douglas Gregord8e97de2009-04-02 15:37:10 +00005176 if (FDecl) {
5177 // Check if we have too few/too many template arguments, based
5178 // on our knowledge of the function definition.
5179 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00005180 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00005181 const FunctionProtoType *Proto
5182 = Def->getType()->getAs<FunctionProtoType>();
5183 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00005184 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5185 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00005186 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00005187
5188 // If the function we're calling isn't a function prototype, but we have
5189 // a function prototype from a prior declaratiom, use that prototype.
5190 if (!FDecl->hasPrototype())
5191 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00005192 }
5193
Steve Naroff0b661582007-08-28 23:30:39 +00005194 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00005195 for (unsigned i = 0; i != NumArgs; i++) {
5196 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00005197
5198 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00005199 InitializedEntity Entity
5200 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00005201 Proto->getArgType(i),
5202 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00005203 ExprResult ArgE = PerformCopyInitialization(Entity,
5204 SourceLocation(),
5205 Owned(Arg));
5206 if (ArgE.isInvalid())
5207 return true;
5208
5209 Arg = ArgE.takeAs<Expr>();
5210
5211 } else {
John Wiegley01296292011-04-08 18:41:53 +00005212 ExprResult ArgE = DefaultArgumentPromotion(Arg);
5213
5214 if (ArgE.isInvalid())
5215 return true;
5216
5217 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00005218 }
5219
Douglas Gregor83025412010-10-26 05:45:40 +00005220 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
5221 Arg->getType(),
5222 PDiag(diag::err_call_incomplete_argument)
5223 << Arg->getSourceRange()))
5224 return ExprError();
5225
Chris Lattner08464942007-12-28 05:29:59 +00005226 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00005227 }
Steve Naroffae4143e2007-04-26 20:39:23 +00005228 }
Chris Lattner08464942007-12-28 05:29:59 +00005229
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005230 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5231 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005232 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5233 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005234
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00005235 // Check for sentinels
5236 if (NDecl)
5237 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00005238
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005239 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005240 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00005241 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005242 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00005243
John McCallbebede42011-02-26 05:39:39 +00005244 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00005245 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005246 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00005247 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005248 return ExprError();
5249 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005250
John McCallb268a282010-08-23 23:25:46 +00005251 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00005252}
5253
John McCalldadc5752010-08-24 06:29:42 +00005254ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005255Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005256 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00005257 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00005258 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00005259 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00005260
5261 TypeSourceInfo *TInfo;
5262 QualType literalType = GetTypeFromParser(Ty, &TInfo);
5263 if (!TInfo)
5264 TInfo = Context.getTrivialTypeSourceInfo(literalType);
5265
John McCallb268a282010-08-23 23:25:46 +00005266 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00005267}
5268
John McCalldadc5752010-08-24 06:29:42 +00005269ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00005270Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00005271 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00005272 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00005273
Eli Friedman37a186d2008-05-20 05:22:08 +00005274 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00005275 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5276 PDiag(diag::err_illegal_decl_array_incomplete_type)
5277 << SourceRange(LParenLoc,
5278 literalExpr->getSourceRange().getEnd())))
5279 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00005280 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005281 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5282 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00005283 } else if (!literalType->isDependentType() &&
5284 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00005285 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00005286 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00005287 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005288 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00005289
Douglas Gregor85dabae2009-12-16 01:38:02 +00005290 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00005291 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005292 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00005293 = InitializationKind::CreateCStyleCast(LParenLoc,
5294 SourceRange(LParenLoc, RParenLoc));
Eli Friedmana553d4a2009-12-22 02:35:53 +00005295 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00005296 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00005297 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00005298 &literalType);
5299 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005300 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00005301 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00005302
Chris Lattner79413952008-12-04 23:50:19 +00005303 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00005304 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00005305 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005306 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00005307 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00005308
John McCall7decc9e2010-11-18 06:31:45 +00005309 // In C, compound literals are l-values for some reason.
5310 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
5311
John McCall5d7aa7f2010-01-19 22:33:45 +00005312 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCall7decc9e2010-11-18 06:31:45 +00005313 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00005314}
5315
John McCalldadc5752010-08-24 06:29:42 +00005316ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00005317Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00005318 SourceLocation RBraceLoc) {
5319 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00005320 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00005321
Steve Naroff30d242c2007-09-15 18:49:24 +00005322 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00005323 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005324
Ted Kremenekac034612010-04-13 23:39:13 +00005325 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
5326 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005327 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005328 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00005329}
5330
John McCalld7646252010-11-14 08:17:51 +00005331/// Prepares for a scalar cast, performing all the necessary stages
5332/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00005333static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00005334 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5335 // Also, callers should have filtered out the invalid cases with
5336 // pointers. Everything else should be possible.
5337
John Wiegley01296292011-04-08 18:41:53 +00005338 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00005339 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00005340 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00005341
John McCall8cb679e2010-11-15 09:13:47 +00005342 switch (SrcTy->getScalarTypeKind()) {
5343 case Type::STK_MemberPointer:
5344 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00005345
John McCall8cb679e2010-11-15 09:13:47 +00005346 case Type::STK_Pointer:
5347 switch (DestTy->getScalarTypeKind()) {
5348 case Type::STK_Pointer:
5349 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00005350 CK_AnyPointerToObjCPointerCast :
5351 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00005352 case Type::STK_Bool:
5353 return CK_PointerToBoolean;
5354 case Type::STK_Integral:
5355 return CK_PointerToIntegral;
5356 case Type::STK_Floating:
5357 case Type::STK_FloatingComplex:
5358 case Type::STK_IntegralComplex:
5359 case Type::STK_MemberPointer:
5360 llvm_unreachable("illegal cast from pointer");
5361 }
5362 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005363
John McCall8cb679e2010-11-15 09:13:47 +00005364 case Type::STK_Bool: // casting from bool is like casting from an integer
5365 case Type::STK_Integral:
5366 switch (DestTy->getScalarTypeKind()) {
5367 case Type::STK_Pointer:
John Wiegley01296292011-04-08 18:41:53 +00005368 if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00005369 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00005370 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005371 case Type::STK_Bool:
5372 return CK_IntegralToBoolean;
5373 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00005374 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00005375 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00005376 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00005377 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00005378 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5379 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00005380 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005381 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00005382 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5383 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00005384 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005385 case Type::STK_MemberPointer:
5386 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005387 }
5388 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005389
John McCall8cb679e2010-11-15 09:13:47 +00005390 case Type::STK_Floating:
5391 switch (DestTy->getScalarTypeKind()) {
5392 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00005393 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00005394 case Type::STK_Bool:
5395 return CK_FloatingToBoolean;
5396 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00005397 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00005398 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00005399 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5400 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00005401 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005402 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00005403 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5404 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00005405 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005406 case Type::STK_Pointer:
5407 llvm_unreachable("valid float->pointer cast?");
5408 case Type::STK_MemberPointer:
5409 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005410 }
5411 break;
5412
John McCall8cb679e2010-11-15 09:13:47 +00005413 case Type::STK_FloatingComplex:
5414 switch (DestTy->getScalarTypeKind()) {
5415 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005416 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00005417 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005418 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00005419 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00005420 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005421 if (S.Context.hasSameType(ET, DestTy))
5422 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00005423 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00005424 return CK_FloatingCast;
5425 }
John McCall8cb679e2010-11-15 09:13:47 +00005426 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005427 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005428 case Type::STK_Integral:
John Wiegley01296292011-04-08 18:41:53 +00005429 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5430 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00005431 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00005432 case Type::STK_Pointer:
5433 llvm_unreachable("valid complex float->pointer cast?");
5434 case Type::STK_MemberPointer:
5435 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005436 }
5437 break;
5438
John McCall8cb679e2010-11-15 09:13:47 +00005439 case Type::STK_IntegralComplex:
5440 switch (DestTy->getScalarTypeKind()) {
5441 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005442 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005443 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005444 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00005445 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00005446 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005447 if (S.Context.hasSameType(ET, DestTy))
5448 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00005449 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00005450 return CK_IntegralCast;
5451 }
John McCall8cb679e2010-11-15 09:13:47 +00005452 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005453 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005454 case Type::STK_Floating:
John Wiegley01296292011-04-08 18:41:53 +00005455 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5456 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00005457 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00005458 case Type::STK_Pointer:
5459 llvm_unreachable("valid complex int->pointer cast?");
5460 case Type::STK_MemberPointer:
5461 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005462 }
5463 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00005464 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005465
John McCalld7646252010-11-14 08:17:51 +00005466 llvm_unreachable("Unhandled scalar cast");
5467 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00005468}
5469
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005470/// CheckCastTypes - Check type constraints for casting between types.
John McCall31168b02011-06-15 23:02:42 +00005471ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyR,
5472 QualType castType, Expr *castExpr,
5473 CastKind& Kind, ExprValueKind &VK,
John Wiegley01296292011-04-08 18:41:53 +00005474 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall31996342011-04-07 08:22:57 +00005475 if (castExpr->getType() == Context.UnknownAnyTy)
5476 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
5477
Sebastian Redl9f831db2009-07-25 15:41:38 +00005478 if (getLangOptions().CPlusPlus)
John McCall31168b02011-06-15 23:02:42 +00005479 return CXXCheckCStyleCast(SourceRange(CastStartLoc,
Douglas Gregor15417cf2010-11-03 00:35:38 +00005480 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00005481 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00005482 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00005483
John McCall3aef3d82011-04-10 19:13:55 +00005484 assert(!castExpr->getType()->isPlaceholderType());
5485
John McCall7decc9e2010-11-18 06:31:45 +00005486 // We only support r-value casts in C.
5487 VK = VK_RValue;
5488
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005489 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
5490 // type needs to be scalar.
5491 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00005492 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley01296292011-04-08 18:41:53 +00005493 ExprResult castExprRes = IgnoredValueConversions(castExpr);
5494 if (castExprRes.isInvalid())
5495 return ExprError();
5496 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00005497
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005498 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00005499 Kind = CK_ToVoid;
John Wiegley01296292011-04-08 18:41:53 +00005500 return Owned(castExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00005501 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005502
John Wiegley01296292011-04-08 18:41:53 +00005503 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
5504 if (castExprRes.isInvalid())
5505 return ExprError();
5506 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00005507
Eli Friedmane98194d2010-07-17 20:43:49 +00005508 if (RequireCompleteType(TyR.getBegin(), castType,
5509 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00005510 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00005511
Anders Carlssonef918ac2009-10-16 02:35:04 +00005512 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005513 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005514 (castType->isStructureType() || castType->isUnionType())) {
5515 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00005516 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005517 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
5518 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005519 Kind = CK_NoOp;
John Wiegley01296292011-04-08 18:41:53 +00005520 return Owned(castExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00005521 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005522
Anders Carlsson525b76b2009-10-16 02:48:28 +00005523 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005524 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005525 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005526 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005527 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005528 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005529 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00005530 castExpr->getType()) &&
5531 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005532 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5533 << castExpr->getSourceRange();
5534 break;
5535 }
5536 }
John Wiegley01296292011-04-08 18:41:53 +00005537 if (Field == FieldEnd) {
5538 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005539 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005540 return ExprError();
5541 }
John McCalle3027922010-08-25 11:45:40 +00005542 Kind = CK_ToUnion;
John Wiegley01296292011-04-08 18:41:53 +00005543 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005544 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005545
Anders Carlsson525b76b2009-10-16 02:48:28 +00005546 // Reject any other conversions to non-scalar types.
John Wiegley01296292011-04-08 18:41:53 +00005547 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlsson525b76b2009-10-16 02:48:28 +00005548 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005549 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005550 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005551
John McCalld7646252010-11-14 08:17:51 +00005552 // The type we're casting to is known to be a scalar or vector.
5553
5554 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005555 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00005556 !castExpr->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005557 Diag(castExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00005558 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005559 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005560 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005561 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005562
5563 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00005564 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005565
Anton Yartsev28ccef72011-03-27 09:32:40 +00005566 if (castType->isVectorType()) {
5567 if (castType->getAs<VectorType>()->getVectorKind() ==
5568 VectorType::AltiVecVector &&
5569 (castExpr->getType()->isIntegerType() ||
5570 castExpr->getType()->isFloatingType())) {
5571 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00005572 return Owned(castExpr);
5573 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
5574 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00005575 } else
John Wiegley01296292011-04-08 18:41:53 +00005576 return Owned(castExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00005577 }
John Wiegley01296292011-04-08 18:41:53 +00005578 if (castExpr->getType()->isVectorType()) {
5579 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
5580 return ExprError();
5581 else
5582 return Owned(castExpr);
5583 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00005584
John McCalld7646252010-11-14 08:17:51 +00005585 // The source and target types are both scalars, i.e.
5586 // - arithmetic types (fundamental, enum, and complex)
5587 // - all kinds of pointers
5588 // Note that member pointers were filtered out with C++, above.
5589
John Wiegley01296292011-04-08 18:41:53 +00005590 if (isa<ObjCSelectorExpr>(castExpr)) {
5591 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
5592 return ExprError();
5593 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005594
John McCalld7646252010-11-14 08:17:51 +00005595 // If either type is a pointer, the other type has to be either an
5596 // integer or a pointer.
John McCall31168b02011-06-15 23:02:42 +00005597 QualType castExprType = castExpr->getType();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005598 if (!castType->isArithmeticType()) {
Douglas Gregor6972a622010-06-16 00:35:25 +00005599 if (!castExprType->isIntegralType(Context) &&
John Wiegley01296292011-04-08 18:41:53 +00005600 castExprType->isArithmeticType()) {
5601 Diag(castExpr->getLocStart(),
5602 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005603 << castExprType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005604 return ExprError();
5605 }
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005606 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley01296292011-04-08 18:41:53 +00005607 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
5608 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005609 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005610 return ExprError();
5611 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005612 }
Anders Carlsson094c4592009-10-18 18:12:03 +00005613
John McCall31168b02011-06-15 23:02:42 +00005614 if (getLangOptions().ObjCAutoRefCount) {
5615 // Diagnose problems with Objective-C casts involving lifetime qualifiers.
5616 CheckObjCARCConversion(SourceRange(CastStartLoc, castExpr->getLocEnd()),
5617 castType, castExpr, CCK_CStyleCast);
5618
5619 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
5620 if (const PointerType *ExprPtr = castExprType->getAs<PointerType>()) {
5621 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
5622 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
5623 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
5624 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
5625 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
5626 Diag(castExpr->getLocStart(),
5627 diag::err_typecheck_incompatible_lifetime)
5628 << castExprType << castType << AA_Casting
5629 << castExpr->getSourceRange();
5630
5631 return ExprError();
5632 }
5633 }
5634 }
5635 }
5636
John Wiegley01296292011-04-08 18:41:53 +00005637 castExprRes = Owned(castExpr);
5638 Kind = PrepareScalarCast(*this, castExprRes, castType);
5639 if (castExprRes.isInvalid())
5640 return ExprError();
5641 castExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00005642
John McCalld7646252010-11-14 08:17:51 +00005643 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00005644 CheckCastAlign(castExpr, castType, TyR);
5645
John Wiegley01296292011-04-08 18:41:53 +00005646 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005647}
5648
Anders Carlsson525b76b2009-10-16 02:48:28 +00005649bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00005650 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00005651 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005652
Anders Carlssonde71adf2007-11-27 05:51:55 +00005653 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00005654 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00005655 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00005656 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00005657 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00005658 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005659 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005660 } else
5661 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00005662 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005663 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005664
John McCalle3027922010-08-25 11:45:40 +00005665 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005666 return false;
5667}
5668
John Wiegley01296292011-04-08 18:41:53 +00005669ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5670 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00005671 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005672
Anders Carlsson43d70f82009-10-16 05:23:41 +00005673 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005674
Nate Begemanc8961a42009-06-27 22:05:55 +00005675 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5676 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00005677 if (SrcTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005678 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
5679 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00005680 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00005681 return ExprError();
5682 }
John McCalle3027922010-08-25 11:45:40 +00005683 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00005684 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00005685 }
5686
Nate Begemanbd956c42009-06-28 02:36:38 +00005687 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00005688 // conversion will take place first from scalar to elt type, and then
5689 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00005690 if (SrcTy->isPointerType())
5691 return Diag(R.getBegin(),
5692 diag::err_invalid_conversion_between_vector_and_scalar)
5693 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00005694
5695 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00005696 ExprResult CastExprRes = Owned(CastExpr);
5697 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
5698 if (CastExprRes.isInvalid())
5699 return ExprError();
5700 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005701
John McCalle3027922010-08-25 11:45:40 +00005702 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00005703 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00005704}
5705
John McCalldadc5752010-08-24 06:29:42 +00005706ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005707Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005708 SourceLocation RParenLoc, Expr *castExpr) {
5709 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00005710 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00005711
John McCall97513962010-01-15 18:39:57 +00005712 TypeSourceInfo *castTInfo;
5713 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5714 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00005715 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00005716
Nate Begeman5ec4b312009-08-10 23:49:36 +00005717 // If the Expr being casted is a ParenListExpr, handle it specially.
5718 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00005719 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00005720 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00005721
John McCallb268a282010-08-23 23:25:46 +00005722 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00005723}
5724
John McCalldadc5752010-08-24 06:29:42 +00005725ExprResult
John McCallebe54742010-01-15 18:56:44 +00005726Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00005727 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00005728 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00005729 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00005730 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00005731 ExprResult CastResult =
John McCall31168b02011-06-15 23:02:42 +00005732 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(),
5733 castExpr, Kind, VK, BasePath);
John Wiegley01296292011-04-08 18:41:53 +00005734 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005735 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00005736 castExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00005737
John McCallcf142162010-08-07 06:22:56 +00005738 return Owned(CStyleCastExpr::Create(Context,
John Wiegley01296292011-04-08 18:41:53 +00005739 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00005740 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00005741 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00005742}
5743
Nate Begeman5ec4b312009-08-10 23:49:36 +00005744/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5745/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00005746ExprResult
John McCallb268a282010-08-23 23:25:46 +00005747Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005748 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5749 if (!E)
5750 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00005751
John McCalldadc5752010-08-24 06:29:42 +00005752 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00005753
Nate Begeman5ec4b312009-08-10 23:49:36 +00005754 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00005755 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5756 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00005757
John McCallb268a282010-08-23 23:25:46 +00005758 if (Result.isInvalid()) return ExprError();
5759
5760 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005761}
5762
John McCalldadc5752010-08-24 06:29:42 +00005763ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00005764Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00005765 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00005766 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00005767 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00005768 QualType Ty = TInfo->getType();
Anton Yartsev28ccef72011-03-27 09:32:40 +00005769 bool isVectorLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00005770
Anton Yartsev28ccef72011-03-27 09:32:40 +00005771 // Check for an altivec or OpenCL literal,
John Thompson781ad172010-06-30 22:55:51 +00005772 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005773 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5774 if (PE->getNumExprs() == 0) {
5775 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5776 return ExprError();
5777 }
John Thompson781ad172010-06-30 22:55:51 +00005778 if (PE->getNumExprs() == 1) {
5779 if (!PE->getExpr(0)->getType()->isVectorType())
Anton Yartsev28ccef72011-03-27 09:32:40 +00005780 isVectorLiteral = true;
John Thompson781ad172010-06-30 22:55:51 +00005781 }
5782 else
Anton Yartsev28ccef72011-03-27 09:32:40 +00005783 isVectorLiteral = true;
John Thompson781ad172010-06-30 22:55:51 +00005784 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00005785
Anton Yartsev28ccef72011-03-27 09:32:40 +00005786 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
John Thompson781ad172010-06-30 22:55:51 +00005787 // then handle it as such.
Anton Yartsev28ccef72011-03-27 09:32:40 +00005788 if (isVectorLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005789 llvm::SmallVector<Expr *, 8> initExprs;
Anton Yartsev28ccef72011-03-27 09:32:40 +00005790 // '(...)' form of vector initialization in AltiVec: the number of
5791 // initializers must be one or must match the size of the vector.
5792 // If a single value is specified in the initializer then it will be
5793 // replicated to all the components of the vector
5794 if (Ty->getAs<VectorType>()->getVectorKind() ==
5795 VectorType::AltiVecVector) {
5796 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5797 // The number of initializers must be one or must match the size of the
5798 // vector. If a single value is specified in the initializer then it will
5799 // be replicated to all the components of the vector
5800 if (PE->getNumExprs() == 1) {
5801 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00005802 ExprResult Literal = Owned(PE->getExpr(0));
5803 Literal = ImpCastExprToType(Literal.take(), ElemTy,
5804 PrepareScalarCast(*this, Literal, ElemTy));
5805 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
Anton Yartsev28ccef72011-03-27 09:32:40 +00005806 }
5807 else if (PE->getNumExprs() < numElems) {
5808 Diag(PE->getExprLoc(),
5809 diag::err_incorrect_number_of_vector_initializers);
5810 return ExprError();
5811 }
5812 else
5813 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5814 initExprs.push_back(PE->getExpr(i));
5815 }
5816 else
5817 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5818 initExprs.push_back(PE->getExpr(i));
Nate Begeman5ec4b312009-08-10 23:49:36 +00005819
5820 // FIXME: This means that pretty-printing the final AST will produce curly
5821 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00005822 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5823 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00005824 initExprs.size(), RParenLoc);
5825 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00005826 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005827 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005828 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00005829 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00005830 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00005831 if (Result.isInvalid()) return ExprError();
5832 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005833 }
5834}
5835
John McCalldadc5752010-08-24 06:29:42 +00005836ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00005837 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005838 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00005839 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005840 unsigned nexprs = Val.size();
5841 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005842 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5843 Expr *expr;
5844 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5845 expr = new (Context) ParenExpr(L, R, exprs[0]);
5846 else
5847 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005848 return Owned(expr);
5849}
5850
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005851/// \brief Emit a specialized diagnostic when one expression is a null pointer
5852/// constant and the other is not a pointer.
5853bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5854 SourceLocation QuestionLoc) {
5855 Expr *NullExpr = LHS;
5856 Expr *NonPointerExpr = RHS;
5857 Expr::NullPointerConstantKind NullKind =
5858 NullExpr->isNullPointerConstant(Context,
5859 Expr::NPC_ValueDependentIsNotNull);
5860
5861 if (NullKind == Expr::NPCK_NotNull) {
5862 NullExpr = RHS;
5863 NonPointerExpr = LHS;
5864 NullKind =
5865 NullExpr->isNullPointerConstant(Context,
5866 Expr::NPC_ValueDependentIsNotNull);
5867 }
5868
5869 if (NullKind == Expr::NPCK_NotNull)
5870 return false;
5871
5872 if (NullKind == Expr::NPCK_ZeroInteger) {
5873 // In this case, check to make sure that we got here from a "NULL"
5874 // string in the source code.
5875 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00005876 SourceLocation loc = NullExpr->getExprLoc();
5877 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005878 return false;
5879 }
5880
5881 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5882 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5883 << NonPointerExpr->getType() << DiagType
5884 << NonPointerExpr->getSourceRange();
5885 return true;
5886}
5887
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005888/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5889/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00005890/// C99 6.5.15
John Wiegley01296292011-04-08 18:41:53 +00005891QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005892 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00005893 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00005894
John McCall3aef3d82011-04-10 19:13:55 +00005895 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00005896 if (!lhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005897 LHS = move(lhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005898
John McCall3aef3d82011-04-10 19:13:55 +00005899 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00005900 if (!rhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005901 RHS = move(rhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005902
Sebastian Redl1a99f442009-04-16 17:51:27 +00005903 // C++ is sufficiently different to merit its own checker.
5904 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00005905 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00005906
5907 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005908 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005909
John Wiegley01296292011-04-08 18:41:53 +00005910 Cond = UsualUnaryConversions(Cond.take());
5911 if (Cond.isInvalid())
5912 return QualType();
5913 LHS = UsualUnaryConversions(LHS.take());
5914 if (LHS.isInvalid())
5915 return QualType();
5916 RHS = UsualUnaryConversions(RHS.take());
5917 if (RHS.isInvalid())
5918 return QualType();
5919
5920 QualType CondTy = Cond.get()->getType();
5921 QualType LHSTy = LHS.get()->getType();
5922 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00005923
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005924 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005925 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00005926 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5927 // Throw an error if its not either.
5928 if (getLangOptions().OpenCL) {
5929 if (!CondTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005930 Diag(Cond.get()->getLocStart(),
Nate Begemanabb5a732010-09-20 22:41:17 +00005931 diag::err_typecheck_cond_expect_scalar_or_vector)
5932 << CondTy;
5933 return QualType();
5934 }
5935 }
5936 else {
John Wiegley01296292011-04-08 18:41:53 +00005937 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005938 << CondTy;
5939 return QualType();
5940 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005941 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005942
Chris Lattnere2949f42008-01-06 22:42:25 +00005943 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005944 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5945 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00005946
Nate Begemanabb5a732010-09-20 22:41:17 +00005947 // OpenCL: If the condition is a vector, and both operands are scalar,
5948 // attempt to implicity convert them to the vector type to act like the
5949 // built in select.
5950 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5951 // Both operands should be of scalar type.
5952 if (!LHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00005953 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005954 << CondTy;
5955 return QualType();
5956 }
5957 if (!RHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00005958 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005959 << CondTy;
5960 return QualType();
5961 }
5962 // Implicity convert these scalars to the type of the condition.
John Wiegley01296292011-04-08 18:41:53 +00005963 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5964 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begemanabb5a732010-09-20 22:41:17 +00005965 }
5966
Chris Lattnere2949f42008-01-06 22:42:25 +00005967 // If both operands have arithmetic type, do the usual arithmetic conversions
5968 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00005969 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5970 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005971 if (LHS.isInvalid() || RHS.isInvalid())
5972 return QualType();
5973 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00005974 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005975
Chris Lattnere2949f42008-01-06 22:42:25 +00005976 // If both operands are the same structure or union type, the result is that
5977 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005978 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5979 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00005980 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005981 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00005982 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00005983 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00005984 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005985 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005986
Chris Lattnere2949f42008-01-06 22:42:25 +00005987 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00005988 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00005989 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5990 if (!LHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00005991 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5992 << RHS.get()->getSourceRange();
Chris Lattner432cff52009-02-18 04:28:32 +00005993 if (!RHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00005994 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5995 << LHS.get()->getSourceRange();
5996 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
5997 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00005998 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00005999 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00006000 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6001 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00006002 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00006003 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00006004 // promote the null to a pointer.
John Wiegley01296292011-04-08 18:41:53 +00006005 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00006006 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00006007 }
Steve Naroff6b712a72009-07-14 18:25:06 +00006008 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00006009 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
6010 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00006011 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00006012 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006013
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006014 // All objective-c pointer type analysis is done here.
6015 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6016 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00006017 if (LHS.isInvalid() || RHS.isInvalid())
6018 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006019 if (!compositeType.isNull())
6020 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006021
6022
Steve Naroff05efa972009-07-01 14:36:47 +00006023 // Handle block pointer types.
6024 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
6025 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6026 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6027 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00006028 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
6029 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00006030 return destType;
6031 }
6032 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00006033 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00006034 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00006035 }
Steve Naroff05efa972009-07-01 14:36:47 +00006036 // We have 2 block pointer types.
6037 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6038 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00006039 return LHSTy;
6040 }
Steve Naroff05efa972009-07-01 14:36:47 +00006041 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006042 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
6043 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006044
Steve Naroff05efa972009-07-01 14:36:47 +00006045 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
6046 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00006047 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006048 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00006049 // In this situation, we assume void* type. No especially good
6050 // reason, but this is what gcc does, and we do have to pick
6051 // to get a consistent AST.
6052 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00006053 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6054 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00006055 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00006056 }
Steve Naroff05efa972009-07-01 14:36:47 +00006057 // The block pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00006058 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
6059 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00006060 return LHSTy;
6061 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006062
Steve Naroff05efa972009-07-01 14:36:47 +00006063 // Check constraints for C object pointers types (C99 6.5.15p3,6).
6064 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
6065 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006066 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6067 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00006068
6069 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6070 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6071 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00006072 QualType destPointee
6073 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00006074 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00006075 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00006076 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00006077 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00006078 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00006079 return destType;
6080 }
6081 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006082 QualType destPointee
6083 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00006084 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00006085 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00006086 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00006087 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00006088 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00006089 return destType;
6090 }
6091
6092 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6093 // Two identical pointer types are always compatible.
6094 return LHSTy;
6095 }
6096 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
6097 rhptee.getUnqualifiedType())) {
6098 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006099 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00006100 // In this situation, we assume void* type. No especially good
6101 // reason, but this is what gcc does, and we do have to pick
6102 // to get a consistent AST.
6103 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00006104 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6105 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00006106 return incompatTy;
6107 }
6108 // The pointer types are compatible.
6109 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
6110 // differently qualified versions of compatible types, the result type is
6111 // a pointer to an appropriately qualified version of the *composite*
6112 // type.
6113 // FIXME: Need to calculate the composite type.
6114 // FIXME: Need to add qualifiers
John Wiegley01296292011-04-08 18:41:53 +00006115 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
6116 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00006117 return LHSTy;
6118 }
Mike Stump11289f42009-09-09 15:08:12 +00006119
John McCalle84af4e2010-11-13 01:35:44 +00006120 // GCC compatibility: soften pointer/integer mismatch. Note that
6121 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00006122 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
6123 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00006124 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6125 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00006126 return RHSTy;
6127 }
6128 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
6129 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00006130 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6131 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00006132 return LHSTy;
6133 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00006134
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006135 // Emit a better diagnostic if one of the expressions is a null pointer
6136 // constant and the other is not a pointer type. In this case, the user most
6137 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00006138 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006139 return QualType();
6140
Chris Lattnere2949f42008-01-06 22:42:25 +00006141 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00006142 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00006143 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00006144 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00006145}
6146
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006147/// FindCompositeObjCPointerType - Helper method to find composite type of
6148/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00006149QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006150 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00006151 QualType LHSTy = LHS.get()->getType();
6152 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006153
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006154 // Handle things like Class and struct objc_class*. Here we case the result
6155 // to the pseudo-builtin, because that will be implicitly cast back to the
6156 // redefinition type if an attempt is made to access its fields.
6157 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00006158 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006159 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006160 return LHSTy;
6161 }
6162 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00006163 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006164 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006165 return RHSTy;
6166 }
6167 // And the same for struct objc_object* / id
6168 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00006169 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006170 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006171 return LHSTy;
6172 }
6173 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00006174 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006175 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006176 return RHSTy;
6177 }
6178 // And the same for struct objc_selector* / SEL
6179 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00006180 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006181 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006182 return LHSTy;
6183 }
6184 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00006185 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006186 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006187 return RHSTy;
6188 }
6189 // Check constraints for Objective-C object pointers types.
6190 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006191
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006192 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6193 // Two identical object pointer types are always compatible.
6194 return LHSTy;
6195 }
6196 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
6197 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
6198 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006199
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006200 // If both operands are interfaces and either operand can be
6201 // assigned to the other, use that type as the composite
6202 // type. This allows
6203 // xxx ? (A*) a : (B*) b
6204 // where B is a subclass of A.
6205 //
6206 // Additionally, as for assignment, if either type is 'id'
6207 // allow silent coercion. Finally, if the types are
6208 // incompatible then make sure to use 'id' as the composite
6209 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006210
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006211 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6212 // It could return the composite type.
6213 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6214 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6215 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6216 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6217 } else if ((LHSTy->isObjCQualifiedIdType() ||
6218 RHSTy->isObjCQualifiedIdType()) &&
6219 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6220 // Need to handle "id<xx>" explicitly.
6221 // GCC allows qualified id and any Objective-C type to devolve to
6222 // id. Currently localizing to here until clear this should be
6223 // part of ObjCQualifiedIdTypesAreCompatible.
6224 compositeType = Context.getObjCIdType();
6225 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6226 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006227 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006228 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
6229 ;
6230 else {
6231 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6232 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00006233 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006234 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00006235 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6236 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006237 return incompatTy;
6238 }
6239 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00006240 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
6241 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006242 return compositeType;
6243 }
6244 // Check Objective-C object pointer types and 'void *'
6245 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6246 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6247 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6248 QualType destPointee
6249 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6250 QualType destType = Context.getPointerType(destPointee);
6251 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00006252 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006253 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00006254 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006255 return destType;
6256 }
6257 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6258 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6259 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6260 QualType destPointee
6261 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6262 QualType destType = Context.getPointerType(destPointee);
6263 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00006264 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006265 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00006266 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006267 return destType;
6268 }
6269 return QualType();
6270}
6271
Chandler Carruthb00e8c02011-06-16 01:05:14 +00006272/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006273/// ParenRange in parentheses.
6274static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00006275 const PartialDiagnostic &Note,
6276 SourceRange ParenRange) {
6277 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6278 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6279 EndLoc.isValid()) {
6280 Self.Diag(Loc, Note)
6281 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6282 << FixItHint::CreateInsertion(EndLoc, ")");
6283 } else {
6284 // We can't display the parentheses, so just show the bare note.
6285 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006286 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006287}
6288
6289static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6290 return Opc >= BO_Mul && Opc <= BO_Shr;
6291}
6292
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006293/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6294/// expression, either using a built-in or overloaded operator,
6295/// and sets *OpCode to the opcode and *RHS to the right-hand side expression.
6296static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6297 Expr **RHS) {
6298 E = E->IgnoreParenImpCasts();
6299 E = E->IgnoreConversionOperator();
6300 E = E->IgnoreParenImpCasts();
6301
6302 // Built-in binary operator.
6303 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6304 if (IsArithmeticOp(OP->getOpcode())) {
6305 *Opcode = OP->getOpcode();
6306 *RHS = OP->getRHS();
6307 return true;
6308 }
6309 }
6310
6311 // Overloaded operator.
6312 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6313 if (Call->getNumArgs() != 2)
6314 return false;
6315
6316 // Make sure this is really a binary operator that is safe to pass into
6317 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6318 OverloadedOperatorKind OO = Call->getOperator();
6319 if (OO < OO_Plus || OO > OO_Arrow)
6320 return false;
6321
6322 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6323 if (IsArithmeticOp(OpKind)) {
6324 *Opcode = OpKind;
6325 *RHS = Call->getArg(1);
6326 return true;
6327 }
6328 }
6329
6330 return false;
6331}
6332
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006333static bool IsLogicOp(BinaryOperatorKind Opc) {
6334 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
6335}
6336
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006337/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6338/// or is a logical expression such as (x==y) which has int type, but is
6339/// commonly interpreted as boolean.
6340static bool ExprLooksBoolean(Expr *E) {
6341 E = E->IgnoreParenImpCasts();
6342
6343 if (E->getType()->isBooleanType())
6344 return true;
6345 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6346 return IsLogicOp(OP->getOpcode());
6347 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6348 return OP->getOpcode() == UO_LNot;
6349
6350 return false;
6351}
6352
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006353/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6354/// and binary operator are mixed in a way that suggests the programmer assumed
6355/// the conditional operator has higher precedence, for example:
6356/// "int x = a + someBinaryCondition ? 1 : 2".
6357static void DiagnoseConditionalPrecedence(Sema &Self,
6358 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00006359 Expr *Condition,
6360 Expr *LHS,
6361 Expr *RHS) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006362 BinaryOperatorKind CondOpcode;
6363 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006364
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00006365 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006366 return;
6367 if (!ExprLooksBoolean(CondRHS))
6368 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006369
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006370 // The condition is an arithmetic binary expression, with a right-
6371 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006372
Chandler Carruthb00e8c02011-06-16 01:05:14 +00006373 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00006374 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006375 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006376
Chandler Carruthb00e8c02011-06-16 01:05:14 +00006377 SuggestParentheses(Self, OpLoc,
6378 Self.PDiag(diag::note_precedence_conditional_silence)
6379 << BinaryOperator::getOpcodeStr(CondOpcode),
6380 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006381
Chandler Carruthb00e8c02011-06-16 01:05:14 +00006382 SuggestParentheses(Self, OpLoc,
6383 Self.PDiag(diag::note_precedence_conditional_first),
6384 SourceRange(CondRHS->getLocStart(), RHS->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006385}
6386
Steve Naroff83895f72007-09-16 03:34:24 +00006387/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00006388/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00006389ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00006390 SourceLocation ColonLoc,
6391 Expr *CondExpr, Expr *LHSExpr,
6392 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00006393 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6394 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00006395 OpaqueValueExpr *opaqueValue = 0;
6396 Expr *commonExpr = 0;
6397 if (LHSExpr == 0) {
6398 commonExpr = CondExpr;
6399
6400 // We usually want to apply unary conversions *before* saving, except
6401 // in the special case of a C++ l-value conditional.
6402 if (!(getLangOptions().CPlusPlus
6403 && !commonExpr->isTypeDependent()
6404 && commonExpr->getValueKind() == RHSExpr->getValueKind()
6405 && commonExpr->isGLValue()
6406 && commonExpr->isOrdinaryOrBitFieldObject()
6407 && RHSExpr->isOrdinaryOrBitFieldObject()
6408 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00006409 ExprResult commonRes = UsualUnaryConversions(commonExpr);
6410 if (commonRes.isInvalid())
6411 return ExprError();
6412 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00006413 }
6414
6415 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6416 commonExpr->getType(),
6417 commonExpr->getValueKind(),
6418 commonExpr->getObjectKind());
6419 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00006420 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00006421
John McCall7decc9e2010-11-18 06:31:45 +00006422 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00006423 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00006424 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
6425 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00006426 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00006427 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6428 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00006429 return ExprError();
6430
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006431 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6432 RHS.get());
6433
John McCallc07a0c72011-02-17 10:25:35 +00006434 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00006435 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
6436 LHS.take(), ColonLoc,
6437 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00006438
6439 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00006440 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
6441 RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00006442}
6443
John McCallaba90822011-01-31 23:13:11 +00006444// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00006445// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00006446// routine is it effectively iqnores the qualifiers on the top level pointee.
6447// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6448// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00006449static Sema::AssignConvertType
6450checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6451 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6452 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006453
Steve Naroff1f4d7272007-05-11 04:00:31 +00006454 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00006455 const Type *lhptee, *rhptee;
6456 Qualifiers lhq, rhq;
6457 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
6458 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006459
John McCallaba90822011-01-31 23:13:11 +00006460 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006461
6462 // C99 6.5.16.1p1: This following citation is common to constraints
6463 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6464 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00006465 Qualifiers lq;
6466
John McCall31168b02011-06-15 23:02:42 +00006467 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
6468 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
6469 lhq.compatiblyIncludesObjCLifetime(rhq)) {
6470 // Ignore lifetime for further calculation.
6471 lhq.removeObjCLifetime();
6472 rhq.removeObjCLifetime();
6473 }
6474
John McCall4fff8f62011-02-01 00:10:29 +00006475 if (!lhq.compatiblyIncludes(rhq)) {
6476 // Treat address-space mismatches as fatal. TODO: address subspaces
6477 if (lhq.getAddressSpace() != rhq.getAddressSpace())
6478 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6479
John McCall31168b02011-06-15 23:02:42 +00006480 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00006481 // and from void*.
John McCall31168b02011-06-15 23:02:42 +00006482 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
6483 .compatiblyIncludes(
6484 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
John McCall78535952011-03-26 02:56:45 +00006485 && (lhptee->isVoidType() || rhptee->isVoidType()))
6486 ; // keep old
6487
John McCall31168b02011-06-15 23:02:42 +00006488 // Treat lifetime mismatches as fatal.
6489 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6490 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6491
John McCall4fff8f62011-02-01 00:10:29 +00006492 // For GCC compatibility, other qualifier mismatches are treated
6493 // as still compatible in C.
6494 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6495 }
Steve Naroff3f597292007-05-11 22:18:03 +00006496
Mike Stump4e1f26a2009-02-19 03:04:26 +00006497 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6498 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00006499 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00006500 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006501 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00006502 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006503
Chris Lattner0a788432008-01-03 22:56:36 +00006504 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006505 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00006506 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00006507 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006508
Chris Lattner0a788432008-01-03 22:56:36 +00006509 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006510 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00006511 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00006512
6513 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006514 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00006515 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00006516 }
John McCall4fff8f62011-02-01 00:10:29 +00006517
Mike Stump4e1f26a2009-02-19 03:04:26 +00006518 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00006519 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00006520 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6521 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00006522 // Check if the pointee types are compatible ignoring the sign.
6523 // We explicitly check for char so that we catch "char" vs
6524 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00006525 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00006526 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006527 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00006528 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006529
Chris Lattnerec3a1562009-10-17 20:33:28 +00006530 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00006531 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006532 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00006533 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00006534
John McCall4fff8f62011-02-01 00:10:29 +00006535 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00006536 // Types are compatible ignoring the sign. Qualifier incompatibility
6537 // takes priority over sign incompatibility because the sign
6538 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00006539 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00006540 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00006541
John McCallaba90822011-01-31 23:13:11 +00006542 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00006543 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006544
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006545 // If we are a multi-level pointer, it's possible that our issue is simply
6546 // one of qualification - e.g. char ** -> const char ** is not allowed. If
6547 // the eventual target type is the same and the pointers have the same
6548 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00006549 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006550 do {
John McCall4fff8f62011-02-01 00:10:29 +00006551 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6552 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00006553 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006554
John McCall4fff8f62011-02-01 00:10:29 +00006555 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00006556 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006557 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006558
Eli Friedman80160bd2009-03-22 23:59:44 +00006559 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00006560 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00006561 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00006562 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00006563}
6564
John McCallaba90822011-01-31 23:13:11 +00006565/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00006566/// block pointer types are compatible or whether a block and normal pointer
6567/// are compatible. It is more restrict than comparing two function pointer
6568// types.
John McCallaba90822011-01-31 23:13:11 +00006569static Sema::AssignConvertType
6570checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
6571 QualType rhsType) {
6572 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6573 assert(rhsType.isCanonical() && "RHS not canonicalized!");
6574
Steve Naroff081c7422008-09-04 15:10:53 +00006575 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006576
Steve Naroff081c7422008-09-04 15:10:53 +00006577 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00006578 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
6579 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006580
John McCallaba90822011-01-31 23:13:11 +00006581 // In C++, the types have to match exactly.
6582 if (S.getLangOptions().CPlusPlus)
6583 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006584
John McCallaba90822011-01-31 23:13:11 +00006585 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006586
Steve Naroff081c7422008-09-04 15:10:53 +00006587 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00006588 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6589 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006590
John McCallaba90822011-01-31 23:13:11 +00006591 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
6592 return Sema::IncompatibleBlockPointer;
6593
Steve Naroff081c7422008-09-04 15:10:53 +00006594 return ConvTy;
6595}
6596
John McCallaba90822011-01-31 23:13:11 +00006597/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006598/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00006599static Sema::AssignConvertType
6600checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6601 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
6602 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
6603
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006604 if (lhsType->isObjCBuiltinType()) {
6605 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00006606 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
6607 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00006608 return Sema::IncompatiblePointer;
6609 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006610 }
6611 if (rhsType->isObjCBuiltinType()) {
6612 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00006613 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
6614 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00006615 return Sema::IncompatiblePointer;
6616 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006617 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006618 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006619 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006620 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006621 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006622
John McCallaba90822011-01-31 23:13:11 +00006623 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
6624 return Sema::CompatiblePointerDiscardsQualifiers;
6625
6626 if (S.Context.typesAreCompatible(lhsType, rhsType))
6627 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006628 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00006629 return Sema::IncompatibleObjCQualifiedId;
6630 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006631}
6632
John McCall29600e12010-11-16 02:32:08 +00006633Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00006634Sema::CheckAssignmentConstraints(SourceLocation Loc,
6635 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00006636 // Fake up an opaque expression. We don't actually care about what
6637 // cast operations are required, so if CheckAssignmentConstraints
6638 // adds casts to this they'll be wasted, but fortunately that doesn't
6639 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00006640 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00006641 ExprResult rhsPtr = &rhs;
John McCall29600e12010-11-16 02:32:08 +00006642 CastKind K = CK_Invalid;
6643
6644 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
6645}
6646
Mike Stump4e1f26a2009-02-19 03:04:26 +00006647/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6648/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00006649/// pointers. Here are some objectionable examples that GCC considers warnings:
6650///
6651/// int a, *pint;
6652/// short *pshort;
6653/// struct foo *pfoo;
6654///
6655/// pint = pshort; // warning: assignment from incompatible pointer type
6656/// a = pint; // warning: assignment makes integer from pointer without a cast
6657/// pint = a; // warning: assignment makes pointer from integer without a cast
6658/// pint = pfoo; // warning: assignment from incompatible pointer type
6659///
6660/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00006661/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00006662///
John McCall8cb679e2010-11-15 09:13:47 +00006663/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00006664Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006665Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCall8cb679e2010-11-15 09:13:47 +00006666 CastKind &Kind) {
John Wiegley01296292011-04-08 18:41:53 +00006667 QualType rhsType = rhs.get()->getType();
John McCall29600e12010-11-16 02:32:08 +00006668
Chris Lattnera52c2f22008-01-04 23:18:45 +00006669 // Get canonical types. We're not formatting these types, just comparing
6670 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00006671 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
6672 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00006673
John McCalle5255932011-01-31 22:28:28 +00006674 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00006675 if (lhsType == rhsType) {
6676 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00006677 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00006678 }
6679
Douglas Gregor6b754842008-10-28 00:22:11 +00006680 // If the left-hand side is a reference type, then we are in a
6681 // (rare!) case where we've allowed the use of references in C,
6682 // e.g., as a parameter type in a built-in function. In this case,
6683 // just make sure that the type referenced is compatible with the
6684 // right-hand side type. The caller is responsible for adjusting
6685 // lhsType so that the resulting expression does not have reference
6686 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006687 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00006688 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
6689 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00006690 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006691 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00006692 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00006693 }
John McCalle5255932011-01-31 22:28:28 +00006694
Nate Begemanbd956c42009-06-28 02:36:38 +00006695 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6696 // to the same ExtVector type.
6697 if (lhsType->isExtVectorType()) {
6698 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00006699 return Incompatible;
6700 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00006701 // CK_VectorSplat does T -> vector T, so first cast to the
6702 // element type.
6703 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
6704 if (elType != rhsType) {
6705 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley01296292011-04-08 18:41:53 +00006706 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00006707 }
6708 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00006709 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006710 }
Nate Begemanbd956c42009-06-28 02:36:38 +00006711 }
Mike Stump11289f42009-09-09 15:08:12 +00006712
John McCalle5255932011-01-31 22:28:28 +00006713 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00006714 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006715 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00006716 // Allow assignments of an AltiVec vector type to an equivalent GCC
6717 // vector type and vice versa
6718 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6719 Kind = CK_BitCast;
6720 return Compatible;
6721 }
6722
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006723 // If we are allowing lax vector conversions, and LHS and RHS are both
6724 // vectors, the total size only needs to be the same. This is a bitcast;
6725 // no bits are changed but the result type is different.
6726 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00006727 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00006728 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006729 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00006730 }
Chris Lattner881a2122008-01-04 23:32:24 +00006731 }
6732 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006733 }
Eli Friedman3360d892008-05-30 18:07:22 +00006734
John McCalle5255932011-01-31 22:28:28 +00006735 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00006736 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00006737 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00006738 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00006739 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006740 }
Eli Friedman3360d892008-05-30 18:07:22 +00006741
John McCalle5255932011-01-31 22:28:28 +00006742 // Conversions to normal pointers.
6743 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
6744 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00006745 if (isa<PointerType>(rhsType)) {
6746 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006747 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00006748 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006749
John McCalle5255932011-01-31 22:28:28 +00006750 // int -> T*
6751 if (rhsType->isIntegerType()) {
6752 Kind = CK_IntegralToPointer; // FIXME: null?
6753 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006754 }
John McCalle5255932011-01-31 22:28:28 +00006755
6756 // C pointers are not compatible with ObjC object pointers,
6757 // with two exceptions:
6758 if (isa<ObjCObjectPointerType>(rhsType)) {
6759 // - conversions to void*
6760 if (lhsPointer->getPointeeType()->isVoidType()) {
6761 Kind = CK_AnyPointerToObjCPointerCast;
6762 return Compatible;
6763 }
6764
6765 // - conversions from 'Class' to the redefinition type
6766 if (rhsType->isObjCClassType() &&
6767 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006768 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006769 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006770 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006771
John McCalle5255932011-01-31 22:28:28 +00006772 Kind = CK_BitCast;
6773 return IncompatiblePointer;
6774 }
6775
6776 // U^ -> void*
6777 if (rhsType->getAs<BlockPointerType>()) {
6778 if (lhsPointer->getPointeeType()->isVoidType()) {
6779 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006780 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006781 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006782 }
John McCalle5255932011-01-31 22:28:28 +00006783
Steve Naroff081c7422008-09-04 15:10:53 +00006784 return Incompatible;
6785 }
6786
John McCalle5255932011-01-31 22:28:28 +00006787 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00006788 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006789 // U^ -> T^
6790 if (rhsType->isBlockPointerType()) {
6791 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00006792 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006793 }
6794
6795 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006796 if (rhsType->isIntegerType()) {
6797 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00006798 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006799 }
6800
John McCalle5255932011-01-31 22:28:28 +00006801 // id -> T^
6802 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6803 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006804 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006805 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006806
John McCalle5255932011-01-31 22:28:28 +00006807 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006808 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00006809 if (RHSPT->getPointeeType()->isVoidType()) {
6810 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006811 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006812 }
John McCall8cb679e2010-11-15 09:13:47 +00006813
Chris Lattnera52c2f22008-01-04 23:18:45 +00006814 return Incompatible;
6815 }
6816
John McCalle5255932011-01-31 22:28:28 +00006817 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006818 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006819 // A* -> B*
6820 if (rhsType->isObjCObjectPointerType()) {
6821 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006822 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006823 }
6824
6825 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00006826 if (rhsType->isIntegerType()) {
6827 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00006828 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006829 }
6830
John McCalle5255932011-01-31 22:28:28 +00006831 // In general, C pointers are not compatible with ObjC object pointers,
6832 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00006833 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006834 // - conversions from 'void*'
6835 if (rhsType->isVoidPointerType()) {
6836 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006837 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006838 }
6839
6840 // - conversions to 'Class' from its redefinition type
6841 if (lhsType->isObjCClassType() &&
6842 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6843 Kind = CK_BitCast;
6844 return Compatible;
6845 }
6846
6847 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006848 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006849 }
John McCalle5255932011-01-31 22:28:28 +00006850
6851 // T^ -> A*
6852 if (rhsType->isBlockPointerType()) {
6853 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006854 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006855 }
6856
Steve Naroff7cae42b2009-07-10 23:34:53 +00006857 return Incompatible;
6858 }
John McCalle5255932011-01-31 22:28:28 +00006859
6860 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00006861 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006862 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006863 if (lhsType == Context.BoolTy) {
6864 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00006865 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006866 }
Eli Friedman3360d892008-05-30 18:07:22 +00006867
John McCalle5255932011-01-31 22:28:28 +00006868 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006869 if (lhsType->isIntegerType()) {
6870 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006871 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006872 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006873
Chris Lattnera52c2f22008-01-04 23:18:45 +00006874 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00006875 }
John McCalle5255932011-01-31 22:28:28 +00006876
6877 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006878 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006879 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006880 if (lhsType == Context.BoolTy) {
6881 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006882 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006883 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006884
John McCalle5255932011-01-31 22:28:28 +00006885 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006886 if (lhsType->isIntegerType()) {
6887 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006888 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006889 }
6890
Steve Naroff7cae42b2009-07-10 23:34:53 +00006891 return Incompatible;
6892 }
Eli Friedman3360d892008-05-30 18:07:22 +00006893
John McCalle5255932011-01-31 22:28:28 +00006894 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00006895 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006896 if (Context.typesAreCompatible(lhsType, rhsType)) {
6897 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00006898 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006899 }
Bill Wendling216423b2007-05-30 06:30:29 +00006900 }
John McCalle5255932011-01-31 22:28:28 +00006901
Steve Naroff98cf3e92007-06-06 18:38:38 +00006902 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00006903}
6904
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006905/// \brief Constructs a transparent union from an expression that is
6906/// used to initialize the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00006907static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006908 QualType UnionType, FieldDecl *Field) {
6909 // Build an initializer list that designates the appropriate member
6910 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00006911 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00006912 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00006913 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006914 SourceLocation());
6915 Initializer->setType(UnionType);
6916 Initializer->setInitializedFieldInUnion(Field);
6917
6918 // Build a compound literal constructing a value of the transparent
6919 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00006920 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00006921 EResult = S.Owned(
6922 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6923 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006924}
6925
6926Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006927Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
6928 QualType FromType = rExpr.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006929
Mike Stump11289f42009-09-09 15:08:12 +00006930 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006931 // transparent_union GCC extension.
6932 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006933 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006934 return Incompatible;
6935
6936 // The field to initialize within the transparent union.
6937 RecordDecl *UD = UT->getDecl();
6938 FieldDecl *InitField = 0;
6939 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006940 for (RecordDecl::field_iterator it = UD->field_begin(),
6941 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006942 it != itend; ++it) {
6943 if (it->getType()->isPointerType()) {
6944 // If the transparent union contains a pointer type, we allow:
6945 // 1) void pointer
6946 // 2) null pointer constant
6947 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006948 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley01296292011-04-08 18:41:53 +00006949 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006950 InitField = *it;
6951 break;
6952 }
Mike Stump11289f42009-09-09 15:08:12 +00006953
John Wiegley01296292011-04-08 18:41:53 +00006954 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006955 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006956 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006957 InitField = *it;
6958 break;
6959 }
6960 }
6961
John McCall8cb679e2010-11-15 09:13:47 +00006962 CastKind Kind = CK_Invalid;
John Wiegley01296292011-04-08 18:41:53 +00006963 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006964 == Compatible) {
John Wiegley01296292011-04-08 18:41:53 +00006965 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006966 InitField = *it;
6967 break;
6968 }
6969 }
6970
6971 if (!InitField)
6972 return Incompatible;
6973
John Wiegley01296292011-04-08 18:41:53 +00006974 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006975 return Compatible;
6976}
6977
Chris Lattner9bad62c2008-01-04 18:04:52 +00006978Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006979Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00006980 if (getLangOptions().CPlusPlus) {
6981 if (!lhsType->isRecordType()) {
6982 // C++ 5.17p3: If the left operand is not of class type, the
6983 // expression is implicitly converted (C++ 4) to the
6984 // cv-unqualified type of the left operand.
John Wiegley01296292011-04-08 18:41:53 +00006985 ExprResult Res = PerformImplicitConversion(rExpr.get(),
6986 lhsType.getUnqualifiedType(),
6987 AA_Assigning);
6988 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00006989 return Incompatible;
John Wiegley01296292011-04-08 18:41:53 +00006990 rExpr = move(Res);
Chris Lattner0d5640c2009-04-12 09:02:39 +00006991 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00006992 }
6993
6994 // FIXME: Currently, we fall through and treat C++ classes like C
6995 // structures.
John McCall34376a62010-12-04 03:47:34 +00006996 }
Douglas Gregor9a657932008-10-21 23:43:52 +00006997
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006998 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6999 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00007000 if ((lhsType->isPointerType() ||
7001 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00007002 lhsType->isBlockPointerType())
John Wiegley01296292011-04-08 18:41:53 +00007003 && rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007004 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00007005 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00007006 return Compatible;
7007 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007008
Chris Lattnere6dcd502007-10-16 02:55:40 +00007009 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007010 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00007011 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00007012 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00007013 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00007014 // Suppress this for references: C++ 8.5.3p5.
John Wiegley01296292011-04-08 18:41:53 +00007015 if (!lhsType->isReferenceType()) {
7016 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
7017 if (rExpr.isInvalid())
7018 return Incompatible;
7019 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00007020
John McCall8cb679e2010-11-15 09:13:47 +00007021 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007022 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00007023 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007024
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00007025 // C99 6.5.16.1p2: The value of the right operand is converted to the
7026 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00007027 // CheckAssignmentConstraints allows the left-hand side to be a reference,
7028 // so that we can use references in built-in functions even in C.
7029 // The getNonReferenceType() call makes sure that the resulting expression
7030 // does not have reference type.
John Wiegley01296292011-04-08 18:41:53 +00007031 if (result != Incompatible && rExpr.get()->getType() != lhsType)
7032 rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00007033 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007034}
7035
John Wiegley01296292011-04-08 18:41:53 +00007036QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007037 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley01296292011-04-08 18:41:53 +00007038 << lex.get()->getType() << rex.get()->getType()
7039 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00007040 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00007041}
7042
John Wiegley01296292011-04-08 18:41:53 +00007043QualType Sema::CheckVectorOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00007044 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00007045 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00007046 QualType lhsType =
John Wiegley01296292011-04-08 18:41:53 +00007047 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattner574dee62008-07-26 22:17:49 +00007048 QualType rhsType =
John Wiegley01296292011-04-08 18:41:53 +00007049 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007050
Nate Begeman191a6b12008-07-14 18:02:46 +00007051 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00007052 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00007053 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00007054
Nate Begeman191a6b12008-07-14 18:02:46 +00007055 // Handle the case of a vector & extvector type of the same size and element
7056 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00007057 if (getLangOptions().LaxVectorConversions) {
John McCall9dd450b2009-09-21 23:43:11 +00007058 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00007059 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00007060 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00007061 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007062 if (lhsType->isExtVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00007063 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007064 return lhsType;
7065 }
7066
John Wiegley01296292011-04-08 18:41:53 +00007067 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007068 return rhsType;
Eric Christophera613f562010-08-26 00:42:16 +00007069 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
7070 // If we are allowing lax vector conversions, and LHS and RHS are both
7071 // vectors, the total size only needs to be the same. This is a
7072 // bitcast; no bits are changed but the result type is different.
John Wiegley01296292011-04-08 18:41:53 +00007073 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Eric Christophera613f562010-08-26 00:42:16 +00007074 return lhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00007075 }
Eric Christophera613f562010-08-26 00:42:16 +00007076 }
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00007077 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +00007078 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007079
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007080 // Handle the case of equivalent AltiVec and GCC vector types
7081 if (lhsType->isVectorType() && rhsType->isVectorType() &&
7082 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John Wiegley01296292011-04-08 18:41:53 +00007083 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007084 return rhsType;
7085 }
7086
Nate Begemanbd956c42009-06-28 02:36:38 +00007087 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
7088 // swap back (so that we don't reverse the inputs to a subtract, for instance.
7089 bool swapped = false;
7090 if (rhsType->isExtVectorType()) {
7091 swapped = true;
7092 std::swap(rex, lex);
7093 std::swap(rhsType, lhsType);
7094 }
Mike Stump11289f42009-09-09 15:08:12 +00007095
Nate Begeman886448d2009-06-28 19:12:57 +00007096 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00007097 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00007098 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00007099 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00007100 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
7101 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00007102 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00007103 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00007104 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00007105 if (swapped) std::swap(rex, lex);
7106 return lhsType;
7107 }
7108 }
7109 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
7110 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00007111 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
7112 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00007113 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00007114 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00007115 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00007116 if (swapped) std::swap(rex, lex);
7117 return lhsType;
7118 }
Nate Begeman330aaa72007-12-30 02:59:45 +00007119 }
7120 }
Mike Stump11289f42009-09-09 15:08:12 +00007121
Nate Begeman886448d2009-06-28 19:12:57 +00007122 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00007123 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley01296292011-04-08 18:41:53 +00007124 << lex.get()->getType() << rex.get()->getType()
7125 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00007126 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00007127}
7128
Chris Lattnerfaa54172010-01-12 21:23:57 +00007129QualType Sema::CheckMultiplyDivideOperands(
John Wiegley01296292011-04-08 18:41:53 +00007130 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
7131 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00007132 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007133
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007134 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00007135 if (lex.isInvalid() || rex.isInvalid())
7136 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007137
John Wiegley01296292011-04-08 18:41:53 +00007138 if (!lex.get()->getType()->isArithmeticType() ||
7139 !rex.get()->getType()->isArithmeticType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00007140 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007141
Chris Lattnerfaa54172010-01-12 21:23:57 +00007142 // Check for division by zero.
7143 if (isDiv &&
John Wiegley01296292011-04-08 18:41:53 +00007144 rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
7145 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
7146 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007147
Chris Lattnerfaa54172010-01-12 21:23:57 +00007148 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00007149}
7150
Chris Lattnerfaa54172010-01-12 21:23:57 +00007151QualType Sema::CheckRemainderOperands(
John Wiegley01296292011-04-08 18:41:53 +00007152 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
7153 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
7154 if (lex.get()->getType()->hasIntegerRepresentation() &&
7155 rex.get()->getType()->hasIntegerRepresentation())
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00007156 return CheckVectorOperands(Loc, lex, rex);
7157 return InvalidOperands(Loc, lex, rex);
7158 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007159
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007160 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00007161 if (lex.isInvalid() || rex.isInvalid())
7162 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007163
John Wiegley01296292011-04-08 18:41:53 +00007164 if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00007165 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007166
Chris Lattnerfaa54172010-01-12 21:23:57 +00007167 // Check for remainder by zero.
John Wiegley01296292011-04-08 18:41:53 +00007168 if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
7169 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
7170 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007171
Chris Lattnerfaa54172010-01-12 21:23:57 +00007172 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007173}
7174
Chris Lattnerfaa54172010-01-12 21:23:57 +00007175QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00007176 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
7177 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007178 QualType compType = CheckVectorOperands(Loc, lex, rex);
7179 if (CompLHSTy) *CompLHSTy = compType;
7180 return compType;
7181 }
Steve Naroff7a5af782007-07-13 16:58:59 +00007182
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007183 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007184 if (lex.isInvalid() || rex.isInvalid())
7185 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00007186
Steve Naroffe4718892007-04-27 18:30:00 +00007187 // handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00007188 if (lex.get()->getType()->isArithmeticType() &&
7189 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007190 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007191 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007192 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00007193
Eli Friedman8e122982008-05-18 18:08:51 +00007194 // Put any potential pointer into PExp
John Wiegley01296292011-04-08 18:41:53 +00007195 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00007196 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00007197 std::swap(PExp, IExp);
7198
Steve Naroff6b712a72009-07-14 18:25:06 +00007199 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00007200
Eli Friedman8e122982008-05-18 18:08:51 +00007201 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00007202 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00007203
Chris Lattner12bdebb2009-04-24 23:50:08 +00007204 // Check for arithmetic on pointers to incomplete types.
7205 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00007206 if (getLangOptions().CPlusPlus) {
7207 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00007208 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00007209 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00007210 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00007211
7212 // GNU extension: arithmetic on pointer to void
7213 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00007214 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00007215 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00007216 if (getLangOptions().CPlusPlus) {
7217 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00007218 << lex.get()->getType() << lex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007219 return QualType();
7220 }
7221
7222 // GNU extension: arithmetic on pointer to function
7223 Diag(Loc, diag::ext_gnu_ptr_func_arith)
John Wiegley01296292011-04-08 18:41:53 +00007224 << lex.get()->getType() << lex.get()->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00007225 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00007226 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00007227 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00007228 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00007229 PExp->getType()->isObjCObjectPointerType()) &&
7230 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00007231 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
7232 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00007233 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00007234 return QualType();
7235 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00007236 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00007237 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00007238 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
7239 << PointeeTy << PExp->getSourceRange();
7240 return QualType();
7241 }
Mike Stump11289f42009-09-09 15:08:12 +00007242
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007243 if (CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00007244 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman629ffb92009-08-20 04:21:42 +00007245 if (LHSTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +00007246 LHSTy = lex.get()->getType();
Eli Friedman629ffb92009-08-20 04:21:42 +00007247 if (LHSTy->isPromotableIntegerType())
7248 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00007249 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007250 *CompLHSTy = LHSTy;
7251 }
Eli Friedman8e122982008-05-18 18:08:51 +00007252 return PExp->getType();
7253 }
7254 }
7255
Chris Lattner326f7572008-11-18 01:30:42 +00007256 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007257}
7258
Chris Lattner2a3569b2008-04-07 05:30:13 +00007259// C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00007260QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007261 SourceLocation Loc, QualType* CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00007262 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007263 QualType compType = CheckVectorOperands(Loc, lex, rex);
7264 if (CompLHSTy) *CompLHSTy = compType;
7265 return compType;
7266 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007267
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007268 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007269 if (lex.isInvalid() || rex.isInvalid())
7270 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007271
Chris Lattner4d62f422007-12-09 21:53:25 +00007272 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007273
Chris Lattner4d62f422007-12-09 21:53:25 +00007274 // Handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00007275 if (lex.get()->getType()->isArithmeticType() &&
7276 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007277 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007278 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007279 }
Mike Stump11289f42009-09-09 15:08:12 +00007280
Chris Lattner4d62f422007-12-09 21:53:25 +00007281 // Either ptr - int or ptr - ptr.
John Wiegley01296292011-04-08 18:41:53 +00007282 if (lex.get()->getType()->isAnyPointerType()) {
7283 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007284
Douglas Gregorac1fb652009-03-24 19:52:54 +00007285 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007286
Douglas Gregorac1fb652009-03-24 19:52:54 +00007287 bool ComplainAboutVoid = false;
7288 Expr *ComplainAboutFunc = 0;
7289 if (lpointee->isVoidType()) {
7290 if (getLangOptions().CPlusPlus) {
7291 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00007292 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007293 return QualType();
7294 }
7295
7296 // GNU C extension: arithmetic on pointer to void
7297 ComplainAboutVoid = true;
7298 } else if (lpointee->isFunctionType()) {
7299 if (getLangOptions().CPlusPlus) {
7300 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00007301 << lex.get()->getType() << lex.get()->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00007302 return QualType();
7303 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00007304
7305 // GNU C extension: arithmetic on pointer to function
John Wiegley01296292011-04-08 18:41:53 +00007306 ComplainAboutFunc = lex.get();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007307 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00007308 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00007309 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley01296292011-04-08 18:41:53 +00007310 << lex.get()->getSourceRange()
7311 << lex.get()->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00007312 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00007313
Chris Lattner12bdebb2009-04-24 23:50:08 +00007314 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00007315 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00007316 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley01296292011-04-08 18:41:53 +00007317 << lpointee << lex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00007318 return QualType();
7319 }
Mike Stump11289f42009-09-09 15:08:12 +00007320
Chris Lattner4d62f422007-12-09 21:53:25 +00007321 // The result type of a pointer-int computation is the pointer type.
John Wiegley01296292011-04-08 18:41:53 +00007322 if (rex.get()->getType()->isIntegerType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00007323 if (ComplainAboutVoid)
7324 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00007325 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007326 if (ComplainAboutFunc)
7327 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00007328 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00007329 << ComplainAboutFunc->getSourceRange();
7330
John Wiegley01296292011-04-08 18:41:53 +00007331 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
7332 return lex.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007333 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007334
Chris Lattner4d62f422007-12-09 21:53:25 +00007335 // Handle pointer-pointer subtractions.
John Wiegley01296292011-04-08 18:41:53 +00007336 if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00007337 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007338
Douglas Gregorac1fb652009-03-24 19:52:54 +00007339 // RHS must be a completely-type object type.
7340 // Handle the GNU void* extension.
7341 if (rpointee->isVoidType()) {
7342 if (getLangOptions().CPlusPlus) {
7343 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00007344 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007345 return QualType();
7346 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007347
Douglas Gregorac1fb652009-03-24 19:52:54 +00007348 ComplainAboutVoid = true;
7349 } else if (rpointee->isFunctionType()) {
7350 if (getLangOptions().CPlusPlus) {
7351 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00007352 << rex.get()->getType() << rex.get()->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00007353 return QualType();
7354 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00007355
7356 // GNU extension: arithmetic on pointer to function
7357 if (!ComplainAboutFunc)
John Wiegley01296292011-04-08 18:41:53 +00007358 ComplainAboutFunc = rex.get();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007359 } else if (!rpointee->isDependentType() &&
7360 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00007361 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley01296292011-04-08 18:41:53 +00007362 << rex.get()->getSourceRange()
7363 << rex.get()->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00007364 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007365
Eli Friedman168fe152009-05-16 13:54:38 +00007366 if (getLangOptions().CPlusPlus) {
7367 // Pointee types must be the same: C++ [expr.add]
7368 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7369 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00007370 << lex.get()->getType() << rex.get()->getType()
7371 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00007372 return QualType();
7373 }
7374 } else {
7375 // Pointee types must be compatible C99 6.5.6p3
7376 if (!Context.typesAreCompatible(
7377 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7378 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7379 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00007380 << lex.get()->getType() << rex.get()->getType()
7381 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00007382 return QualType();
7383 }
Chris Lattner4d62f422007-12-09 21:53:25 +00007384 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007385
Douglas Gregorac1fb652009-03-24 19:52:54 +00007386 if (ComplainAboutVoid)
7387 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00007388 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007389 if (ComplainAboutFunc)
7390 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00007391 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00007392 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007393
John Wiegley01296292011-04-08 18:41:53 +00007394 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00007395 return Context.getPointerDiffType();
7396 }
7397 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007398
Chris Lattner326f7572008-11-18 01:30:42 +00007399 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00007400}
7401
Douglas Gregor0bf31402010-10-08 23:50:27 +00007402static bool isScopedEnumerationType(QualType T) {
7403 if (const EnumType *ET = dyn_cast<EnumType>(T))
7404 return ET->getDecl()->isScoped();
7405 return false;
7406}
7407
John Wiegley01296292011-04-08 18:41:53 +00007408static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007409 SourceLocation Loc, unsigned Opc,
7410 QualType LHSTy) {
7411 llvm::APSInt Right;
7412 // Check right/shifter operand
John Wiegley01296292011-04-08 18:41:53 +00007413 if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007414 return;
7415
7416 if (Right.isNegative()) {
John Wiegley01296292011-04-08 18:41:53 +00007417 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00007418 S.PDiag(diag::warn_shift_negative)
John Wiegley01296292011-04-08 18:41:53 +00007419 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007420 return;
7421 }
7422 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley01296292011-04-08 18:41:53 +00007423 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007424 if (Right.uge(LeftBits)) {
John Wiegley01296292011-04-08 18:41:53 +00007425 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00007426 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley01296292011-04-08 18:41:53 +00007427 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007428 return;
7429 }
7430 if (Opc != BO_Shl)
7431 return;
7432
7433 // When left shifting an ICE which is signed, we can check for overflow which
7434 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7435 // integers have defined behavior modulo one more than the maximum value
7436 // representable in the result type, so never warn for those.
7437 llvm::APSInt Left;
John Wiegley01296292011-04-08 18:41:53 +00007438 if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007439 LHSTy->hasUnsignedIntegerRepresentation())
7440 return;
7441 llvm::APInt ResultBits =
7442 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7443 if (LeftBits.uge(ResultBits))
7444 return;
7445 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7446 Result = Result.shl(Right);
7447
Ted Kremenek70f05fd2011-06-15 00:54:52 +00007448 // Print the bit representation of the signed integer as an unsigned
7449 // hexadecimal number.
7450 llvm::SmallString<40> HexResult;
7451 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7452
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007453 // If we are only missing a sign bit, this is less likely to result in actual
7454 // bugs -- if the result is cast back to an unsigned type, it will have the
7455 // expected value. Thus we place this behind a different warning that can be
7456 // turned off separately if needed.
7457 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00007458 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
7459 << HexResult.str() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00007460 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007461 return;
7462 }
7463
7464 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Ted Kremenek70f05fd2011-06-15 00:54:52 +00007465 << HexResult.str() << Result.getMinSignedBits() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00007466 << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007467}
7468
Chris Lattner2a3569b2008-04-07 05:30:13 +00007469// C99 6.5.7
John Wiegley01296292011-04-08 18:41:53 +00007470QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007471 unsigned Opc, bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00007472 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley01296292011-04-08 18:41:53 +00007473 if (!lex.get()->getType()->hasIntegerRepresentation() ||
7474 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00007475 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007476
Douglas Gregor0bf31402010-10-08 23:50:27 +00007477 // C++0x: Don't allow scoped enums. FIXME: Use something better than
7478 // hasIntegerRepresentation() above instead of this.
John Wiegley01296292011-04-08 18:41:53 +00007479 if (isScopedEnumerationType(lex.get()->getType()) ||
7480 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00007481 return InvalidOperands(Loc, lex, rex);
7482 }
7483
Nate Begemane46ee9a2009-10-25 02:26:48 +00007484 // Vector shifts promote their scalar inputs to vector type.
John Wiegley01296292011-04-08 18:41:53 +00007485 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Nate Begemane46ee9a2009-10-25 02:26:48 +00007486 return CheckVectorOperands(Loc, lex, rex);
7487
Chris Lattner5c11c412007-12-12 05:47:28 +00007488 // Shifts don't perform usual arithmetic conversions, they just do integer
7489 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007490
John McCall57cdd882010-12-16 19:28:59 +00007491 // For the LHS, do usual unary conversions, but then reset them away
7492 // if this is a compound assignment.
John Wiegley01296292011-04-08 18:41:53 +00007493 ExprResult old_lex = lex;
7494 lex = UsualUnaryConversions(lex.take());
7495 if (lex.isInvalid())
7496 return QualType();
7497 QualType LHSTy = lex.get()->getType();
John McCall57cdd882010-12-16 19:28:59 +00007498 if (isCompAssign) lex = old_lex;
7499
7500 // The RHS is simpler.
John Wiegley01296292011-04-08 18:41:53 +00007501 rex = UsualUnaryConversions(rex.take());
7502 if (rex.isInvalid())
7503 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007504
Ryan Flynnf53fab82009-08-07 16:20:20 +00007505 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007506 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00007507
Chris Lattner5c11c412007-12-12 05:47:28 +00007508 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007509 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00007510}
7511
Chandler Carruth17773fc2010-07-10 12:30:03 +00007512static bool IsWithinTemplateSpecialization(Decl *D) {
7513 if (DeclContext *DC = D->getDeclContext()) {
7514 if (isa<ClassTemplateSpecializationDecl>(DC))
7515 return true;
7516 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7517 return FD->isFunctionTemplateSpecialization();
7518 }
7519 return false;
7520}
7521
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007522// C99 6.5.8, C++ [expr.rel]
John Wiegley01296292011-04-08 18:41:53 +00007523QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007524 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00007525 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007526
Chris Lattner9a152e22009-12-05 05:40:13 +00007527 // Handle vector comparisons separately.
John Wiegley01296292011-04-08 18:41:53 +00007528 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00007529 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007530
John Wiegley01296292011-04-08 18:41:53 +00007531 QualType lType = lex.get()->getType();
7532 QualType rType = rex.get()->getType();
Douglas Gregor1beec452011-03-12 01:48:56 +00007533
John Wiegley01296292011-04-08 18:41:53 +00007534 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
7535 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00007536 QualType LHSStrippedType = LHSStripped->getType();
7537 QualType RHSStrippedType = RHSStripped->getType();
7538
Douglas Gregor1beec452011-03-12 01:48:56 +00007539
7540
Chandler Carruth712563b2011-02-17 08:37:06 +00007541 // Two different enums will raise a warning when compared.
7542 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
7543 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
7544 if (LHSEnumType->getDecl()->getIdentifier() &&
7545 RHSEnumType->getDecl()->getIdentifier() &&
7546 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
7547 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7548 << LHSStrippedType << RHSStrippedType
John Wiegley01296292011-04-08 18:41:53 +00007549 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth712563b2011-02-17 08:37:06 +00007550 }
7551 }
7552 }
7553
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007554 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00007555 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley01296292011-04-08 18:41:53 +00007556 !lex.get()->getLocStart().isMacroID() &&
7557 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00007558 // For non-floating point types, check for self-comparisons of the form
7559 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7560 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00007561 //
7562 // NOTE: Don't warn about comparison expressions resulting from macro
7563 // expansion. Also don't warn about comparisons which are only self
7564 // comparisons within a template specialization. The warnings should catch
7565 // obvious cases in the definition of the template anyways. The idea is to
7566 // warn when the typed comparison operator will always evaluate to the same
7567 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00007568 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00007569 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00007570 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00007571 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00007572 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00007573 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00007574 << (Opc == BO_EQ
7575 || Opc == BO_LE
7576 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00007577 } else if (lType->isArrayType() && rType->isArrayType() &&
7578 !DRL->getDecl()->getType()->isReferenceType() &&
7579 !DRR->getDecl()->getType()->isReferenceType()) {
7580 // what is it always going to eval to?
7581 char always_evals_to;
7582 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00007583 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00007584 always_evals_to = 0; // false
7585 break;
John McCalle3027922010-08-25 11:45:40 +00007586 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00007587 always_evals_to = 1; // true
7588 break;
7589 default:
7590 // best we can say is 'a constant'
7591 always_evals_to = 2; // e.g. array1 <= array2
7592 break;
7593 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00007594 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00007595 << 1 // array
7596 << always_evals_to);
7597 }
7598 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00007599 }
Mike Stump11289f42009-09-09 15:08:12 +00007600
Chris Lattner222b8bd2009-03-08 19:39:53 +00007601 if (isa<CastExpr>(LHSStripped))
7602 LHSStripped = LHSStripped->IgnoreParenCasts();
7603 if (isa<CastExpr>(RHSStripped))
7604 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00007605
Chris Lattner222b8bd2009-03-08 19:39:53 +00007606 // Warn about comparisons against a string constant (unless the other
7607 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007608 Expr *literalString = 0;
7609 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00007610 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007611 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007612 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00007613 literalString = lex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007614 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00007615 } else if ((isa<StringLiteral>(RHSStripped) ||
7616 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007617 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007618 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00007619 literalString = rex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007620 literalStringStripped = RHSStripped;
7621 }
7622
7623 if (literalString) {
7624 std::string resultComparison;
7625 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007626 case BO_LT: resultComparison = ") < 0"; break;
7627 case BO_GT: resultComparison = ") > 0"; break;
7628 case BO_LE: resultComparison = ") <= 0"; break;
7629 case BO_GE: resultComparison = ") >= 0"; break;
7630 case BO_EQ: resultComparison = ") == 0"; break;
7631 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007632 default: assert(false && "Invalid comparison operator");
7633 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007634
Ted Kremenek3427fac2011-02-23 01:52:04 +00007635 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00007636 PDiag(diag::warn_stringcompare)
7637 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00007638 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007639 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00007640 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007641
Douglas Gregorec170db2010-06-08 19:50:34 +00007642 // C99 6.5.8p3 / C99 6.5.9p4
John Wiegley01296292011-04-08 18:41:53 +00007643 if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
Douglas Gregorec170db2010-06-08 19:50:34 +00007644 UsualArithmeticConversions(lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00007645 if (lex.isInvalid() || rex.isInvalid())
7646 return QualType();
7647 }
Douglas Gregorec170db2010-06-08 19:50:34 +00007648 else {
John Wiegley01296292011-04-08 18:41:53 +00007649 lex = UsualUnaryConversions(lex.take());
7650 if (lex.isInvalid())
7651 return QualType();
7652
7653 rex = UsualUnaryConversions(rex.take());
7654 if (rex.isInvalid())
7655 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007656 }
7657
John Wiegley01296292011-04-08 18:41:53 +00007658 lType = lex.get()->getType();
7659 rType = rex.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007660
Douglas Gregorca63811b2008-11-19 03:25:36 +00007661 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007662 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00007663
Chris Lattnerb620c342007-08-26 01:18:55 +00007664 if (isRelational) {
7665 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007666 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007667 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00007668 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007669 if (lType->hasFloatingRepresentation())
John Wiegley01296292011-04-08 18:41:53 +00007670 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007671
Chris Lattnerb620c342007-08-26 01:18:55 +00007672 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007673 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007674 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007675
John Wiegley01296292011-04-08 18:41:53 +00007676 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007677 Expr::NPC_ValueDependentIsNull);
John Wiegley01296292011-04-08 18:41:53 +00007678 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007679 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007680
Douglas Gregorf267edd2010-06-15 21:38:40 +00007681 // All of the following pointer-related warnings are GCC extensions, except
7682 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00007683 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00007684 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007685 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00007686 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007687 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007688
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007689 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00007690 if (LCanPointeeTy == RCanPointeeTy)
7691 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007692 if (!isRelational &&
7693 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7694 // Valid unless comparison between non-null pointer and function pointer
7695 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00007696 // In a SFINAE context, we treat this as a hard error to maintain
7697 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007698 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7699 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00007700 Diag(Loc,
7701 isSFINAEContext()?
7702 diag::err_typecheck_comparison_of_fptr_to_void
7703 : diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00007704 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007705
7706 if (isSFINAEContext())
7707 return QualType();
7708
John Wiegley01296292011-04-08 18:41:53 +00007709 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007710 return ResultTy;
7711 }
7712 }
Anders Carlssona95069c2010-11-04 03:17:43 +00007713
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007714 // C++ [expr.rel]p2:
7715 // [...] Pointer conversions (4.10) and qualification
7716 // conversions (4.4) are performed on pointer operands (or on
7717 // a pointer operand and a null pointer constant) to bring
7718 // them to their composite pointer type. [...]
7719 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007720 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007721 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007722 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007723 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007724 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007725 if (T.isNull()) {
7726 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007727 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007728 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007729 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007730 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007731 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007732 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00007733 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007734 }
7735
John Wiegley01296292011-04-08 18:41:53 +00007736 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7737 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007738 return ResultTy;
7739 }
Eli Friedman16c209612009-08-23 00:27:47 +00007740 // C99 6.5.9p2 and C99 6.5.8p2
7741 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7742 RCanPointeeTy.getUnqualifiedType())) {
7743 // Valid unless a relational comparison of function pointers
7744 if (isRelational && LCanPointeeTy->isFunctionType()) {
7745 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007746 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007747 }
7748 } else if (!isRelational &&
7749 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7750 // Valid unless comparison between non-null pointer and function pointer
7751 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7752 && !LHSIsNull && !RHSIsNull) {
7753 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00007754 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007755 }
7756 } else {
7757 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00007758 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007759 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00007760 }
John McCall7684dde2011-03-11 04:25:25 +00007761 if (LCanPointeeTy != RCanPointeeTy) {
7762 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007763 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007764 else
John Wiegley01296292011-04-08 18:41:53 +00007765 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007766 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00007767 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00007768 }
Mike Stump11289f42009-09-09 15:08:12 +00007769
Sebastian Redl576fd422009-05-10 18:38:11 +00007770 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00007771 // Comparison of nullptr_t with itself.
7772 if (lType->isNullPtrType() && rType->isNullPtrType())
7773 return ResultTy;
7774
Mike Stump11289f42009-09-09 15:08:12 +00007775 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007776 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00007777 if (RHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00007778 ((lType->isAnyPointerType() || lType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00007779 (!isRelational &&
7780 (lType->isMemberPointerType() || lType->isBlockPointerType())))) {
John Wiegley01296292011-04-08 18:41:53 +00007781 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00007782 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007783 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007784 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007785 return ResultTy;
7786 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007787 if (LHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00007788 ((rType->isAnyPointerType() || rType->isNullPtrType()) ||
Douglas Gregor3e85c9c2011-06-16 18:52:05 +00007789 (!isRelational &&
7790 (rType->isMemberPointerType() || rType->isBlockPointerType())))) {
John Wiegley01296292011-04-08 18:41:53 +00007791 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00007792 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007793 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007794 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007795 return ResultTy;
7796 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007797
7798 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00007799 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007800 lType->isMemberPointerType() && rType->isMemberPointerType()) {
7801 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00007802 // In addition, pointers to members can be compared, or a pointer to
7803 // member and a null pointer constant. Pointer to member conversions
7804 // (4.11) and qualification conversions (4.4) are performed to bring
7805 // them to a common type. If one operand is a null pointer constant,
7806 // the common type is the type of the other operand. Otherwise, the
7807 // common type is a pointer to member type similar (4.4) to the type
7808 // of one of the operands, with a cv-qualification signature (4.4)
7809 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007810 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007811 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007812 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007813 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007814 if (T.isNull()) {
7815 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007816 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007817 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007818 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007819 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007820 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007821 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00007822 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007823 }
Mike Stump11289f42009-09-09 15:08:12 +00007824
John Wiegley01296292011-04-08 18:41:53 +00007825 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7826 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007827 return ResultTy;
7828 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007829
7830 // Handle scoped enumeration types specifically, since they don't promote
7831 // to integers.
John Wiegley01296292011-04-08 18:41:53 +00007832 if (lex.get()->getType()->isEnumeralType() &&
7833 Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007834 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00007835 }
Mike Stump11289f42009-09-09 15:08:12 +00007836
Steve Naroff081c7422008-09-04 15:10:53 +00007837 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00007838 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007839 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7840 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007841
Steve Naroff081c7422008-09-04 15:10:53 +00007842 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007843 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007844 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00007845 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007846 }
John Wiegley01296292011-04-08 18:41:53 +00007847 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007848 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007849 }
John Wiegley01296292011-04-08 18:41:53 +00007850
Steve Naroffe18f94c2008-09-28 01:11:11 +00007851 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00007852 if (!isRelational
7853 && ((lType->isBlockPointerType() && rType->isPointerType())
7854 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007855 if (!LHSIsNull && !RHSIsNull) {
John McCall7684dde2011-03-11 04:25:25 +00007856 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007857 ->getPointeeType()->isVoidType())
John McCall7684dde2011-03-11 04:25:25 +00007858 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007859 ->getPointeeType()->isVoidType())))
7860 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00007861 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007862 }
John McCall7684dde2011-03-11 04:25:25 +00007863 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007864 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007865 else
John Wiegley01296292011-04-08 18:41:53 +00007866 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007867 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007868 }
Steve Naroff081c7422008-09-04 15:10:53 +00007869
John McCall7684dde2011-03-11 04:25:25 +00007870 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
7871 const PointerType *LPT = lType->getAs<PointerType>();
7872 const PointerType *RPT = rType->getAs<PointerType>();
7873 if (LPT || RPT) {
7874 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7875 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007876
Steve Naroff753567f2008-11-17 19:49:16 +00007877 if (!LPtrToVoid && !RPtrToVoid &&
7878 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007879 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007880 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007881 }
John McCall7684dde2011-03-11 04:25:25 +00007882 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007883 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007884 else
John Wiegley01296292011-04-08 18:41:53 +00007885 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007886 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007887 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007888 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007889 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007890 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007891 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
John McCall7684dde2011-03-11 04:25:25 +00007892 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007893 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007894 else
John Wiegley01296292011-04-08 18:41:53 +00007895 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007896 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007897 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007898 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007899 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7900 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007901 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007902 bool isError = false;
7903 if ((LHSIsNull && lType->isIntegerType()) ||
7904 (RHSIsNull && rType->isIntegerType())) {
7905 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007906 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007907 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007908 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007909 else if (getLangOptions().CPlusPlus) {
7910 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7911 isError = true;
7912 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007913 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007914
Chris Lattnerd99bd522009-08-23 00:03:44 +00007915 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007916 Diag(Loc, DiagID)
John Wiegley01296292011-04-08 18:41:53 +00007917 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007918 if (isError)
7919 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007920 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007921
7922 if (lType->isIntegerType())
John Wiegley01296292011-04-08 18:41:53 +00007923 lex = ImpCastExprToType(lex.take(), rType,
John McCalle84af4e2010-11-13 01:35:44 +00007924 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007925 else
John Wiegley01296292011-04-08 18:41:53 +00007926 rex = ImpCastExprToType(rex.take(), lType,
John McCalle84af4e2010-11-13 01:35:44 +00007927 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007928 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007929 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007930
Steve Naroff4b191572008-09-04 16:56:14 +00007931 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00007932 if (!isRelational && RHSIsNull
7933 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley01296292011-04-08 18:41:53 +00007934 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007935 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007936 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00007937 if (!isRelational && LHSIsNull
7938 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley01296292011-04-08 18:41:53 +00007939 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007940 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007941 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007942
Chris Lattner326f7572008-11-18 01:30:42 +00007943 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007944}
7945
Nate Begeman191a6b12008-07-14 18:02:46 +00007946/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007947/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007948/// like a scalar comparison, a vector comparison produces a vector of integer
7949/// types.
John Wiegley01296292011-04-08 18:41:53 +00007950QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner326f7572008-11-18 01:30:42 +00007951 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00007952 bool isRelational) {
7953 // Check to make sure we're operating on vectors of the same type and width,
7954 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00007955 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00007956 if (vType.isNull())
7957 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007958
John Wiegley01296292011-04-08 18:41:53 +00007959 QualType lType = lex.get()->getType();
7960 QualType rType = rex.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007961
Anton Yartsev530deb92011-03-27 15:36:07 +00007962 // If AltiVec, the comparison results in a numeric type, i.e.
7963 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00007964 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00007965 return Context.getLogicalOperationType();
7966
Nate Begeman191a6b12008-07-14 18:02:46 +00007967 // For non-floating point types, check for self-comparisons of the form
7968 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7969 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007970 if (!lType->hasFloatingRepresentation()) {
John Wiegley01296292011-04-08 18:41:53 +00007971 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
7972 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00007973 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007974 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007975 PDiag(diag::warn_comparison_always)
7976 << 0 // self-
7977 << 2 // "a constant"
7978 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007979 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007980
Nate Begeman191a6b12008-07-14 18:02:46 +00007981 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007982 if (!isRelational && lType->hasFloatingRepresentation()) {
7983 assert (rType->hasFloatingRepresentation());
John Wiegley01296292011-04-08 18:41:53 +00007984 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00007985 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007986
Nate Begeman191a6b12008-07-14 18:02:46 +00007987 // Return the type for the comparison, which is the same as vector type for
7988 // integer vectors, or an integer type of identical size and number of
7989 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007990 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00007991 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007992
John McCall9dd450b2009-09-21 23:43:11 +00007993 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00007994 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007995 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00007996 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00007997 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007998 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7999
Mike Stump4e1f26a2009-02-19 03:04:26 +00008000 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008001 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00008002 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
8003}
8004
Steve Naroff218bc2b2007-05-04 21:54:46 +00008005inline QualType Sema::CheckBitwiseOperands(
John Wiegley01296292011-04-08 18:41:53 +00008006 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
8007 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
8008 if (lex.get()->getType()->hasIntegerRepresentation() &&
8009 rex.get()->getType()->hasIntegerRepresentation())
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00008010 return CheckVectorOperands(Loc, lex, rex);
8011
8012 return InvalidOperands(Loc, lex, rex);
8013 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00008014
John Wiegley01296292011-04-08 18:41:53 +00008015 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
8016 QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
8017 if (lexResult.isInvalid() || rexResult.isInvalid())
8018 return QualType();
8019 lex = lexResult.take();
8020 rex = rexResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008021
John Wiegley01296292011-04-08 18:41:53 +00008022 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
8023 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00008024 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00008025 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00008026}
8027
Steve Naroff218bc2b2007-05-04 21:54:46 +00008028inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley01296292011-04-08 18:41:53 +00008029 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00008030
8031 // Diagnose cases where the user write a logical and/or but probably meant a
8032 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
8033 // is a constant.
John Wiegley01296292011-04-08 18:41:53 +00008034 if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
8035 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00008036 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00008037 !Loc.isMacroID()) {
8038 // If the RHS can be constant folded, and if it constant folds to something
8039 // that isn't 0 or 1 (which indicate a potential logical operation that
8040 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00008041 // Parens on the RHS are ignored.
Chris Lattner938533d2010-07-24 01:10:11 +00008042 Expr::EvalResult Result;
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00008043 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
8044 if ((getLangOptions().Bool && !rex.get()->getType()->isBooleanType()) ||
8045 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
8046 Diag(Loc, diag::warn_logical_instead_of_bitwise)
8047 << rex.get()->getSourceRange()
8048 << (Opc == BO_LAnd ? "&&" : "||")
8049 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00008050 }
8051 }
Chris Lattner8406c512010-07-13 19:41:32 +00008052
Anders Carlsson2e7bc112009-11-23 21:47:44 +00008053 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00008054 lex = UsualUnaryConversions(lex.take());
8055 if (lex.isInvalid())
8056 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008057
John Wiegley01296292011-04-08 18:41:53 +00008058 rex = UsualUnaryConversions(rex.take());
8059 if (rex.isInvalid())
8060 return QualType();
8061
8062 if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00008063 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008064
Anders Carlsson2e7bc112009-11-23 21:47:44 +00008065 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00008066 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008067
John McCall4a2429a2010-06-04 00:29:51 +00008068 // The following is safe because we only use this method for
8069 // non-overloadable operands.
8070
Anders Carlsson2e7bc112009-11-23 21:47:44 +00008071 // C++ [expr.log.and]p1
8072 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00008073 // The operands are both contextually converted to type bool.
John Wiegley01296292011-04-08 18:41:53 +00008074 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
8075 if (lexRes.isInvalid())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00008076 return InvalidOperands(Loc, lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00008077 lex = move(lexRes);
8078
8079 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
8080 if (rexRes.isInvalid())
8081 return InvalidOperands(Loc, lex, rex);
8082 rex = move(rexRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008083
Anders Carlsson2e7bc112009-11-23 21:47:44 +00008084 // C++ [expr.log.and]p2
8085 // C++ [expr.log.or]p2
8086 // The result is a bool.
8087 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00008088}
8089
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00008090/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
8091/// is a read-only property; return true if so. A readonly property expression
8092/// depends on various declarations and thus must be treated specially.
8093///
Mike Stump11289f42009-09-09 15:08:12 +00008094static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00008095 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
8096 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00008097 if (PropExpr->isImplicitProperty()) return false;
8098
8099 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
8100 QualType BaseType = PropExpr->isSuperReceiver() ?
8101 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00008102 PropExpr->getBase()->getType();
8103
John McCallb7bd14f2010-12-02 01:19:52 +00008104 if (const ObjCObjectPointerType *OPT =
8105 BaseType->getAsObjCInterfacePointerType())
8106 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
8107 if (S.isPropertyReadonly(PDecl, IFace))
8108 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00008109 }
8110 return false;
8111}
8112
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00008113static bool IsConstProperty(Expr *E, Sema &S) {
8114 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
8115 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
8116 if (PropExpr->isImplicitProperty()) return false;
8117
8118 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
8119 QualType T = PDecl->getType();
8120 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00008121 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00008122 CanQualType CT = S.Context.getCanonicalType(T);
8123 return CT.isConstQualified();
8124 }
8125 return false;
8126}
8127
Fariborz Jahanian071caef2011-03-26 19:48:30 +00008128static bool IsReadonlyMessage(Expr *E, Sema &S) {
8129 if (E->getStmtClass() != Expr::MemberExprClass)
8130 return false;
8131 const MemberExpr *ME = cast<MemberExpr>(E);
8132 NamedDecl *Member = ME->getMemberDecl();
8133 if (isa<FieldDecl>(Member)) {
8134 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
8135 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
8136 return false;
8137 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
8138 }
8139 return false;
8140}
8141
Chris Lattner30bd3272008-11-18 01:22:49 +00008142/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
8143/// emit an error and return true. If so, return false.
8144static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00008145 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00008146 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00008147 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00008148 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
8149 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00008150 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
8151 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00008152 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
8153 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00008154 if (IsLV == Expr::MLV_Valid)
8155 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008156
Chris Lattner30bd3272008-11-18 01:22:49 +00008157 unsigned Diag = 0;
8158 bool NeedType = false;
8159 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00008160 case Expr::MLV_ConstQualified:
8161 Diag = diag::err_typecheck_assign_const;
8162
8163 // In ARC, use some specialized diagnostics for the times when we
8164 // infer const.
8165 if (S.getLangOptions().ObjCAutoRefCount) {
8166 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
8167 if (declRef && isa<VarDecl>(declRef->getDecl())) {
8168 VarDecl *var = cast<VarDecl>(declRef->getDecl());
8169
8170 // If the variable wasn't written with 'const', there are some
8171 // cases where we infer const anyway:
8172 // - self
8173 // - fast enumeration variables
8174 if (!var->getTypeSourceInfo() ||
8175 !var->getTypeSourceInfo()->getType().isConstQualified()) {
8176 ObjCMethodDecl *method = S.getCurMethodDecl();
8177 if (method && var == method->getSelfDecl())
8178 Diag = diag::err_typecheck_arr_assign_self;
8179 else if (var->getType().getObjCLifetime()
8180 == Qualifiers::OCL_ExplicitNone)
8181 Diag = diag::err_typecheck_arr_assign_enumeration;
8182 SourceRange Assign;
8183 if (Loc != OrigLoc)
8184 Assign = SourceRange(OrigLoc, OrigLoc);
8185 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8186 // We need to preserve the AST regardless, so migration tool
8187 // can do its job.
8188 return false;
8189 }
8190 }
8191 }
8192
8193 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008194 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00008195 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
8196 NeedType = true;
8197 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008198 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00008199 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
8200 NeedType = true;
8201 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00008202 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00008203 Diag = diag::err_typecheck_lvalue_casts_not_supported;
8204 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008205 case Expr::MLV_Valid:
8206 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00008207 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008208 case Expr::MLV_MemberFunction:
8209 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00008210 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
8211 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008212 case Expr::MLV_IncompleteType:
8213 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00008214 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00008215 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00008216 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00008217 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00008218 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
8219 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00008220 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00008221 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
8222 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00008223 case Expr::MLV_ReadonlyProperty:
8224 Diag = diag::error_readonly_property_assignment;
8225 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00008226 case Expr::MLV_NoSetterProperty:
8227 Diag = diag::error_nosetter_property_assignment;
8228 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00008229 case Expr::MLV_InvalidMessageExpression:
8230 Diag = diag::error_readonly_message_assignment;
8231 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00008232 case Expr::MLV_SubObjCPropertySetting:
8233 Diag = diag::error_no_subobject_property_setting;
8234 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008235 }
Steve Naroffad373bd2007-07-31 12:34:36 +00008236
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00008237 SourceRange Assign;
8238 if (Loc != OrigLoc)
8239 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00008240 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00008241 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00008242 else
Mike Stump11289f42009-09-09 15:08:12 +00008243 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00008244 return true;
8245}
8246
8247
8248
8249// C99 6.5.16.1
John Wiegley01296292011-04-08 18:41:53 +00008250QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00008251 SourceLocation Loc,
8252 QualType CompoundType) {
8253 // Verify that LHS is a modifiable lvalue, and emit error if not.
8254 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00008255 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00008256
8257 QualType LHSType = LHS->getType();
John Wiegley01296292011-04-08 18:41:53 +00008258 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008259 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00008260 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00008261 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00008262 // Simple assignment "x = y".
John Wiegley01296292011-04-08 18:41:53 +00008263 if (LHS->getObjectKind() == OK_ObjCProperty) {
8264 ExprResult LHSResult = Owned(LHS);
8265 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
8266 if (LHSResult.isInvalid())
8267 return QualType();
8268 LHS = LHSResult.take();
8269 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00008270 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00008271 if (RHS.isInvalid())
8272 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00008273 // Special case of NSObject attributes on c-style pointer types.
8274 if (ConvTy == IncompatiblePointer &&
8275 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00008276 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00008277 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00008278 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00008279 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008280
John McCall7decc9e2010-11-18 06:31:45 +00008281 if (ConvTy == Compatible &&
8282 getLangOptions().ObjCNonFragileABI &&
8283 LHSType->isObjCObjectType())
8284 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
8285 << LHSType;
8286
Chris Lattnerea714382008-08-21 18:04:13 +00008287 // If the RHS is a unary plus or minus, check to see if they = and + are
8288 // right next to each other. If so, the user may have typo'd "x =+ 4"
8289 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00008290 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00008291 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8292 RHSCheck = ICE->getSubExpr();
8293 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00008294 if ((UO->getOpcode() == UO_Plus ||
8295 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00008296 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00008297 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00008298 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
8299 // And there is a space or other character before the subexpr of the
8300 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00008301 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
8302 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00008303 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00008304 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00008305 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00008306 }
Chris Lattnerea714382008-08-21 18:04:13 +00008307 }
John McCall31168b02011-06-15 23:02:42 +00008308
8309 if (ConvTy == Compatible) {
8310 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
8311 checkRetainCycles(LHS, RHS.get());
8312 else
8313 checkUnsafeAssigns(Loc, LHSType, RHS.get());
8314 }
Chris Lattnerea714382008-08-21 18:04:13 +00008315 } else {
8316 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00008317 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00008318 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00008319
Chris Lattner326f7572008-11-18 01:30:42 +00008320 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00008321 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00008322 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008323
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +00008324 CheckForNullPointerDereference(*this, LHS);
Ted Kremenek64699be2011-02-16 01:57:07 +00008325 // Check for trivial buffer overflows.
Ted Kremenekdf26df72011-03-01 18:41:00 +00008326 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremenek64699be2011-02-16 01:57:07 +00008327
Steve Naroff98cf3e92007-06-06 18:38:38 +00008328 // C99 6.5.16p3: The type of an assignment expression is the type of the
8329 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00008330 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00008331 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8332 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00008333 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00008334 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00008335 return (getLangOptions().CPlusPlus
8336 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00008337}
8338
Chris Lattner326f7572008-11-18 01:30:42 +00008339// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00008340static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00008341 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00008342 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00008343
John McCall3aef3d82011-04-10 19:13:55 +00008344 LHS = S.CheckPlaceholderExpr(LHS.take());
8345 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00008346 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00008347 return QualType();
8348
John McCall73d36182010-10-12 07:14:40 +00008349 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8350 // operands, but not unary promotions.
8351 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00008352
John McCall34376a62010-12-04 03:47:34 +00008353 // So we treat the LHS as a ignored value, and in C++ we allow the
8354 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00008355 LHS = S.IgnoredValueConversions(LHS.take());
8356 if (LHS.isInvalid())
8357 return QualType();
John McCall34376a62010-12-04 03:47:34 +00008358
8359 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00008360 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8361 if (RHS.isInvalid())
8362 return QualType();
8363 if (!RHS.get()->getType()->isVoidType())
8364 S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00008365 }
Eli Friedmanba961a92009-03-23 00:24:07 +00008366
John Wiegley01296292011-04-08 18:41:53 +00008367 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00008368}
8369
Steve Naroff7a5af782007-07-13 16:58:59 +00008370/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8371/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00008372static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8373 ExprValueKind &VK,
8374 SourceLocation OpLoc,
8375 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008376 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008377 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008378
Chris Lattner6b0cf142008-11-21 07:05:48 +00008379 QualType ResType = Op->getType();
8380 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00008381
John McCall4bc41ae2010-11-18 19:01:18 +00008382 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00008383 // Decrement of bool is not allowed.
8384 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00008385 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00008386 return QualType();
8387 }
8388 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00008389 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00008390 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00008391 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00008392 } else if (ResType->isAnyPointerType()) {
8393 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00008394
Chris Lattner6b0cf142008-11-21 07:05:48 +00008395 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00008396 if (PointeeTy->isVoidType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008397 if (S.getLangOptions().CPlusPlus) {
8398 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00008399 << Op->getSourceRange();
8400 return QualType();
8401 }
8402
8403 // Pointer to void is a GNU extension in C.
John McCall4bc41ae2010-11-18 19:01:18 +00008404 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00008405 } else if (PointeeTy->isFunctionType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008406 if (S.getLangOptions().CPlusPlus) {
8407 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00008408 << Op->getType() << Op->getSourceRange();
8409 return QualType();
8410 }
8411
John McCall4bc41ae2010-11-18 19:01:18 +00008412 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008413 << ResType << Op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00008414 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
8415 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00008416 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00008417 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00008418 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00008419 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00008420 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
8421 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00008422 << PointeeTy << Op->getSourceRange();
8423 return QualType();
8424 }
Eli Friedman090addd2010-01-03 00:20:48 +00008425 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00008426 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00008427 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008428 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008429 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008430 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00008431 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008432 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8433 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00008434 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
8435 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00008436 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00008437 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00008438 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00008439 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00008440 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008441 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00008442 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00008443 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00008444 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00008445 // In C++, a prefix increment is the same type as the operand. Otherwise
8446 // (in C or with postfix), the increment is the unqualified type of the
8447 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00008448 if (isPrefix && S.getLangOptions().CPlusPlus) {
8449 VK = VK_LValue;
8450 return ResType;
8451 } else {
8452 VK = VK_RValue;
8453 return ResType.getUnqualifiedType();
8454 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00008455}
8456
John Wiegley01296292011-04-08 18:41:53 +00008457ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00008458 assert(E->getValueKind() == VK_LValue &&
8459 E->getObjectKind() == OK_ObjCProperty);
8460 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
8461
Douglas Gregor33823722011-06-11 01:09:30 +00008462 QualType T = E->getType();
8463 QualType ReceiverType;
8464 if (PRE->isObjectReceiver())
8465 ReceiverType = PRE->getBase()->getType();
8466 else if (PRE->isSuperReceiver())
8467 ReceiverType = PRE->getSuperReceiverType();
8468 else
8469 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
8470
John McCall34376a62010-12-04 03:47:34 +00008471 ExprValueKind VK = VK_RValue;
8472 if (PRE->isImplicitProperty()) {
Douglas Gregor33823722011-06-11 01:09:30 +00008473 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00008474 PRE->getImplicitPropertyGetter()) {
Douglas Gregor33823722011-06-11 01:09:30 +00008475 T = getMessageSendResultType(ReceiverType, GetterMethod,
8476 PRE->isClassReceiver(),
8477 PRE->isSuperReceiver());
8478 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00008479 }
8480 else {
8481 Diag(PRE->getLocation(), diag::err_getter_not_found)
8482 << PRE->getBase()->getType();
8483 }
John McCall34376a62010-12-04 03:47:34 +00008484 }
Douglas Gregor33823722011-06-11 01:09:30 +00008485
8486 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCall34376a62010-12-04 03:47:34 +00008487 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00008488
8489 ExprResult Result = MaybeBindToTemporary(E);
8490 if (!Result.isInvalid())
8491 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00008492
8493 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00008494}
8495
John Wiegley01296292011-04-08 18:41:53 +00008496void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
8497 assert(LHS.get()->getValueKind() == VK_LValue &&
8498 LHS.get()->getObjectKind() == OK_ObjCProperty);
8499 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00008500
John McCall31168b02011-06-15 23:02:42 +00008501 bool Consumed = false;
8502
John Wiegley01296292011-04-08 18:41:53 +00008503 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00008504 // If using property-dot syntax notation for assignment, and there is a
8505 // setter, RHS expression is being passed to the setter argument. So,
8506 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00008507 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00008508 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
8509 LHSTy = (*P)->getType();
John McCall31168b02011-06-15 23:02:42 +00008510 Consumed = (getLangOptions().ObjCAutoRefCount &&
8511 (*P)->hasAttr<NSConsumedAttr>());
John McCall34376a62010-12-04 03:47:34 +00008512
8513 // Otherwise, if the getter returns an l-value, just call that.
8514 } else {
John Wiegley01296292011-04-08 18:41:53 +00008515 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00008516 ExprValueKind VK = Expr::getValueKindForType(Result);
8517 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00008518 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
8519 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00008520 return;
John McCallb7bd14f2010-12-02 01:19:52 +00008521 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008522 }
John McCall31168b02011-06-15 23:02:42 +00008523 } else if (getLangOptions().ObjCAutoRefCount) {
8524 const ObjCMethodDecl *setter
8525 = PropRef->getExplicitProperty()->getSetterMethodDecl();
8526 if (setter) {
8527 ObjCMethodDecl::param_iterator P = setter->param_begin();
8528 LHSTy = (*P)->getType();
8529 Consumed = (*P)->hasAttr<NSConsumedAttr>();
8530 }
John McCall34376a62010-12-04 03:47:34 +00008531 }
8532
John McCall31168b02011-06-15 23:02:42 +00008533 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
8534 getLangOptions().ObjCAutoRefCount) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008535 InitializedEntity Entity =
John McCall31168b02011-06-15 23:02:42 +00008536 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
John Wiegley01296292011-04-08 18:41:53 +00008537 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
John McCall31168b02011-06-15 23:02:42 +00008538 if (!ArgE.isInvalid()) {
John Wiegley01296292011-04-08 18:41:53 +00008539 RHS = ArgE;
John McCall31168b02011-06-15 23:02:42 +00008540 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
8541 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
8542 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008543 }
8544}
8545
8546
Anders Carlsson806700f2008-02-01 07:15:58 +00008547/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00008548/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008549/// where the declaration is needed for type checking. We only need to
8550/// handle cases when the expression references a function designator
8551/// or is an lvalue. Here are some examples:
8552/// - &(x) => x
8553/// - &*****f => f for f a function designator.
8554/// - &s.xx => s
8555/// - &s.zz[1].yy -> s, if zz is an array
8556/// - *(x + 1) -> x, if x is an array
8557/// - &"123"[2] -> 0
8558/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00008559static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008560 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00008561 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008562 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00008563 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00008564 // If this is an arrow operator, the address is an offset from
8565 // the base's value, so the object the base refers to is
8566 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008567 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00008568 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00008569 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008570 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00008571 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00008572 // FIXME: This code shouldn't be necessary! We should catch the implicit
8573 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00008574 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8575 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8576 if (ICE->getSubExpr()->getType()->isArrayType())
8577 return getPrimaryDecl(ICE->getSubExpr());
8578 }
8579 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00008580 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008581 case Stmt::UnaryOperatorClass: {
8582 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008583
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008584 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008585 case UO_Real:
8586 case UO_Imag:
8587 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008588 return getPrimaryDecl(UO->getSubExpr());
8589 default:
8590 return 0;
8591 }
8592 }
Steve Naroff47500512007-04-19 23:00:49 +00008593 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008594 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00008595 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00008596 // If the result of an implicit cast is an l-value, we care about
8597 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008598 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00008599 default:
8600 return 0;
8601 }
8602}
8603
8604/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00008605/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00008606/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008607/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00008608/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008609/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00008610/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00008611static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
8612 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00008613 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008614 return S.Context.DependentTy;
8615 if (OrigOp->getType() == S.Context.OverloadTy)
8616 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00008617 if (OrigOp->getType() == S.Context.UnknownAnyTy)
8618 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00008619 if (OrigOp->getType() == S.Context.BoundMemberTy) {
8620 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8621 << OrigOp->getSourceRange();
8622 return QualType();
8623 }
John McCall8d08b9b2010-08-27 09:08:28 +00008624
John McCall2979fe02011-04-12 00:42:48 +00008625 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00008626
John McCall8d08b9b2010-08-27 09:08:28 +00008627 // Make sure to ignore parentheses in subsequent checks
8628 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00008629
John McCall4bc41ae2010-11-18 19:01:18 +00008630 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00008631 // Implement C99-only parts of addressof rules.
8632 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00008633 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00008634 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8635 // (assuming the deref expression is valid).
8636 return uOp->getSubExpr()->getType();
8637 }
8638 // Technically, there should be a check for array subscript
8639 // expressions here, but the result of one is always an lvalue anyway.
8640 }
John McCallf3a88602011-02-03 08:15:49 +00008641 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00008642 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00008643
Fariborz Jahanian071caef2011-03-26 19:48:30 +00008644 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00008645 bool sfinae = S.isSFINAEContext();
8646 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8647 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008648 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00008649 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008650 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00008651 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008652 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00008653 } else if (lval == Expr::LV_MemberFunction) {
8654 // If it's an instance method, make a member pointer.
8655 // The expression must have exactly the form &A::foo.
8656
8657 // If the underlying expression isn't a decl ref, give up.
8658 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008659 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008660 << OrigOp->getSourceRange();
8661 return QualType();
8662 }
8663 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8664 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8665
8666 // The id-expression was parenthesized.
8667 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00008668 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008669 << OrigOp->getSourceRange();
8670
8671 // The method was named without a qualifier.
8672 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008673 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008674 << op->getSourceRange();
8675 }
8676
John McCall4bc41ae2010-11-18 19:01:18 +00008677 return S.Context.getMemberPointerType(op->getType(),
8678 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00008679 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00008680 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008681 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00008682 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00008683 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00008684 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00008685 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00008686 return QualType();
8687 }
John McCall086a4642010-11-24 05:12:34 +00008688 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008689 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00008690 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00008691 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00008692 return QualType();
John McCall086a4642010-11-24 05:12:34 +00008693 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00008694 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00008695 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00008696 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008697 return QualType();
John McCall086a4642010-11-24 05:12:34 +00008698 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00008699 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00008700 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00008701 << "property expression" << op->getSourceRange();
8702 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008703 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00008704 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00008705 // with the register storage-class specifier.
8706 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00008707 // in C++ it is not error to take address of a register
8708 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00008709 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00008710 !S.getLangOptions().CPlusPlus) {
8711 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00008712 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00008713 return QualType();
8714 }
John McCalld14a8642009-11-21 08:51:07 +00008715 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008716 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00008717 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00008718 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008719 // Could be a pointer to member, though, if there is an explicit
8720 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00008721 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008722 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008723 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00008724 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008725 S.Diag(OpLoc,
8726 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00008727 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008728 return QualType();
8729 }
Mike Stump11289f42009-09-09 15:08:12 +00008730
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00008731 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8732 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00008733 return S.Context.getMemberPointerType(op->getType(),
8734 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00008735 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008736 }
Anders Carlsson5b535762009-05-16 21:43:42 +00008737 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00008738 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00008739 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008740
Eli Friedmance7f9002009-05-16 23:27:50 +00008741 if (lval == Expr::LV_IncompleteVoidType) {
8742 // Taking the address of a void variable is technically illegal, but we
8743 // allow it in cases which are otherwise valid.
8744 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00008745 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00008746 }
8747
Steve Naroff47500512007-04-19 23:00:49 +00008748 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00008749 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00008750 return S.Context.getObjCObjectPointerType(op->getType());
8751 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00008752}
8753
Chris Lattner9156f1b2010-07-05 19:17:26 +00008754/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00008755static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8756 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008757 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008758 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008759
John Wiegley01296292011-04-08 18:41:53 +00008760 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8761 if (ConvResult.isInvalid())
8762 return QualType();
8763 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00008764 QualType OpTy = Op->getType();
8765 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00008766
8767 if (isa<CXXReinterpretCastExpr>(Op)) {
8768 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8769 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8770 Op->getSourceRange());
8771 }
8772
Chris Lattner9156f1b2010-07-05 19:17:26 +00008773 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8774 // is an incomplete type or void. It would be possible to warn about
8775 // dereferencing a void pointer, but it's completely well-defined, and such a
8776 // warning is unlikely to catch any mistakes.
8777 if (const PointerType *PT = OpTy->getAs<PointerType>())
8778 Result = PT->getPointeeType();
8779 else if (const ObjCObjectPointerType *OPT =
8780 OpTy->getAs<ObjCObjectPointerType>())
8781 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00008782 else {
John McCall3aef3d82011-04-10 19:13:55 +00008783 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00008784 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008785 if (PR.take() != Op)
8786 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00008787 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008788
Chris Lattner9156f1b2010-07-05 19:17:26 +00008789 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008790 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00008791 << OpTy << Op->getSourceRange();
8792 return QualType();
8793 }
John McCall4bc41ae2010-11-18 19:01:18 +00008794
8795 // Dereferences are usually l-values...
8796 VK = VK_LValue;
8797
8798 // ...except that certain expressions are never l-values in C.
8799 if (!S.getLangOptions().CPlusPlus &&
8800 IsCForbiddenLValueType(S.Context, Result))
8801 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00008802
8803 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00008804}
Steve Naroff218bc2b2007-05-04 21:54:46 +00008805
John McCalle3027922010-08-25 11:45:40 +00008806static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00008807 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008808 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008809 switch (Kind) {
8810 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00008811 case tok::periodstar: Opc = BO_PtrMemD; break;
8812 case tok::arrowstar: Opc = BO_PtrMemI; break;
8813 case tok::star: Opc = BO_Mul; break;
8814 case tok::slash: Opc = BO_Div; break;
8815 case tok::percent: Opc = BO_Rem; break;
8816 case tok::plus: Opc = BO_Add; break;
8817 case tok::minus: Opc = BO_Sub; break;
8818 case tok::lessless: Opc = BO_Shl; break;
8819 case tok::greatergreater: Opc = BO_Shr; break;
8820 case tok::lessequal: Opc = BO_LE; break;
8821 case tok::less: Opc = BO_LT; break;
8822 case tok::greaterequal: Opc = BO_GE; break;
8823 case tok::greater: Opc = BO_GT; break;
8824 case tok::exclaimequal: Opc = BO_NE; break;
8825 case tok::equalequal: Opc = BO_EQ; break;
8826 case tok::amp: Opc = BO_And; break;
8827 case tok::caret: Opc = BO_Xor; break;
8828 case tok::pipe: Opc = BO_Or; break;
8829 case tok::ampamp: Opc = BO_LAnd; break;
8830 case tok::pipepipe: Opc = BO_LOr; break;
8831 case tok::equal: Opc = BO_Assign; break;
8832 case tok::starequal: Opc = BO_MulAssign; break;
8833 case tok::slashequal: Opc = BO_DivAssign; break;
8834 case tok::percentequal: Opc = BO_RemAssign; break;
8835 case tok::plusequal: Opc = BO_AddAssign; break;
8836 case tok::minusequal: Opc = BO_SubAssign; break;
8837 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8838 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8839 case tok::ampequal: Opc = BO_AndAssign; break;
8840 case tok::caretequal: Opc = BO_XorAssign; break;
8841 case tok::pipeequal: Opc = BO_OrAssign; break;
8842 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008843 }
8844 return Opc;
8845}
8846
John McCalle3027922010-08-25 11:45:40 +00008847static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00008848 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008849 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00008850 switch (Kind) {
8851 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00008852 case tok::plusplus: Opc = UO_PreInc; break;
8853 case tok::minusminus: Opc = UO_PreDec; break;
8854 case tok::amp: Opc = UO_AddrOf; break;
8855 case tok::star: Opc = UO_Deref; break;
8856 case tok::plus: Opc = UO_Plus; break;
8857 case tok::minus: Opc = UO_Minus; break;
8858 case tok::tilde: Opc = UO_Not; break;
8859 case tok::exclaim: Opc = UO_LNot; break;
8860 case tok::kw___real: Opc = UO_Real; break;
8861 case tok::kw___imag: Opc = UO_Imag; break;
8862 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00008863 }
8864 return Opc;
8865}
8866
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008867/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8868/// This warning is only emitted for builtin assignment operations. It is also
8869/// suppressed in the event of macro expansions.
8870static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
8871 SourceLocation OpLoc) {
8872 if (!S.ActiveTemplateInstantiations.empty())
8873 return;
8874 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8875 return;
8876 lhs = lhs->IgnoreParenImpCasts();
8877 rhs = rhs->IgnoreParenImpCasts();
8878 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
8879 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
8880 if (!LeftDeclRef || !RightDeclRef ||
8881 LeftDeclRef->getLocation().isMacroID() ||
8882 RightDeclRef->getLocation().isMacroID())
8883 return;
8884 const ValueDecl *LeftDecl =
8885 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
8886 const ValueDecl *RightDecl =
8887 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
8888 if (LeftDecl != RightDecl)
8889 return;
8890 if (LeftDecl->getType().isVolatileQualified())
8891 return;
8892 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
8893 if (RefTy->getPointeeType().isVolatileQualified())
8894 return;
8895
8896 S.Diag(OpLoc, diag::warn_self_assignment)
8897 << LeftDeclRef->getType()
8898 << lhs->getSourceRange() << rhs->getSourceRange();
8899}
8900
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008901/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8902/// operator @p Opc at location @c TokLoc. This routine only supports
8903/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00008904ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008905 BinaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008906 Expr *lhsExpr, Expr *rhsExpr) {
8907 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008908 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008909 // The following two variables are used for compound assignment operators
8910 QualType CompLHSTy; // Type of LHS after promotions for computation
8911 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00008912 ExprValueKind VK = VK_RValue;
8913 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008914
Douglas Gregor1beec452011-03-12 01:48:56 +00008915 // Check if a 'foo<int>' involved in a binary op, identifies a single
8916 // function unambiguously (i.e. an lvalue ala 13.4)
8917 // But since an assignment can trigger target based overload, exclude it in
8918 // our blind search. i.e:
8919 // template<class T> void f(); template<class T, class U> void f(U);
8920 // f<int> == 0; // resolve f<int> blindly
8921 // void (*p)(int); p = f<int>; // resolve f<int> using target
8922 if (Opc != BO_Assign) {
John McCall3aef3d82011-04-10 19:13:55 +00008923 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall31996342011-04-07 08:22:57 +00008924 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008925 lhs = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00008926
John McCall3aef3d82011-04-10 19:13:55 +00008927 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall31996342011-04-07 08:22:57 +00008928 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008929 rhs = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00008930 }
8931
Richard Trieu701fb362011-06-16 21:36:56 +00008932 bool LeftNull = Expr::NPCK_GNUNull ==
8933 lhs.get()->isNullPointerConstant(Context,
8934 Expr::NPC_ValueDependentIsNotNull);
8935 bool RightNull = Expr::NPCK_GNUNull ==
8936 rhs.get()->isNullPointerConstant(Context,
8937 Expr::NPC_ValueDependentIsNotNull);
8938
8939 // Detect when a NULL constant is used improperly in an expression. These
8940 // are mainly cases where the null pointer is used as an integer instead
8941 // of a pointer.
8942 if (LeftNull || RightNull) {
8943 if (Opc == BO_Mul || Opc == BO_Div || Opc == BO_Rem || Opc == BO_Add ||
8944 Opc == BO_Sub || Opc == BO_Shl || Opc == BO_Shr || Opc == BO_And ||
8945 Opc == BO_Xor || Opc == BO_Or || Opc == BO_MulAssign ||
8946 Opc == BO_DivAssign || Opc == BO_AddAssign || Opc == BO_SubAssign ||
8947 Opc == BO_RemAssign || Opc == BO_ShlAssign || Opc == BO_ShrAssign ||
8948 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign) {
8949 // These are the operations that would not make sense with a null pointer
8950 // no matter what the other expression is.
8951 if (LeftNull && RightNull) {
8952 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
8953 << lhs.get()->getSourceRange() << rhs.get()->getSourceRange();
8954 } else if (LeftNull) {
8955 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
8956 << lhs.get()->getSourceRange();
8957 } else if (RightNull) {
8958 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
8959 << rhs.get()->getSourceRange();
8960 }
8961 } else if (Opc == BO_LE || Opc == BO_LT || Opc == BO_GE || Opc == BO_GT ||
8962 Opc == BO_EQ || Opc == BO_NE) {
8963 // These are the operations that would not make sense with a null pointer
8964 // if the other expression the other expression is not a pointer.
8965 QualType LeftType = lhs.get()->getType();
8966 QualType RightType = rhs.get()->getType();
8967 bool LeftPointer = LeftType->isPointerType() ||
8968 LeftType->isBlockPointerType() ||
8969 LeftType->isMemberPointerType() ||
8970 LeftType->isObjCObjectPointerType();
8971 bool RightPointer = RightType->isPointerType() ||
8972 RightType->isBlockPointerType() ||
8973 RightType->isMemberPointerType() ||
8974 RightType->isObjCObjectPointerType();
8975 if ((LeftNull != RightNull) && !LeftPointer && !RightPointer) {
8976 if (LeftNull)
8977 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
8978 << lhs.get()->getSourceRange();
8979 if (RightNull)
8980 Diag(OpLoc, diag::warn_null_in_arithmetic_operation)
8981 << rhs.get()->getSourceRange();
8982 }
8983 }
8984 }
8985
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008986 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008987 case BO_Assign:
John Wiegley01296292011-04-08 18:41:53 +00008988 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00008989 if (getLangOptions().CPlusPlus &&
John Wiegley01296292011-04-08 18:41:53 +00008990 lhs.get()->getObjectKind() != OK_ObjCProperty) {
8991 VK = lhs.get()->getValueKind();
8992 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008993 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008994 if (!ResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00008995 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008996 break;
John McCalle3027922010-08-25 11:45:40 +00008997 case BO_PtrMemD:
8998 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00008999 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00009000 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00009001 break;
John McCalle3027922010-08-25 11:45:40 +00009002 case BO_Mul:
9003 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00009004 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00009005 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009006 break;
John McCalle3027922010-08-25 11:45:40 +00009007 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009008 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
9009 break;
John McCalle3027922010-08-25 11:45:40 +00009010 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009011 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
9012 break;
John McCalle3027922010-08-25 11:45:40 +00009013 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009014 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
9015 break;
John McCalle3027922010-08-25 11:45:40 +00009016 case BO_Shl:
9017 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00009018 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009019 break;
John McCalle3027922010-08-25 11:45:40 +00009020 case BO_LE:
9021 case BO_LT:
9022 case BO_GE:
9023 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00009024 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009025 break;
John McCalle3027922010-08-25 11:45:40 +00009026 case BO_EQ:
9027 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00009028 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009029 break;
John McCalle3027922010-08-25 11:45:40 +00009030 case BO_And:
9031 case BO_Xor:
9032 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009033 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
9034 break;
John McCalle3027922010-08-25 11:45:40 +00009035 case BO_LAnd:
9036 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00009037 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009038 break;
John McCalle3027922010-08-25 11:45:40 +00009039 case BO_MulAssign:
9040 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00009041 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00009042 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00009043 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00009044 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9045 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009046 break;
John McCalle3027922010-08-25 11:45:40 +00009047 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00009048 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
9049 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00009050 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9051 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009052 break;
John McCalle3027922010-08-25 11:45:40 +00009053 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00009054 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00009055 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9056 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009057 break;
John McCalle3027922010-08-25 11:45:40 +00009058 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00009059 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00009060 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9061 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009062 break;
John McCalle3027922010-08-25 11:45:40 +00009063 case BO_ShlAssign:
9064 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00009065 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00009066 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00009067 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9068 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009069 break;
John McCalle3027922010-08-25 11:45:40 +00009070 case BO_AndAssign:
9071 case BO_XorAssign:
9072 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00009073 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
9074 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00009075 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
9076 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009077 break;
John McCalle3027922010-08-25 11:45:40 +00009078 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00009079 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009080 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
9081 VK = rhs.get()->getValueKind();
9082 OK = rhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00009083 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009084 break;
9085 }
John Wiegley01296292011-04-08 18:41:53 +00009086 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00009087 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00009088 if (CompResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00009089 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
9090 ResultTy, VK, OK, OpLoc));
9091 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00009092 VK = VK_LValue;
John Wiegley01296292011-04-08 18:41:53 +00009093 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00009094 }
John Wiegley01296292011-04-08 18:41:53 +00009095 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
9096 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00009097 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009098}
9099
Sebastian Redl44615072009-10-27 12:10:02 +00009100/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
9101/// operators are mixed in a way that suggests that the programmer forgot that
9102/// comparison operators have higher precedence. The most typical example of
9103/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00009104static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00009105 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00009106 typedef BinaryOperator BinOp;
9107 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
9108 rhsopc = static_cast<BinOp::Opcode>(-1);
9109 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00009110 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00009111 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00009112 rhsopc = BO->getOpcode();
9113
9114 // Subs are not binary operators.
9115 if (lhsopc == -1 && rhsopc == -1)
9116 return;
9117
9118 // Bitwise operations are sometimes used as eager logical ops.
9119 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00009120 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
9121 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00009122 return;
9123
Chandler Carruthb00e8c02011-06-16 01:05:14 +00009124 if (BinOp::isComparisonOp(lhsopc)) {
9125 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9126 << SourceRange(lhs->getLocStart(), OpLoc)
9127 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc);
Sebastian Redl4afb7c582009-10-26 17:01:32 +00009128 SuggestParentheses(Self, OpLoc,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00009129 Self.PDiag(diag::note_precedence_bitwise_silence)
9130 << BinOp::getOpcodeStr(lhsopc),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00009131 lhs->getSourceRange());
9132 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009133 Self.PDiag(diag::note_precedence_bitwise_first)
9134 << BinOp::getOpcodeStr(Opc),
9135 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
Chandler Carruthb00e8c02011-06-16 01:05:14 +00009136 } else if (BinOp::isComparisonOp(rhsopc)) {
9137 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9138 << SourceRange(OpLoc, rhs->getLocEnd())
9139 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc);
Sebastian Redl4afb7c582009-10-26 17:01:32 +00009140 SuggestParentheses(Self, OpLoc,
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009141 Self.PDiag(diag::note_precedence_bitwise_silence)
9142 << BinOp::getOpcodeStr(rhsopc),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00009143 rhs->getSourceRange());
9144 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009145 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00009146 << BinOp::getOpcodeStr(Opc),
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00009147 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Chandler Carruthb00e8c02011-06-16 01:05:14 +00009148 }
Sebastian Redl43028242009-10-26 15:24:15 +00009149}
9150
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009151/// \brief It accepts a '&&' expr that is inside a '||' one.
9152/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
9153/// in parentheses.
9154static void
9155EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00009156 BinaryOperator *Bop) {
9157 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00009158 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
9159 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00009160 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009161 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00009162 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009163}
9164
9165/// \brief Returns true if the given expression can be evaluated as a constant
9166/// 'true'.
9167static bool EvaluatesAsTrue(Sema &S, Expr *E) {
9168 bool Res;
9169 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
9170}
9171
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00009172/// \brief Returns true if the given expression can be evaluated as a constant
9173/// 'false'.
9174static bool EvaluatesAsFalse(Sema &S, Expr *E) {
9175 bool Res;
9176 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
9177}
9178
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009179/// \brief Look for '&&' in the left hand of a '||' expr.
9180static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00009181 Expr *OrLHS, Expr *OrRHS) {
9182 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00009183 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00009184 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
9185 if (EvaluatesAsFalse(S, OrRHS))
9186 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009187 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
9188 if (!EvaluatesAsTrue(S, Bop->getLHS()))
9189 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9190 } else if (Bop->getOpcode() == BO_LOr) {
9191 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
9192 // If it's "a || b && 1 || c" we didn't warn earlier for
9193 // "a || b && 1", but warn now.
9194 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
9195 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
9196 }
9197 }
9198 }
9199}
9200
9201/// \brief Look for '&&' in the right hand of a '||' expr.
9202static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00009203 Expr *OrLHS, Expr *OrRHS) {
9204 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009205 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00009206 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
9207 if (EvaluatesAsFalse(S, OrLHS))
9208 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009209 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
9210 if (!EvaluatesAsTrue(S, Bop->getRHS()))
9211 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00009212 }
9213 }
9214}
9215
Sebastian Redl43028242009-10-26 15:24:15 +00009216/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00009217/// precedence.
John McCalle3027922010-08-25 11:45:40 +00009218static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00009219 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00009220 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00009221 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00009222 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
9223
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009224 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9225 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00009226 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00009227 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
9228 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00009229 }
Sebastian Redl43028242009-10-26 15:24:15 +00009230}
9231
Steve Naroff218bc2b2007-05-04 21:54:46 +00009232// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00009233ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00009234 tok::TokenKind Kind,
9235 Expr *lhs, Expr *rhs) {
9236 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00009237 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
9238 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00009239
Sebastian Redl43028242009-10-26 15:24:15 +00009240 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
9241 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
9242
Douglas Gregor5287f092009-11-05 00:51:44 +00009243 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
9244}
9245
John McCalldadc5752010-08-24 06:29:42 +00009246ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00009247 BinaryOperatorKind Opc,
9248 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00009249 if (getLangOptions().CPlusPlus) {
9250 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009251
John McCall622114c2010-12-06 05:26:58 +00009252 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
9253 UseBuiltinOperator = false;
9254 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
9255 UseBuiltinOperator = true;
9256 } else {
9257 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
9258 !rhs->getType()->isOverloadableType();
9259 }
9260
9261 if (!UseBuiltinOperator) {
9262 // Find all of the overloaded operators visible from this
9263 // point. We perform both an operator-name lookup from the local
9264 // scope and an argument-dependent lookup based on the types of
9265 // the arguments.
9266 UnresolvedSet<16> Functions;
9267 OverloadedOperatorKind OverOp
9268 = BinaryOperator::getOverloadedOperator(Opc);
9269 if (S && OverOp != OO_None)
9270 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
9271 Functions);
9272
9273 // Build the (potentially-overloaded, potentially-dependent)
9274 // binary operation.
9275 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
9276 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00009277 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009278
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009279 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00009280 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00009281}
9282
John McCalldadc5752010-08-24 06:29:42 +00009283ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00009284 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00009285 Expr *InputExpr) {
9286 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00009287 ExprValueKind VK = VK_RValue;
9288 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00009289 QualType resultType;
9290 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00009291 case UO_PreInc:
9292 case UO_PreDec:
9293 case UO_PostInc:
9294 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00009295 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00009296 Opc == UO_PreInc ||
9297 Opc == UO_PostInc,
9298 Opc == UO_PreInc ||
9299 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00009300 break;
John McCalle3027922010-08-25 11:45:40 +00009301 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00009302 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00009303 break;
John McCall31996342011-04-07 08:22:57 +00009304 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00009305 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00009306 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009307 Input = move(resolved);
9308 Input = DefaultFunctionArrayLvalueConversion(Input.take());
9309 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00009310 break;
John McCall31996342011-04-07 08:22:57 +00009311 }
John McCalle3027922010-08-25 11:45:40 +00009312 case UO_Plus:
9313 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00009314 Input = UsualUnaryConversions(Input.take());
9315 if (Input.isInvalid()) return ExprError();
9316 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009317 if (resultType->isDependentType())
9318 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00009319 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9320 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00009321 break;
9322 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
9323 resultType->isEnumeralType())
9324 break;
9325 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00009326 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00009327 resultType->isPointerType())
9328 break;
John McCall36226622010-10-12 02:09:17 +00009329 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00009330 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00009331 if (Input.isInvalid()) return ExprError();
9332 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00009333 }
Douglas Gregord08452f2008-11-19 15:42:04 +00009334
Sebastian Redlc215cfc2009-01-19 00:08:26 +00009335 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00009336 << resultType << Input.get()->getSourceRange());
9337
John McCalle3027922010-08-25 11:45:40 +00009338 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00009339 Input = UsualUnaryConversions(Input.take());
9340 if (Input.isInvalid()) return ExprError();
9341 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009342 if (resultType->isDependentType())
9343 break;
Chris Lattner0d707612008-07-25 23:52:49 +00009344 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9345 if (resultType->isComplexType() || resultType->isComplexIntegerType())
9346 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00009347 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00009348 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00009349 else if (resultType->hasIntegerRepresentation())
9350 break;
9351 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00009352 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00009353 if (Input.isInvalid()) return ExprError();
9354 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00009355 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00009356 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00009357 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00009358 }
Steve Naroff35d85152007-05-07 00:24:15 +00009359 break;
John Wiegley01296292011-04-08 18:41:53 +00009360
John McCalle3027922010-08-25 11:45:40 +00009361 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00009362 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00009363 Input = DefaultFunctionArrayLvalueConversion(Input.take());
9364 if (Input.isInvalid()) return ExprError();
9365 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009366 if (resultType->isDependentType())
9367 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00009368 if (resultType->isScalarType()) {
9369 // C99 6.5.3.3p1: ok, fallthrough;
9370 if (Context.getLangOptions().CPlusPlus) {
9371 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9372 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00009373 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
9374 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00009375 }
John McCall36226622010-10-12 02:09:17 +00009376 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00009377 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00009378 if (Input.isInvalid()) return ExprError();
9379 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00009380 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00009381 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00009382 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00009383 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00009384
Chris Lattnerbe31ed82007-06-02 19:11:33 +00009385 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00009386 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00009387 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00009388 break;
John McCalle3027922010-08-25 11:45:40 +00009389 case UO_Real:
9390 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00009391 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00009392 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00009393 if (Input.isInvalid()) return ExprError();
9394 if (Input.get()->getValueKind() != VK_RValue &&
9395 Input.get()->getObjectKind() == OK_Ordinary)
9396 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00009397 break;
John McCalle3027922010-08-25 11:45:40 +00009398 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00009399 resultType = Input.get()->getType();
9400 VK = Input.get()->getValueKind();
9401 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00009402 break;
Steve Naroff35d85152007-05-07 00:24:15 +00009403 }
John Wiegley01296292011-04-08 18:41:53 +00009404 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00009405 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00009406
John Wiegley01296292011-04-08 18:41:53 +00009407 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00009408 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00009409}
Chris Lattnereefa10e2007-05-28 06:56:27 +00009410
John McCalldadc5752010-08-24 06:29:42 +00009411ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00009412 UnaryOperatorKind Opc,
9413 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00009414 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00009415 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009416 // Find all of the overloaded operators visible from this
9417 // point. We perform both an operator-name lookup from the local
9418 // scope and an argument-dependent lookup based on the types of
9419 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00009420 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00009421 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00009422 if (S && OverOp != OO_None)
9423 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9424 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009425
John McCallb268a282010-08-23 23:25:46 +00009426 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009427 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009428
John McCallb268a282010-08-23 23:25:46 +00009429 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009430}
9431
Douglas Gregor5287f092009-11-05 00:51:44 +00009432// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00009433ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00009434 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00009435 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00009436}
9437
Steve Naroff66356bd2007-09-16 14:56:35 +00009438/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00009439ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00009440 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00009441 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00009442 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00009443 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009444 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00009445}
9446
John McCall31168b02011-06-15 23:02:42 +00009447/// Given the last statement in a statement-expression, check whether
9448/// the result is a producing expression (like a call to an
9449/// ns_returns_retained function) and, if so, rebuild it to hoist the
9450/// release out of the full-expression. Otherwise, return null.
9451/// Cannot fail.
9452static Expr *maybeRebuildARCConsumingStmt(Stmt *s) {
9453 // Should always be wrapped with one of these.
9454 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(s);
9455 if (!cleanups) return 0;
9456
9457 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
9458 if (!cast || cast->getCastKind() != CK_ObjCConsumeObject)
9459 return 0;
9460
9461 // Splice out the cast. This shouldn't modify any interesting
9462 // features of the statement.
9463 Expr *producer = cast->getSubExpr();
9464 assert(producer->getType() == cast->getType());
9465 assert(producer->getValueKind() == cast->getValueKind());
9466 cleanups->setSubExpr(producer);
9467 return cleanups;
9468}
9469
John McCalldadc5752010-08-24 06:29:42 +00009470ExprResult
John McCallb268a282010-08-23 23:25:46 +00009471Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009472 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00009473 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9474 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9475
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00009476 bool isFileScope
9477 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00009478 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009479 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00009480
Chris Lattner366727f2007-07-24 16:58:17 +00009481 // FIXME: there are a variety of strange constraints to enforce here, for
9482 // example, it is not possible to goto into a stmt expression apparently.
9483 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00009484
Chris Lattner366727f2007-07-24 16:58:17 +00009485 // If there are sub stmts in the compound stmt, take the type of the last one
9486 // as the type of the stmtexpr.
9487 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009488 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00009489 if (!Compound->body_empty()) {
9490 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009491 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00009492 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009493 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9494 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00009495 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009496 }
John McCall31168b02011-06-15 23:02:42 +00009497
John Wiegley01296292011-04-08 18:41:53 +00009498 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00009499 // Do function/array conversion on the last expression, but not
9500 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00009501 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9502 if (LastExpr.isInvalid())
9503 return ExprError();
9504 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00009505
John Wiegley01296292011-04-08 18:41:53 +00009506 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00009507 // In ARC, if the final expression ends in a consume, splice
9508 // the consume out and bind it later. In the alternate case
9509 // (when dealing with a retainable type), the result
9510 // initialization will create a produce. In both cases the
9511 // result will be +1, and we'll need to balance that out with
9512 // a bind.
9513 if (Expr *rebuiltLastStmt
9514 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9515 LastExpr = rebuiltLastStmt;
9516 } else {
9517 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009518 InitializedEntity::InitializeResult(LPLoc,
9519 Ty,
9520 false),
9521 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00009522 LastExpr);
9523 }
9524
John Wiegley01296292011-04-08 18:41:53 +00009525 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009526 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009527 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009528 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00009529 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009530 else
John Wiegley01296292011-04-08 18:41:53 +00009531 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009532 StmtExprMayBindToTemp = true;
9533 }
9534 }
9535 }
Chris Lattner944d3062008-07-26 19:51:01 +00009536 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009537
Eli Friedmanba961a92009-03-23 00:24:07 +00009538 // FIXME: Check that expression type is complete/non-abstract; statement
9539 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009540 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9541 if (StmtExprMayBindToTemp)
9542 return MaybeBindToTemporary(ResStmtExpr);
9543 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00009544}
Steve Naroff78864672007-08-01 22:05:33 +00009545
John McCalldadc5752010-08-24 06:29:42 +00009546ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009547 TypeSourceInfo *TInfo,
9548 OffsetOfComponent *CompPtr,
9549 unsigned NumComponents,
9550 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00009551 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009552 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00009553 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00009554
Chris Lattnerf17bd422007-08-30 17:45:32 +00009555 // We must have at least one component that refers to the type, and the first
9556 // one is known to be a field designator. Verify that the ArgTy represents
9557 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009558 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00009559 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9560 << ArgTy << TypeRange);
9561
9562 // Type must be complete per C99 7.17p3 because a declaring a variable
9563 // with an incomplete type would be ill-formed.
9564 if (!Dependent
9565 && RequireCompleteType(BuiltinLoc, ArgTy,
9566 PDiag(diag::err_offsetof_incomplete_type)
9567 << TypeRange))
9568 return ExprError();
9569
Chris Lattner78502cf2007-08-31 21:49:13 +00009570 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9571 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00009572 // FIXME: This diagnostic isn't actually visible because the location is in
9573 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00009574 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00009575 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9576 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00009577
9578 bool DidWarnAboutNonPOD = false;
9579 QualType CurrentType = ArgTy;
9580 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9581 llvm::SmallVector<OffsetOfNode, 4> Comps;
9582 llvm::SmallVector<Expr*, 4> Exprs;
9583 for (unsigned i = 0; i != NumComponents; ++i) {
9584 const OffsetOfComponent &OC = CompPtr[i];
9585 if (OC.isBrackets) {
9586 // Offset of an array sub-field. TODO: Should we allow vector elements?
9587 if (!CurrentType->isDependentType()) {
9588 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9589 if(!AT)
9590 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9591 << CurrentType);
9592 CurrentType = AT->getElementType();
9593 } else
9594 CurrentType = Context.DependentTy;
9595
9596 // The expression must be an integral expression.
9597 // FIXME: An integral constant expression?
9598 Expr *Idx = static_cast<Expr*>(OC.U.E);
9599 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9600 !Idx->getType()->isIntegerType())
9601 return ExprError(Diag(Idx->getLocStart(),
9602 diag::err_typecheck_subscript_not_integer)
9603 << Idx->getSourceRange());
9604
9605 // Record this array index.
9606 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9607 Exprs.push_back(Idx);
9608 continue;
9609 }
9610
9611 // Offset of a field.
9612 if (CurrentType->isDependentType()) {
9613 // We have the offset of a field, but we can't look into the dependent
9614 // type. Just record the identifier of the field.
9615 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9616 CurrentType = Context.DependentTy;
9617 continue;
9618 }
9619
9620 // We need to have a complete type to look into.
9621 if (RequireCompleteType(OC.LocStart, CurrentType,
9622 diag::err_offsetof_incomplete_type))
9623 return ExprError();
9624
9625 // Look for the designated field.
9626 const RecordType *RC = CurrentType->getAs<RecordType>();
9627 if (!RC)
9628 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9629 << CurrentType);
9630 RecordDecl *RD = RC->getDecl();
9631
9632 // C++ [lib.support.types]p5:
9633 // The macro offsetof accepts a restricted set of type arguments in this
9634 // International Standard. type shall be a POD structure or a POD union
9635 // (clause 9).
9636 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9637 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00009638 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00009639 PDiag(diag::warn_offsetof_non_pod_type)
9640 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9641 << CurrentType))
9642 DidWarnAboutNonPOD = true;
9643 }
9644
9645 // Look for the field.
9646 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9647 LookupQualifiedName(R, RD);
9648 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009649 IndirectFieldDecl *IndirectMemberDecl = 0;
9650 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00009651 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00009652 MemberDecl = IndirectMemberDecl->getAnonField();
9653 }
9654
Douglas Gregor882211c2010-04-28 22:16:22 +00009655 if (!MemberDecl)
9656 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9657 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9658 OC.LocEnd));
9659
Douglas Gregor10982ea2010-04-28 22:36:06 +00009660 // C99 7.17p3:
9661 // (If the specified member is a bit-field, the behavior is undefined.)
9662 //
9663 // We diagnose this as an error.
9664 if (MemberDecl->getBitWidth()) {
9665 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9666 << MemberDecl->getDeclName()
9667 << SourceRange(BuiltinLoc, RParenLoc);
9668 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9669 return ExprError();
9670 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009671
9672 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009673 if (IndirectMemberDecl)
9674 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009675
Douglas Gregord1702062010-04-29 00:18:15 +00009676 // If the member was found in a base class, introduce OffsetOfNodes for
9677 // the base class indirections.
9678 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9679 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009680 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00009681 CXXBasePath &Path = Paths.front();
9682 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9683 B != BEnd; ++B)
9684 Comps.push_back(OffsetOfNode(B->Base));
9685 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009686
Francois Pichet783dd6e2010-11-21 06:08:52 +00009687 if (IndirectMemberDecl) {
9688 for (IndirectFieldDecl::chain_iterator FI =
9689 IndirectMemberDecl->chain_begin(),
9690 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9691 assert(isa<FieldDecl>(*FI));
9692 Comps.push_back(OffsetOfNode(OC.LocStart,
9693 cast<FieldDecl>(*FI), OC.LocEnd));
9694 }
9695 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00009696 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00009697
Douglas Gregor882211c2010-04-28 22:16:22 +00009698 CurrentType = MemberDecl->getType().getNonReferenceType();
9699 }
9700
9701 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9702 TInfo, Comps.data(), Comps.size(),
9703 Exprs.data(), Exprs.size(), RParenLoc));
9704}
Mike Stump4e1f26a2009-02-19 03:04:26 +00009705
John McCalldadc5752010-08-24 06:29:42 +00009706ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00009707 SourceLocation BuiltinLoc,
9708 SourceLocation TypeLoc,
9709 ParsedType argty,
9710 OffsetOfComponent *CompPtr,
9711 unsigned NumComponents,
9712 SourceLocation RPLoc) {
9713
Douglas Gregor882211c2010-04-28 22:16:22 +00009714 TypeSourceInfo *ArgTInfo;
9715 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
9716 if (ArgTy.isNull())
9717 return ExprError();
9718
Eli Friedman06dcfd92010-08-05 10:15:45 +00009719 if (!ArgTInfo)
9720 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9721
9722 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9723 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00009724}
9725
9726
John McCalldadc5752010-08-24 06:29:42 +00009727ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009728 Expr *CondExpr,
9729 Expr *LHSExpr, Expr *RHSExpr,
9730 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00009731 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9732
John McCall7decc9e2010-11-18 06:31:45 +00009733 ExprValueKind VK = VK_RValue;
9734 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009735 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00009736 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00009737 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009738 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00009739 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009740 } else {
9741 // The conditional expression is required to be a constant expression.
9742 llvm::APSInt condEval(32);
9743 SourceLocation ExpLoc;
9744 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009745 return ExprError(Diag(ExpLoc,
9746 diag::err_typecheck_choose_expr_requires_constant)
9747 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00009748
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009749 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00009750 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9751
9752 resType = ActiveExpr->getType();
9753 ValueDependent = ActiveExpr->isValueDependent();
9754 VK = ActiveExpr->getValueKind();
9755 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009756 }
9757
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009758 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00009759 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00009760 resType->isDependentType(),
9761 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00009762}
9763
Steve Naroffc540d662008-09-03 18:15:37 +00009764//===----------------------------------------------------------------------===//
9765// Clang Extensions.
9766//===----------------------------------------------------------------------===//
9767
9768/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009769void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009770 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9771 PushBlockScope(BlockScope, Block);
9772 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009773 if (BlockScope)
9774 PushDeclContext(BlockScope, Block);
9775 else
9776 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009777}
9778
Mike Stump82f071f2009-02-04 22:31:32 +00009779void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00009780 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00009781 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009782 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009783
John McCall8cb7bdf2010-06-04 23:28:52 +00009784 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00009785 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00009786
John McCall3882ace2011-01-05 12:14:39 +00009787 // GetTypeForDeclarator always produces a function type for a block
9788 // literal signature. Furthermore, it is always a FunctionProtoType
9789 // unless the function was written with a typedef.
9790 assert(T->isFunctionType() &&
9791 "GetTypeForDeclarator made a non-function block signature");
9792
9793 // Look for an explicit signature in that function type.
9794 FunctionProtoTypeLoc ExplicitSignature;
9795
9796 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9797 if (isa<FunctionProtoTypeLoc>(tmp)) {
9798 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9799
9800 // Check whether that explicit signature was synthesized by
9801 // GetTypeForDeclarator. If so, don't save that as part of the
9802 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00009803 if (ExplicitSignature.getLocalRangeBegin() ==
9804 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00009805 // This would be much cheaper if we stored TypeLocs instead of
9806 // TypeSourceInfos.
9807 TypeLoc Result = ExplicitSignature.getResultLoc();
9808 unsigned Size = Result.getFullDataSize();
9809 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9810 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9811
9812 ExplicitSignature = FunctionProtoTypeLoc();
9813 }
John McCalla3ccba02010-06-04 11:21:44 +00009814 }
Mike Stump11289f42009-09-09 15:08:12 +00009815
John McCall3882ace2011-01-05 12:14:39 +00009816 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9817 CurBlock->FunctionType = T;
9818
9819 const FunctionType *Fn = T->getAs<FunctionType>();
9820 QualType RetTy = Fn->getResultType();
9821 bool isVariadic =
9822 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9823
John McCall8e346702010-06-04 19:02:56 +00009824 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00009825
John McCalla3ccba02010-06-04 11:21:44 +00009826 // Don't allow returning a objc interface by value.
9827 if (RetTy->isObjCObjectType()) {
9828 Diag(ParamInfo.getSourceRange().getBegin(),
9829 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9830 return;
9831 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009832
John McCalla3ccba02010-06-04 11:21:44 +00009833 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00009834 // return type. TODO: what should we do with declarators like:
9835 // ^ * { ... }
9836 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00009837 if (RetTy != Context.DependentTy)
9838 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009839
John McCalla3ccba02010-06-04 11:21:44 +00009840 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00009841 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00009842 if (ExplicitSignature) {
9843 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9844 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009845 if (Param->getIdentifier() == 0 &&
9846 !Param->isImplicit() &&
9847 !Param->isInvalidDecl() &&
9848 !getLangOptions().CPlusPlus)
9849 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00009850 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009851 }
John McCalla3ccba02010-06-04 11:21:44 +00009852
9853 // Fake up parameter variables if we have a typedef, like
9854 // ^ fntype { ... }
9855 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9856 for (FunctionProtoType::arg_type_iterator
9857 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9858 ParmVarDecl *Param =
9859 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9860 ParamInfo.getSourceRange().getBegin(),
9861 *I);
John McCall8e346702010-06-04 19:02:56 +00009862 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00009863 }
Steve Naroffc540d662008-09-03 18:15:37 +00009864 }
John McCalla3ccba02010-06-04 11:21:44 +00009865
John McCall8e346702010-06-04 19:02:56 +00009866 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00009867 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00009868 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00009869 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9870 CurBlock->TheDecl->param_end(),
9871 /*CheckParameterNames=*/false);
9872 }
9873
John McCalla3ccba02010-06-04 11:21:44 +00009874 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00009875 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00009876
John McCall8e346702010-06-04 19:02:56 +00009877 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00009878 Diag(ParamInfo.getAttributes()->getLoc(),
9879 diag::warn_attribute_sentinel_not_variadic) << 1;
9880 // FIXME: remove the attribute.
9881 }
9882
9883 // Put the parameter variables in scope. We can bail out immediately
9884 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00009885 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00009886 return;
9887
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009888 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00009889 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9890 (*AI)->setOwningFunction(CurBlock->TheDecl);
9891
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009892 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009893 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009894 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00009895
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009896 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009897 }
John McCallf7b2fb52010-01-22 00:28:27 +00009898 }
Steve Naroffc540d662008-09-03 18:15:37 +00009899}
9900
9901/// ActOnBlockError - If there is an error parsing a block, this callback
9902/// is invoked to pop the information about the block from the action impl.
9903void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00009904 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00009905 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00009906 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00009907}
9908
9909/// ActOnBlockStmtExpr - This is called when the body of a block statement
9910/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00009911ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00009912 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00009913 // If blocks are disabled, emit an error.
9914 if (!LangOpts.Blocks)
9915 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00009916
Douglas Gregor9a28e842010-03-01 23:15:13 +00009917 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009918
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009919 PopDeclContext();
9920
Steve Naroffc540d662008-09-03 18:15:37 +00009921 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00009922 if (!BSI->ReturnType.isNull())
9923 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009924
Mike Stump3bf1ab42009-07-28 22:04:01 +00009925 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00009926 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00009927
John McCallc63de662011-02-02 13:00:07 +00009928 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00009929 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
9930 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00009931
John McCall8e346702010-06-04 19:02:56 +00009932 // If the user wrote a function type in some form, try to use that.
9933 if (!BSI->FunctionType.isNull()) {
9934 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9935
9936 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9937 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9938
9939 // Turn protoless block types into nullary block types.
9940 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009941 FunctionProtoType::ExtProtoInfo EPI;
9942 EPI.ExtInfo = Ext;
9943 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009944
9945 // Otherwise, if we don't need to change anything about the function type,
9946 // preserve its sugar structure.
9947 } else if (FTy->getResultType() == RetTy &&
9948 (!NoReturn || FTy->getNoReturnAttr())) {
9949 BlockTy = BSI->FunctionType;
9950
9951 // Otherwise, make the minimal modifications to the function type.
9952 } else {
9953 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009954 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9955 EPI.TypeQuals = 0; // FIXME: silently?
9956 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009957 BlockTy = Context.getFunctionType(RetTy,
9958 FPT->arg_type_begin(),
9959 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009960 EPI);
John McCall8e346702010-06-04 19:02:56 +00009961 }
9962
9963 // If we don't have a function type, just build one from nothing.
9964 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009965 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00009966 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00009967 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009968 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009969
John McCall8e346702010-06-04 19:02:56 +00009970 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9971 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009972 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009973
Chris Lattner45542ea2009-04-19 05:28:12 +00009974 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00009975 if (getCurFunction()->NeedsScopeChecking() &&
9976 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00009977 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009978
Chris Lattner60f84492011-02-17 23:58:47 +00009979 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009980
John McCallc63de662011-02-02 13:00:07 +00009981 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCall1d570a72010-08-25 05:56:39 +00009982
Ted Kremenek1767a272011-02-23 01:51:48 +00009983 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9984 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009985 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009986}
9987
John McCalldadc5752010-08-24 06:29:42 +00009988ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00009989 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009990 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009991 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009992 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00009993 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009994}
9995
John McCalldadc5752010-08-24 06:29:42 +00009996ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009997 Expr *E, TypeSourceInfo *TInfo,
9998 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009999 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +000010000
Eli Friedman121ba0c2008-08-09 23:32:40 +000010001 // Get the va_list type
10002 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +000010003 if (VaListType->isArrayType()) {
10004 // Deal with implicit array decay; for example, on x86-64,
10005 // va_list is an array, but it's supposed to decay to
10006 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +000010007 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +000010008 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +000010009 ExprResult Result = UsualUnaryConversions(E);
10010 if (Result.isInvalid())
10011 return ExprError();
10012 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +000010013 } else {
10014 // Otherwise, the va_list argument must be an l-value because
10015 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +000010016 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +000010017 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +000010018 return ExprError();
10019 }
Eli Friedman121ba0c2008-08-09 23:32:40 +000010020
Douglas Gregorad3150c2009-05-19 23:10:31 +000010021 if (!E->isTypeDependent() &&
10022 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +000010023 return ExprError(Diag(E->getLocStart(),
10024 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +000010025 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +000010026 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000010027
David Majnemerc75d1a12011-06-14 05:17:32 +000010028 if (!TInfo->getType()->isDependentType()) {
10029 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
10030 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
10031 << TInfo->getTypeLoc().getSourceRange()))
10032 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +000010033
David Majnemerc75d1a12011-06-14 05:17:32 +000010034 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
10035 TInfo->getType(),
10036 PDiag(diag::err_second_parameter_to_va_arg_abstract)
10037 << TInfo->getTypeLoc().getSourceRange()))
10038 return ExprError();
10039
John McCall31168b02011-06-15 23:02:42 +000010040 if (!TInfo->getType().isPODType(Context))
David Majnemerc75d1a12011-06-14 05:17:32 +000010041 Diag(TInfo->getTypeLoc().getBeginLoc(),
10042 diag::warn_second_parameter_to_va_arg_not_pod)
10043 << TInfo->getType()
10044 << TInfo->getTypeLoc().getSourceRange();
10045 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000010046
Abramo Bagnara27db2392010-08-10 10:06:15 +000010047 QualType T = TInfo->getType().getNonLValueExprType(Context);
10048 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +000010049}
10050
John McCalldadc5752010-08-24 06:29:42 +000010051ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +000010052 // The type of __null will be int or long, depending on the size of
10053 // pointers on the target.
10054 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +000010055 unsigned pw = Context.Target.getPointerWidth(0);
10056 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +000010057 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +000010058 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +000010059 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +000010060 else if (pw == Context.Target.getLongLongWidth())
10061 Ty = Context.LongLongTy;
10062 else {
10063 assert(!"I don't know size of pointer!");
10064 Ty = Context.IntTy;
10065 }
Douglas Gregor3be4b122008-11-29 04:51:27 +000010066
Sebastian Redl6d4256c2009-03-15 17:47:39 +000010067 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +000010068}
10069
Alexis Huntc46382e2010-04-28 23:02:27 +000010070static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +000010071 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +000010072 if (!SemaRef.getLangOptions().ObjC1)
10073 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010074
Anders Carlssonace5d072009-11-10 04:46:30 +000010075 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10076 if (!PT)
10077 return;
10078
10079 // Check if the destination is of type 'id'.
10080 if (!PT->isObjCIdType()) {
10081 // Check if the destination is the 'NSString' interface.
10082 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10083 if (!ID || !ID->getIdentifier()->isStr("NSString"))
10084 return;
10085 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010086
Anders Carlssonace5d072009-11-10 04:46:30 +000010087 // Strip off any parens and casts.
10088 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
10089 if (!SL || SL->isWide())
10090 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010091
Douglas Gregora771f462010-03-31 17:46:05 +000010092 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +000010093}
10094
Chris Lattner9bad62c2008-01-04 18:04:52 +000010095bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10096 SourceLocation Loc,
10097 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +000010098 Expr *SrcExpr, AssignmentAction Action,
10099 bool *Complained) {
10100 if (Complained)
10101 *Complained = false;
10102
Chris Lattner9bad62c2008-01-04 18:04:52 +000010103 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +000010104 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +000010105 bool isInvalid = false;
10106 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +000010107 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010108
Chris Lattner9bad62c2008-01-04 18:04:52 +000010109 switch (ConvTy) {
10110 default: assert(0 && "Unknown conversion type");
10111 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +000010112 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +000010113 DiagKind = diag::ext_typecheck_convert_pointer_int;
10114 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +000010115 case IntToPointer:
10116 DiagKind = diag::ext_typecheck_convert_int_pointer;
10117 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +000010118 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +000010119 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +000010120 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +000010121 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10122 SrcType->isObjCObjectPointerType();
Chris Lattner9bad62c2008-01-04 18:04:52 +000010123 break;
Eli Friedman80160bd2009-03-22 23:59:44 +000010124 case IncompatiblePointerSign:
10125 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10126 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +000010127 case FunctionVoidPointer:
10128 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10129 break;
John McCall4fff8f62011-02-01 00:10:29 +000010130 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +000010131 // Perform array-to-pointer decay if necessary.
10132 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10133
John McCall4fff8f62011-02-01 00:10:29 +000010134 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10135 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10136 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10137 DiagKind = diag::err_typecheck_incompatible_address_space;
10138 break;
John McCall31168b02011-06-15 23:02:42 +000010139
10140
10141 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
10142 DiagKind = diag::err_typecheck_incompatible_lifetime;
10143 break;
John McCall4fff8f62011-02-01 00:10:29 +000010144 }
10145
10146 llvm_unreachable("unknown error case for discarding qualifiers!");
10147 // fallthrough
10148 }
Chris Lattner9bad62c2008-01-04 18:04:52 +000010149 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +000010150 // If the qualifiers lost were because we were applying the
10151 // (deprecated) C++ conversion from a string literal to a char*
10152 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
10153 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +000010154 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +000010155 // bit of refactoring (so that the second argument is an
10156 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +000010157 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +000010158 // C++ semantics.
10159 if (getLangOptions().CPlusPlus &&
10160 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10161 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +000010162 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10163 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +000010164 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +000010165 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +000010166 break;
Steve Naroff081c7422008-09-04 15:10:53 +000010167 case IntToBlockPointer:
10168 DiagKind = diag::err_int_to_block_pointer;
10169 break;
10170 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +000010171 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +000010172 break;
Steve Naroff8afa9892008-10-14 22:18:38 +000010173 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +000010174 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +000010175 // it can give a more specific diagnostic.
10176 DiagKind = diag::warn_incompatible_qualified_id;
10177 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +000010178 case IncompatibleVectors:
10179 DiagKind = diag::warn_incompatible_vectors;
10180 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +000010181 case Incompatible:
10182 DiagKind = diag::err_typecheck_convert_incompatible;
10183 isInvalid = true;
10184 break;
10185 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000010186
Douglas Gregorc68e1402010-04-09 00:35:39 +000010187 QualType FirstType, SecondType;
10188 switch (Action) {
10189 case AA_Assigning:
10190 case AA_Initializing:
10191 // The destination type comes first.
10192 FirstType = DstType;
10193 SecondType = SrcType;
10194 break;
Alexis Huntc46382e2010-04-28 23:02:27 +000010195
Douglas Gregorc68e1402010-04-09 00:35:39 +000010196 case AA_Returning:
10197 case AA_Passing:
10198 case AA_Converting:
10199 case AA_Sending:
10200 case AA_Casting:
10201 // The source type comes first.
10202 FirstType = SrcType;
10203 SecondType = DstType;
10204 break;
10205 }
Alexis Huntc46382e2010-04-28 23:02:27 +000010206
Douglas Gregorc68e1402010-04-09 00:35:39 +000010207 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +000010208 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor33823722011-06-11 01:09:30 +000010209 if (CheckInferredResultType)
10210 EmitRelatedResultTypeNote(SrcExpr);
10211
Douglas Gregor4f4946a2010-04-22 00:20:18 +000010212 if (Complained)
10213 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +000010214 return isInvalid;
10215}
Anders Carlssone54e8a12008-11-30 19:50:32 +000010216
Chris Lattnerc71d08b2009-04-25 21:59:05 +000010217bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +000010218 llvm::APSInt ICEResult;
10219 if (E->isIntegerConstantExpr(ICEResult, Context)) {
10220 if (Result)
10221 *Result = ICEResult;
10222 return false;
10223 }
10224
Anders Carlssone54e8a12008-11-30 19:50:32 +000010225 Expr::EvalResult EvalResult;
10226
Mike Stump4e1f26a2009-02-19 03:04:26 +000010227 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +000010228 EvalResult.HasSideEffects) {
10229 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
10230
10231 if (EvalResult.Diag) {
10232 // We only show the note if it's not the usual "invalid subexpression"
10233 // or if it's actually in a subexpression.
10234 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
10235 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
10236 Diag(EvalResult.DiagLoc, EvalResult.Diag);
10237 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000010238
Anders Carlssone54e8a12008-11-30 19:50:32 +000010239 return true;
10240 }
10241
Eli Friedmanbb967cc2009-04-25 22:26:58 +000010242 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
10243 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +000010244
Eli Friedmanbb967cc2009-04-25 22:26:58 +000010245 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +000010246 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
10247 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +000010248 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +000010249
Anders Carlssone54e8a12008-11-30 19:50:32 +000010250 if (Result)
10251 *Result = EvalResult.Val.getInt();
10252 return false;
10253}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010254
Douglas Gregorff790f12009-11-26 00:44:06 +000010255void
Mike Stump11289f42009-09-09 15:08:12 +000010256Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +000010257 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +000010258 ExpressionEvaluationContextRecord(NewContext,
10259 ExprTemporaries.size(),
10260 ExprNeedsCleanups));
10261 ExprNeedsCleanups = false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010262}
10263
Mike Stump11289f42009-09-09 15:08:12 +000010264void
Douglas Gregorff790f12009-11-26 00:44:06 +000010265Sema::PopExpressionEvaluationContext() {
10266 // Pop the current expression evaluation context off the stack.
10267 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
10268 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010269
Douglas Gregorfab31f42009-12-12 07:57:52 +000010270 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
10271 if (Rec.PotentiallyReferenced) {
10272 // Mark any remaining declarations in the current position of the stack
10273 // as "referenced". If they were not meant to be referenced, semantic
10274 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010275 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +000010276 I = Rec.PotentiallyReferenced->begin(),
10277 IEnd = Rec.PotentiallyReferenced->end();
10278 I != IEnd; ++I)
10279 MarkDeclarationReferenced(I->first, I->second);
10280 }
10281
10282 if (Rec.PotentiallyDiagnosed) {
10283 // Emit any pending diagnostics.
10284 for (PotentiallyEmittedDiagnostics::iterator
10285 I = Rec.PotentiallyDiagnosed->begin(),
10286 IEnd = Rec.PotentiallyDiagnosed->end();
10287 I != IEnd; ++I)
10288 Diag(I->first, I->second);
10289 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010290 }
Douglas Gregorff790f12009-11-26 00:44:06 +000010291
10292 // When are coming out of an unevaluated context, clear out any
10293 // temporaries that we may have created as part of the evaluation of
10294 // the expression in that context: they aren't relevant because they
10295 // will never be constructed.
John McCall31168b02011-06-15 23:02:42 +000010296 if (Rec.Context == Unevaluated) {
Douglas Gregorff790f12009-11-26 00:44:06 +000010297 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
10298 ExprTemporaries.end());
John McCall31168b02011-06-15 23:02:42 +000010299 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
10300
10301 // Otherwise, merge the contexts together.
10302 } else {
10303 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
10304 }
Douglas Gregorff790f12009-11-26 00:44:06 +000010305
10306 // Destroy the popped expression evaluation record.
10307 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010308}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010309
John McCall31168b02011-06-15 23:02:42 +000010310void Sema::DiscardCleanupsInEvaluationContext() {
10311 ExprTemporaries.erase(
10312 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
10313 ExprTemporaries.end());
10314 ExprNeedsCleanups = false;
10315}
10316
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010317/// \brief Note that the given declaration was referenced in the source code.
10318///
10319/// This routine should be invoke whenever a given declaration is referenced
10320/// in the source code, and where that reference occurred. If this declaration
10321/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
10322/// C99 6.9p3), then the declaration will be marked as used.
10323///
10324/// \param Loc the location where the declaration was referenced.
10325///
10326/// \param D the declaration that has been referenced by the source code.
10327void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
10328 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +000010329
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +000010330 D->setReferenced();
10331
Douglas Gregorebada0772010-06-17 23:14:26 +000010332 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +000010333 return;
Mike Stump11289f42009-09-09 15:08:12 +000010334
Douglas Gregor3beaf9b2009-10-08 21:35:42 +000010335 // Mark a parameter or variable declaration "used", regardless of whether we're in a
10336 // template or not. The reason for this is that unevaluated expressions
10337 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
10338 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010339 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +000010340 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +000010341 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +000010342 return;
10343 }
Alexis Huntc46382e2010-04-28 23:02:27 +000010344
Douglas Gregorfd27fed2010-04-07 20:29:57 +000010345 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
10346 return;
Alexis Huntc46382e2010-04-28 23:02:27 +000010347
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010348 // Do not mark anything as "used" within a dependent context; wait for
10349 // an instantiation.
10350 if (CurContext->isDependentContext())
10351 return;
Mike Stump11289f42009-09-09 15:08:12 +000010352
Douglas Gregorff790f12009-11-26 00:44:06 +000010353 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010354 case Unevaluated:
10355 // We are in an expression that is not potentially evaluated; do nothing.
10356 return;
Mike Stump11289f42009-09-09 15:08:12 +000010357
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010358 case PotentiallyEvaluated:
10359 // We are in a potentially-evaluated expression, so this declaration is
10360 // "used"; handle this below.
10361 break;
Mike Stump11289f42009-09-09 15:08:12 +000010362
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010363 case PotentiallyPotentiallyEvaluated:
10364 // We are in an expression that may be potentially evaluated; queue this
10365 // declaration reference until we know whether the expression is
10366 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +000010367 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010368 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010369
10370 case PotentiallyEvaluatedIfUsed:
10371 // Referenced declarations will only be used if the construct in the
10372 // containing expression is used.
10373 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010374 }
Mike Stump11289f42009-09-09 15:08:12 +000010375
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010376 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +000010377 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Alexis Huntf92197c2011-05-12 03:51:51 +000010378 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor()) {
10379 if (Constructor->isTrivial())
Chandler Carruthc9262402010-08-23 07:55:51 +000010380 return;
10381 if (!Constructor->isUsed(false))
10382 DefineImplicitDefaultConstructor(Loc, Constructor);
Alexis Hunt22b5b132011-05-14 18:20:50 +000010383 } else if (Constructor->isDefaulted() &&
Alexis Hunt913820d2011-05-13 06:10:58 +000010384 Constructor->isCopyConstructor()) {
Douglas Gregorebada0772010-06-17 23:14:26 +000010385 if (!Constructor->isUsed(false))
Alexis Hunt913820d2011-05-13 06:10:58 +000010386 DefineImplicitCopyConstructor(Loc, Constructor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010387 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010388
Douglas Gregor88d292c2010-05-13 16:44:06 +000010389 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010390 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Alexis Huntf91729462011-05-12 22:46:25 +000010391 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010392 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010393 if (Destructor->isVirtual())
10394 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010395 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Alexis Huntc9a55732011-05-14 05:23:28 +000010396 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010397 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +000010398 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +000010399 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010400 } else if (MethodDecl->isVirtual())
10401 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010402 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +000010403 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +000010404 // Recursive functions should be marked when used from another function.
10405 if (CurContext == Function) return;
10406
Mike Stump11289f42009-09-09 15:08:12 +000010407 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +000010408 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +000010409 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +000010410 bool AlreadyInstantiated = false;
10411 if (FunctionTemplateSpecializationInfo *SpecInfo
10412 = Function->getTemplateSpecializationInfo()) {
10413 if (SpecInfo->getPointOfInstantiation().isInvalid())
10414 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010415 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +000010416 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +000010417 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010418 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +000010419 = Function->getMemberSpecializationInfo()) {
10420 if (MSInfo->getPointOfInstantiation().isInvalid())
10421 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010422 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +000010423 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +000010424 AlreadyInstantiated = true;
10425 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010426
Douglas Gregor7f792cf2010-01-16 22:29:39 +000010427 if (!AlreadyInstantiated) {
10428 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
10429 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
10430 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
10431 Loc));
10432 else
Chandler Carruth54080172010-08-25 08:44:16 +000010433 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +000010434 }
John McCall83779672011-02-19 02:53:41 +000010435 } else {
10436 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +000010437 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
10438 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +000010439 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +000010440 MarkDeclarationReferenced(Loc, *i);
10441 }
John McCall83779672011-02-19 02:53:41 +000010442 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010443
John McCall83779672011-02-19 02:53:41 +000010444 // Keep track of used but undefined functions.
10445 if (!Function->isPure() && !Function->hasBody() &&
10446 Function->getLinkage() != ExternalLinkage) {
10447 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
10448 if (old.isInvalid()) old = Loc;
10449 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +000010450
John McCall83779672011-02-19 02:53:41 +000010451 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010452 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +000010453 }
Mike Stump11289f42009-09-09 15:08:12 +000010454
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010455 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +000010456 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +000010457 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +000010458 Var->getInstantiatedFromStaticDataMember()) {
10459 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10460 assert(MSInfo && "Missing member specialization information?");
10461 if (MSInfo->getPointOfInstantiation().isInvalid() &&
10462 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
10463 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redl2ac2c722011-04-29 08:19:30 +000010464 // This is a modification of an existing AST node. Notify listeners.
10465 if (ASTMutationListener *L = getASTMutationListener())
10466 L->StaticDataMemberInstantiated(Var);
Chandler Carruth54080172010-08-25 08:44:16 +000010467 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +000010468 }
10469 }
Mike Stump11289f42009-09-09 15:08:12 +000010470
John McCall15dd4042011-02-21 19:25:48 +000010471 // Keep track of used but undefined variables. We make a hole in
10472 // the warning for static const data members with in-line
10473 // initializers.
John McCall83779672011-02-19 02:53:41 +000010474 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +000010475 && Var->getLinkage() != ExternalLinkage
10476 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +000010477 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
10478 if (old.isInvalid()) old = Loc;
10479 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +000010480
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010481 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +000010482 return;
Sam Weinigbae69142009-09-11 03:29:30 +000010483 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010484}
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010485
Douglas Gregor5597ab42010-05-07 23:12:07 +000010486namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +000010487 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +000010488 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +000010489 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +000010490 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10491 Sema &S;
10492 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010493
Douglas Gregor5597ab42010-05-07 23:12:07 +000010494 public:
10495 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010496
Douglas Gregor5597ab42010-05-07 23:12:07 +000010497 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010498
10499 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10500 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010501 };
10502}
10503
Chandler Carruthaf80f662010-06-09 08:17:30 +000010504bool MarkReferencedDecls::TraverseTemplateArgument(
10505 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010506 if (Arg.getKind() == TemplateArgument::Declaration) {
10507 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
10508 }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010509
10510 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010511}
10512
Chandler Carruthaf80f662010-06-09 08:17:30 +000010513bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010514 if (ClassTemplateSpecializationDecl *Spec
10515 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10516 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +000010517 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +000010518 }
10519
Chandler Carruthc65667c2010-06-10 10:31:57 +000010520 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +000010521}
10522
10523void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10524 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000010525 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000010526}
10527
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010528namespace {
10529 /// \brief Helper class that marks all of the declarations referenced by
10530 /// potentially-evaluated subexpressions as "referenced".
10531 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10532 Sema &S;
10533
10534 public:
10535 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10536
10537 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
10538
10539 void VisitDeclRefExpr(DeclRefExpr *E) {
10540 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10541 }
10542
10543 void VisitMemberExpr(MemberExpr *E) {
10544 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010545 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010546 }
10547
10548 void VisitCXXNewExpr(CXXNewExpr *E) {
10549 if (E->getConstructor())
10550 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
10551 if (E->getOperatorNew())
10552 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
10553 if (E->getOperatorDelete())
10554 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010555 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010556 }
10557
10558 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10559 if (E->getOperatorDelete())
10560 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000010561 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10562 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10563 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10564 S.MarkDeclarationReferenced(E->getLocStart(),
10565 S.LookupDestructor(Record));
10566 }
10567
Douglas Gregor32b3de52010-09-11 23:32:50 +000010568 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010569 }
10570
10571 void VisitCXXConstructExpr(CXXConstructExpr *E) {
10572 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010573 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010574 }
10575
10576 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
10577 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10578 }
Douglas Gregorf0873f42010-10-19 17:17:35 +000010579
10580 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10581 Visit(E->getExpr());
10582 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010583 };
10584}
10585
10586/// \brief Mark any declarations that appear within this expression or any
10587/// potentially-evaluated subexpressions as "referenced".
10588void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
10589 EvaluatedExprMarker(*this).Visit(E);
10590}
10591
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010592/// \brief Emit a diagnostic that describes an effect on the run-time behavior
10593/// of the program being compiled.
10594///
10595/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010596/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010597/// possibility that the code will actually be executable. Code in sizeof()
10598/// expressions, code used only during overload resolution, etc., are not
10599/// potentially evaluated. This routine will suppress such diagnostics or,
10600/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010601/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010602/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010603///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010604/// This routine should be used for all diagnostics that describe the run-time
10605/// behavior of a program, such as passing a non-POD value through an ellipsis.
10606/// Failure to do so will likely result in spurious diagnostics or failures
10607/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +000010608bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010609 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +000010610 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010611 case Unevaluated:
10612 // The argument will never be evaluated, so don't complain.
10613 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010614
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010615 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010616 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +000010617 if (stmt && getCurFunctionOrMethodDecl()) {
10618 FunctionScopes.back()->PossiblyUnreachableDiags.
10619 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
10620 }
10621 else
10622 Diag(Loc, PD);
10623
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010624 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010625
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010626 case PotentiallyPotentiallyEvaluated:
10627 ExprEvalContexts.back().addDiagnostic(Loc, PD);
10628 break;
10629 }
10630
10631 return false;
10632}
10633
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010634bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
10635 CallExpr *CE, FunctionDecl *FD) {
10636 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
10637 return false;
10638
10639 PartialDiagnostic Note =
10640 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
10641 << FD->getDeclName() : PDiag();
10642 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010643
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010644 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010645 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010646 PDiag(diag::err_call_function_incomplete_return)
10647 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010648 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010649 << CE->getSourceRange(),
10650 std::make_pair(NoteLoc, Note)))
10651 return true;
10652
10653 return false;
10654}
10655
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010656// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000010657// will prevent this condition from triggering, which is what we want.
10658void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
10659 SourceLocation Loc;
10660
John McCall0506e4a2009-11-11 02:41:58 +000010661 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010662 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000010663
John McCalld5707ab2009-10-12 21:59:07 +000010664 if (isa<BinaryOperator>(E)) {
10665 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010666 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000010667 return;
10668
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010669 IsOrAssign = Op->getOpcode() == BO_OrAssign;
10670
John McCallb0e419e2009-11-12 00:06:05 +000010671 // Greylist some idioms by putting them into a warning subcategory.
10672 if (ObjCMessageExpr *ME
10673 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
10674 Selector Sel = ME->getSelector();
10675
John McCallb0e419e2009-11-12 00:06:05 +000010676 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000010677 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +000010678 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10679
10680 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000010681 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000010682 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10683 }
John McCall0506e4a2009-11-11 02:41:58 +000010684
John McCalld5707ab2009-10-12 21:59:07 +000010685 Loc = Op->getOperatorLoc();
10686 } else if (isa<CXXOperatorCallExpr>(E)) {
10687 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010688 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000010689 return;
10690
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010691 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000010692 Loc = Op->getOperatorLoc();
10693 } else {
10694 // Not an assignment.
10695 return;
10696 }
10697
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000010698 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010699
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000010700 SourceLocation Open = E->getSourceRange().getBegin();
10701 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
10702 Diag(Loc, diag::note_condition_assign_silence)
10703 << FixItHint::CreateInsertion(Open, "(")
10704 << FixItHint::CreateInsertion(Close, ")");
10705
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010706 if (IsOrAssign)
10707 Diag(Loc, diag::note_condition_or_assign_to_comparison)
10708 << FixItHint::CreateReplacement(Loc, "!=");
10709 else
10710 Diag(Loc, diag::note_condition_assign_to_comparison)
10711 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +000010712}
10713
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010714/// \brief Redundant parentheses over an equality comparison can indicate
10715/// that the user intended an assignment used as condition.
10716void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010717 // Don't warn if the parens came from a macro.
10718 SourceLocation parenLoc = parenE->getLocStart();
10719 if (parenLoc.isInvalid() || parenLoc.isMacroID())
10720 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000010721 // Don't warn for dependent expressions.
10722 if (parenE->isTypeDependent())
10723 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010724
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010725 Expr *E = parenE->IgnoreParens();
10726
10727 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000010728 if (opE->getOpcode() == BO_EQ &&
10729 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
10730 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010731 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000010732
Ted Kremenekae022092011-02-02 02:20:30 +000010733 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +000010734 Diag(Loc, diag::note_equality_comparison_silence)
10735 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
10736 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000010737 Diag(Loc, diag::note_equality_comparison_to_assign)
10738 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010739 }
10740}
10741
John Wiegley01296292011-04-08 18:41:53 +000010742ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000010743 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010744 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
10745 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000010746
John McCall0009fcc2011-04-26 20:42:42 +000010747 ExprResult result = CheckPlaceholderExpr(E);
10748 if (result.isInvalid()) return ExprError();
10749 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000010750
John McCall0009fcc2011-04-26 20:42:42 +000010751 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +000010752 if (getLangOptions().CPlusPlus)
10753 return CheckCXXBooleanCondition(E); // C++ 6.4p4
10754
John Wiegley01296292011-04-08 18:41:53 +000010755 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
10756 if (ERes.isInvalid())
10757 return ExprError();
10758 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +000010759
10760 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000010761 if (!T->isScalarType()) { // C99 6.8.4.1p1
10762 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
10763 << T << E->getSourceRange();
10764 return ExprError();
10765 }
John McCalld5707ab2009-10-12 21:59:07 +000010766 }
10767
John Wiegley01296292011-04-08 18:41:53 +000010768 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +000010769}
Douglas Gregore60e41a2010-05-06 17:25:47 +000010770
John McCalldadc5752010-08-24 06:29:42 +000010771ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
10772 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +000010773 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +000010774 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010775
10776 return CheckBooleanCondition(Sub, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000010777}
John McCall36e7fe32010-10-12 00:20:44 +000010778
John McCall31996342011-04-07 08:22:57 +000010779namespace {
John McCall2979fe02011-04-12 00:42:48 +000010780 /// A visitor for rebuilding a call to an __unknown_any expression
10781 /// to have an appropriate type.
10782 struct RebuildUnknownAnyFunction
10783 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
10784
10785 Sema &S;
10786
10787 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
10788
10789 ExprResult VisitStmt(Stmt *S) {
10790 llvm_unreachable("unexpected statement!");
10791 return ExprError();
10792 }
10793
10794 ExprResult VisitExpr(Expr *expr) {
10795 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
10796 << expr->getSourceRange();
10797 return ExprError();
10798 }
10799
10800 /// Rebuild an expression which simply semantically wraps another
10801 /// expression which it shares the type and value kind of.
10802 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10803 ExprResult subResult = Visit(expr->getSubExpr());
10804 if (subResult.isInvalid()) return ExprError();
10805
10806 Expr *subExpr = subResult.take();
10807 expr->setSubExpr(subExpr);
10808 expr->setType(subExpr->getType());
10809 expr->setValueKind(subExpr->getValueKind());
10810 assert(expr->getObjectKind() == OK_Ordinary);
10811 return expr;
10812 }
10813
10814 ExprResult VisitParenExpr(ParenExpr *paren) {
10815 return rebuildSugarExpr(paren);
10816 }
10817
10818 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10819 return rebuildSugarExpr(op);
10820 }
10821
10822 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10823 ExprResult subResult = Visit(op->getSubExpr());
10824 if (subResult.isInvalid()) return ExprError();
10825
10826 Expr *subExpr = subResult.take();
10827 op->setSubExpr(subExpr);
10828 op->setType(S.Context.getPointerType(subExpr->getType()));
10829 assert(op->getValueKind() == VK_RValue);
10830 assert(op->getObjectKind() == OK_Ordinary);
10831 return op;
10832 }
10833
10834 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
10835 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
10836
10837 expr->setType(decl->getType());
10838
10839 assert(expr->getValueKind() == VK_RValue);
10840 if (S.getLangOptions().CPlusPlus &&
10841 !(isa<CXXMethodDecl>(decl) &&
10842 cast<CXXMethodDecl>(decl)->isInstance()))
10843 expr->setValueKind(VK_LValue);
10844
10845 return expr;
10846 }
10847
10848 ExprResult VisitMemberExpr(MemberExpr *mem) {
10849 return resolveDecl(mem, mem->getMemberDecl());
10850 }
10851
10852 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
10853 return resolveDecl(ref, ref->getDecl());
10854 }
10855 };
10856}
10857
10858/// Given a function expression of unknown-any type, try to rebuild it
10859/// to have a function type.
10860static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
10861 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
10862 if (result.isInvalid()) return ExprError();
10863 return S.DefaultFunctionArrayConversion(result.take());
10864}
10865
10866namespace {
John McCall2d2e8702011-04-11 07:02:50 +000010867 /// A visitor for rebuilding an expression of type __unknown_anytype
10868 /// into one which resolves the type directly on the referring
10869 /// expression. Strict preservation of the original source
10870 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000010871 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000010872 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000010873
10874 Sema &S;
10875
10876 /// The current destination type.
10877 QualType DestType;
10878
10879 RebuildUnknownAnyExpr(Sema &S, QualType castType)
10880 : S(S), DestType(castType) {}
10881
John McCall39439732011-04-09 22:50:59 +000010882 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000010883 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +000010884 return ExprError();
John McCall31996342011-04-07 08:22:57 +000010885 }
10886
John McCall2d2e8702011-04-11 07:02:50 +000010887 ExprResult VisitExpr(Expr *expr) {
10888 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10889 << expr->getSourceRange();
10890 return ExprError();
John McCall31996342011-04-07 08:22:57 +000010891 }
10892
John McCall2d2e8702011-04-11 07:02:50 +000010893 ExprResult VisitCallExpr(CallExpr *call);
10894 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
10895
John McCall39439732011-04-09 22:50:59 +000010896 /// Rebuild an expression which simply semantically wraps another
10897 /// expression which it shares the type and value kind of.
10898 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10899 ExprResult subResult = Visit(expr->getSubExpr());
John McCall2979fe02011-04-12 00:42:48 +000010900 if (subResult.isInvalid()) return ExprError();
John McCall39439732011-04-09 22:50:59 +000010901 Expr *subExpr = subResult.take();
10902 expr->setSubExpr(subExpr);
10903 expr->setType(subExpr->getType());
10904 expr->setValueKind(subExpr->getValueKind());
10905 assert(expr->getObjectKind() == OK_Ordinary);
10906 return expr;
10907 }
John McCall31996342011-04-07 08:22:57 +000010908
John McCall39439732011-04-09 22:50:59 +000010909 ExprResult VisitParenExpr(ParenExpr *paren) {
10910 return rebuildSugarExpr(paren);
10911 }
10912
10913 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10914 return rebuildSugarExpr(op);
10915 }
10916
John McCall2979fe02011-04-12 00:42:48 +000010917 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10918 const PointerType *ptr = DestType->getAs<PointerType>();
10919 if (!ptr) {
10920 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
10921 << op->getSourceRange();
10922 return ExprError();
10923 }
10924 assert(op->getValueKind() == VK_RValue);
10925 assert(op->getObjectKind() == OK_Ordinary);
10926 op->setType(DestType);
10927
10928 // Build the sub-expression as if it were an object of the pointee type.
10929 DestType = ptr->getPointeeType();
10930 ExprResult subResult = Visit(op->getSubExpr());
10931 if (subResult.isInvalid()) return ExprError();
10932 op->setSubExpr(subResult.take());
10933 return op;
10934 }
10935
John McCall2d2e8702011-04-11 07:02:50 +000010936 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCall39439732011-04-09 22:50:59 +000010937
John McCall2979fe02011-04-12 00:42:48 +000010938 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCall39439732011-04-09 22:50:59 +000010939
John McCall2979fe02011-04-12 00:42:48 +000010940 ExprResult VisitMemberExpr(MemberExpr *mem) {
10941 return resolveDecl(mem, mem->getMemberDecl());
10942 }
John McCall39439732011-04-09 22:50:59 +000010943
10944 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall2d2e8702011-04-11 07:02:50 +000010945 return resolveDecl(ref, ref->getDecl());
John McCall31996342011-04-07 08:22:57 +000010946 }
10947 };
10948}
10949
John McCall2d2e8702011-04-11 07:02:50 +000010950/// Rebuilds a call expression which yielded __unknown_anytype.
10951ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
10952 Expr *callee = call->getCallee();
10953
10954 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +000010955 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +000010956 FK_FunctionPointer,
10957 FK_BlockPointer
10958 };
10959
10960 FnKind kind;
10961 QualType type = callee->getType();
John McCall4adb38c2011-04-27 00:36:17 +000010962 if (type == S.Context.BoundMemberTy) {
10963 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
10964 kind = FK_MemberFunction;
10965 type = Expr::findBoundMemberType(callee);
John McCall2d2e8702011-04-11 07:02:50 +000010966 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
10967 type = ptr->getPointeeType();
10968 kind = FK_FunctionPointer;
10969 } else {
10970 type = type->castAs<BlockPointerType>()->getPointeeType();
10971 kind = FK_BlockPointer;
10972 }
10973 const FunctionType *fnType = type->castAs<FunctionType>();
10974
10975 // Verify that this is a legal result type of a function.
10976 if (DestType->isArrayType() || DestType->isFunctionType()) {
10977 unsigned diagID = diag::err_func_returning_array_function;
10978 if (kind == FK_BlockPointer)
10979 diagID = diag::err_block_returning_array_function;
10980
10981 S.Diag(call->getExprLoc(), diagID)
10982 << DestType->isFunctionType() << DestType;
10983 return ExprError();
10984 }
10985
10986 // Otherwise, go ahead and set DestType as the call's result.
10987 call->setType(DestType.getNonLValueExprType(S.Context));
10988 call->setValueKind(Expr::getValueKindForType(DestType));
10989 assert(call->getObjectKind() == OK_Ordinary);
10990
10991 // Rebuild the function type, replacing the result type with DestType.
10992 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
10993 DestType = S.Context.getFunctionType(DestType,
10994 proto->arg_type_begin(),
10995 proto->getNumArgs(),
10996 proto->getExtProtoInfo());
10997 else
10998 DestType = S.Context.getFunctionNoProtoType(DestType,
10999 fnType->getExtInfo());
11000
11001 // Rebuild the appropriate pointer-to-function type.
11002 switch (kind) {
John McCall4adb38c2011-04-27 00:36:17 +000011003 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +000011004 // Nothing to do.
11005 break;
11006
11007 case FK_FunctionPointer:
11008 DestType = S.Context.getPointerType(DestType);
11009 break;
11010
11011 case FK_BlockPointer:
11012 DestType = S.Context.getBlockPointerType(DestType);
11013 break;
11014 }
11015
11016 // Finally, we can recurse.
11017 ExprResult calleeResult = Visit(callee);
11018 if (!calleeResult.isUsable()) return ExprError();
11019 call->setCallee(calleeResult.take());
11020
11021 // Bind a temporary if necessary.
11022 return S.MaybeBindToTemporary(call);
11023}
11024
11025ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall2979fe02011-04-12 00:42:48 +000011026 ObjCMethodDecl *method = msg->getMethodDecl();
11027 assert(method && "__unknown_anytype message without result type?");
John McCall2d2e8702011-04-11 07:02:50 +000011028
John McCall2979fe02011-04-12 00:42:48 +000011029 // Verify that this is a legal result type of a call.
11030 if (DestType->isArrayType() || DestType->isFunctionType()) {
11031 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
11032 << DestType->isFunctionType() << DestType;
11033 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011034 }
11035
John McCall2979fe02011-04-12 00:42:48 +000011036 assert(method->getResultType() == S.Context.UnknownAnyTy);
11037 method->setResultType(DestType);
11038
John McCall2d2e8702011-04-11 07:02:50 +000011039 // Change the type of the message.
John McCall2979fe02011-04-12 00:42:48 +000011040 msg->setType(DestType.getNonReferenceType());
11041 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000011042
John McCall2979fe02011-04-12 00:42:48 +000011043 return S.MaybeBindToTemporary(msg);
John McCall2d2e8702011-04-11 07:02:50 +000011044}
11045
11046ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall2979fe02011-04-12 00:42:48 +000011047 // The only case we should ever see here is a function-to-pointer decay.
John McCall2d2e8702011-04-11 07:02:50 +000011048 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall2d2e8702011-04-11 07:02:50 +000011049 assert(ice->getValueKind() == VK_RValue);
11050 assert(ice->getObjectKind() == OK_Ordinary);
11051
John McCall2979fe02011-04-12 00:42:48 +000011052 ice->setType(DestType);
11053
John McCall2d2e8702011-04-11 07:02:50 +000011054 // Rebuild the sub-expression as the pointee (function) type.
11055 DestType = DestType->castAs<PointerType>()->getPointeeType();
11056
11057 ExprResult result = Visit(ice->getSubExpr());
11058 if (!result.isUsable()) return ExprError();
11059
11060 ice->setSubExpr(result.take());
11061 return S.Owned(ice);
11062}
11063
John McCall2979fe02011-04-12 00:42:48 +000011064ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall2d2e8702011-04-11 07:02:50 +000011065 ExprValueKind valueKind = VK_LValue;
John McCall2d2e8702011-04-11 07:02:50 +000011066 QualType type = DestType;
11067
11068 // We know how to make this work for certain kinds of decls:
11069
11070 // - functions
John McCall2979fe02011-04-12 00:42:48 +000011071 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCall2d2e8702011-04-11 07:02:50 +000011072 // This is true because FunctionDecls must always have function
11073 // type, so we can't be resolving the entire thing at once.
11074 assert(type->isFunctionType());
11075
John McCall4adb38c2011-04-27 00:36:17 +000011076 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
11077 if (method->isInstance()) {
11078 valueKind = VK_RValue;
11079 type = S.Context.BoundMemberTy;
11080 }
11081
John McCall2d2e8702011-04-11 07:02:50 +000011082 // Function references aren't l-values in C.
11083 if (!S.getLangOptions().CPlusPlus)
11084 valueKind = VK_RValue;
11085
11086 // - variables
11087 } else if (isa<VarDecl>(decl)) {
John McCall2979fe02011-04-12 00:42:48 +000011088 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
11089 type = refTy->getPointeeType();
John McCall2d2e8702011-04-11 07:02:50 +000011090 } else if (type->isFunctionType()) {
John McCall2979fe02011-04-12 00:42:48 +000011091 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
11092 << decl << expr->getSourceRange();
11093 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011094 }
11095
11096 // - nothing else
11097 } else {
11098 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11099 << decl << expr->getSourceRange();
11100 return ExprError();
11101 }
11102
John McCall2979fe02011-04-12 00:42:48 +000011103 decl->setType(DestType);
11104 expr->setType(type);
11105 expr->setValueKind(valueKind);
11106 return S.Owned(expr);
John McCall2d2e8702011-04-11 07:02:50 +000011107}
11108
John McCall31996342011-04-07 08:22:57 +000011109/// Check a cast of an unknown-any type. We intentionally only
11110/// trigger this for C-style casts.
John Wiegley01296292011-04-08 18:41:53 +000011111ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
11112 Expr *castExpr, CastKind &castKind,
11113 ExprValueKind &VK, CXXCastPath &path) {
John McCall31996342011-04-07 08:22:57 +000011114 // Rewrite the casted expression from scratch.
John McCall39439732011-04-09 22:50:59 +000011115 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
11116 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000011117
John McCall39439732011-04-09 22:50:59 +000011118 castExpr = result.take();
11119 VK = castExpr->getValueKind();
11120 castKind = CK_NoOp;
11121
11122 return castExpr;
John McCall31996342011-04-07 08:22:57 +000011123}
11124
11125static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
11126 Expr *orig = e;
John McCall2d2e8702011-04-11 07:02:50 +000011127 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000011128 while (true) {
11129 e = e->IgnoreParenImpCasts();
John McCall2d2e8702011-04-11 07:02:50 +000011130 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall31996342011-04-07 08:22:57 +000011131 e = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011132 diagID = diag::err_uncasted_call_of_unknown_any;
11133 } else {
John McCall31996342011-04-07 08:22:57 +000011134 break;
John McCall2d2e8702011-04-11 07:02:50 +000011135 }
John McCall31996342011-04-07 08:22:57 +000011136 }
11137
John McCall2d2e8702011-04-11 07:02:50 +000011138 SourceLocation loc;
11139 NamedDecl *d;
11140 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11141 loc = ref->getLocation();
11142 d = ref->getDecl();
11143 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
11144 loc = mem->getMemberLoc();
11145 d = mem->getMemberDecl();
11146 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
11147 diagID = diag::err_uncasted_call_of_unknown_any;
11148 loc = msg->getSelectorLoc();
11149 d = msg->getMethodDecl();
11150 assert(d && "unknown method returning __unknown_any?");
11151 } else {
11152 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11153 << e->getSourceRange();
11154 return ExprError();
11155 }
11156
11157 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000011158
11159 // Never recoverable.
11160 return ExprError();
11161}
11162
John McCall36e7fe32010-10-12 00:20:44 +000011163/// Check for operands with placeholder types and complain if found.
11164/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000011165ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +000011166 // Placeholder types are always *exactly* the appropriate builtin type.
11167 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +000011168
John McCall31996342011-04-07 08:22:57 +000011169 // Overloaded expressions.
11170 if (type == Context.OverloadTy)
11171 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +000011172 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +000011173 QualType(),
11174 diag::err_ovl_unresolvable);
11175
John McCall0009fcc2011-04-26 20:42:42 +000011176 // Bound member functions.
11177 if (type == Context.BoundMemberTy) {
11178 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
11179 << E->getSourceRange();
11180 return ExprError();
11181 }
11182
John McCall31996342011-04-07 08:22:57 +000011183 // Expressions of unknown type.
11184 if (type == Context.UnknownAnyTy)
11185 return diagnoseUnknownAnyExpr(*this, E);
11186
11187 assert(!type->isPlaceholderType());
11188 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +000011189}
Richard Trieu2c850c02011-04-21 21:44:26 +000011190
11191bool Sema::CheckCaseExpression(Expr *expr) {
11192 if (expr->isTypeDependent())
11193 return true;
11194 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
11195 return expr->getType()->isIntegralOrEnumerationType();
11196 return false;
11197}