blob: 6bccdaeb2466314a06c360b8b7781776b7c3fc33 [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);
90 Diag(D->getLocation(), diag::note_unavailable_here) << true;
91 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;
117 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
118 break;
119 }
120
Anders Carlsson73067a02010-10-22 23:37:08 +0000121 // Warn if this is used but marked unused.
122 if (D->hasAttr<UnusedAttr>())
123 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
124
Douglas Gregor171c45a2009-02-18 21:56:37 +0000125 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000126}
127
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000128/// \brief Retrieve the message suffix that should be added to a
129/// diagnostic complaining about the given function being deleted or
130/// unavailable.
131std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
132 // FIXME: C++0x implicitly-deleted special member functions could be
133 // detected here so that we could improve diagnostics to say, e.g.,
134 // "base class 'A' had a deleted copy constructor".
135 if (FD->isDeleted())
136 return std::string();
137
138 std::string Message;
139 if (FD->getAvailability(&Message))
140 return ": " + Message;
141
142 return std::string();
143}
144
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000145/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +0000146/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000147/// attribute. It warns if call does not have the sentinel argument.
148///
149void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000150 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000151 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000152 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000153 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000154
155 // FIXME: In C++0x, if any of the arguments are parameter pack
156 // expansions, we can't check for the sentinel now.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000157 int sentinelPos = attr->getSentinel();
158 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +0000159
Mike Stump87c57ac2009-05-16 07:39:55 +0000160 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
161 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000162 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000163 bool warnNotEnoughArgs = false;
164 int isMethod = 0;
165 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
166 // skip over named parameters.
167 ObjCMethodDecl::param_iterator P, E = MD->param_end();
168 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
169 if (nullPos)
170 --nullPos;
171 else
172 ++i;
173 }
174 warnNotEnoughArgs = (P != E || i >= NumArgs);
175 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000176 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000177 // skip over named parameters.
178 ObjCMethodDecl::param_iterator P, E = FD->param_end();
179 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
180 if (nullPos)
181 --nullPos;
182 else
183 ++i;
184 }
185 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000186 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000187 // block or function pointer call.
188 QualType Ty = V->getType();
189 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000190 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000191 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
192 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000193 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
194 unsigned NumArgsInProto = Proto->getNumArgs();
195 unsigned k;
196 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
197 if (nullPos)
198 --nullPos;
199 else
200 ++i;
201 }
202 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
203 }
204 if (Ty->isBlockPointerType())
205 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000206 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000207 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000208 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000209 return;
210
211 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000212 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000213 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000214 return;
215 }
216 int sentinel = i;
217 while (sentinelPos > 0 && i < NumArgs-1) {
218 --sentinelPos;
219 ++i;
220 }
221 if (sentinelPos > 0) {
222 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000223 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000224 return;
225 }
226 while (i < NumArgs-1) {
227 ++i;
228 ++sentinel;
229 }
230 Expr *sentinelExpr = Args[sentinel];
John McCall7ddbcf42010-05-06 23:53:00 +0000231 if (!sentinelExpr) return;
232 if (sentinelExpr->isTypeDependent()) return;
233 if (sentinelExpr->isValueDependent()) return;
Anders Carlssone981a8c2010-11-05 15:21:33 +0000234
235 // nullptr_t is always treated as null.
236 if (sentinelExpr->getType()->isNullPtrType()) return;
237
Fariborz Jahanianc0b0ced2010-07-14 16:37:51 +0000238 if (sentinelExpr->getType()->isAnyPointerType() &&
John McCall7ddbcf42010-05-06 23:53:00 +0000239 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
240 Expr::NPC_ValueDependentIsNull))
241 return;
242
243 // Unfortunately, __null has type 'int'.
244 if (isa<GNUNullExpr>(sentinelExpr)) return;
245
246 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
247 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000248}
249
Douglas Gregor87f95b02009-02-26 21:00:50 +0000250SourceRange Sema::getExprRange(ExprTy *E) const {
251 Expr *Ex = (Expr *)E;
252 return Ex? Ex->getSourceRange() : SourceRange();
253}
254
Chris Lattner513165e2008-07-25 21:10:04 +0000255//===----------------------------------------------------------------------===//
256// Standard Promotions and Conversions
257//===----------------------------------------------------------------------===//
258
Chris Lattner513165e2008-07-25 21:10:04 +0000259/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000260ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
Chris Lattner513165e2008-07-25 21:10:04 +0000261 QualType Ty = E->getType();
262 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
263
Chris Lattner513165e2008-07-25 21:10:04 +0000264 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000265 E = ImpCastExprToType(E, Context.getPointerType(Ty),
266 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000267 else if (Ty->isArrayType()) {
268 // In C90 mode, arrays only promote to pointers if the array expression is
269 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
270 // type 'array of type' is converted to an expression that has type 'pointer
271 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
272 // that has type 'array of type' ...". The relevant change is "an lvalue"
273 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000274 //
275 // C++ 4.2p1:
276 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
277 // T" can be converted to an rvalue of type "pointer to T".
278 //
John McCall086a4642010-11-24 05:12:34 +0000279 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000280 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
281 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000282 }
John Wiegley01296292011-04-08 18:41:53 +0000283 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000284}
285
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000286static void CheckForNullPointerDereference(Sema &S, Expr *E) {
287 // Check to see if we are dereferencing a null pointer. If so,
288 // and if not volatile-qualified, this is undefined behavior that the
289 // optimizer will delete, so warn about it. People sometimes try to use this
290 // to get a deterministic trap and are surprised by clang's behavior. This
291 // only handles the pattern "*null", which is a very syntactic check.
292 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
293 if (UO->getOpcode() == UO_Deref &&
294 UO->getSubExpr()->IgnoreParenCasts()->
295 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
296 !UO->getType().isVolatileQualified()) {
297 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
298 S.PDiag(diag::warn_indirection_through_null)
299 << UO->getSubExpr()->getSourceRange());
300 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
301 S.PDiag(diag::note_indirection_through_null));
302 }
303}
304
John Wiegley01296292011-04-08 18:41:53 +0000305ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000306 // C++ [conv.lval]p1:
307 // A glvalue of a non-function, non-array type T can be
308 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000309 if (!E->isGLValue()) return Owned(E);
John McCall34376a62010-12-04 03:47:34 +0000310
John McCall27584242010-12-06 20:48:59 +0000311 QualType T = E->getType();
312 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000313
John McCall27584242010-12-06 20:48:59 +0000314 // Create a load out of an ObjCProperty l-value, if necessary.
315 if (E->getObjectKind() == OK_ObjCProperty) {
John Wiegley01296292011-04-08 18:41:53 +0000316 ExprResult Res = ConvertPropertyForRValue(E);
317 if (Res.isInvalid())
318 return Owned(E);
319 E = Res.take();
John McCall27584242010-12-06 20:48:59 +0000320 if (!E->isGLValue())
John Wiegley01296292011-04-08 18:41:53 +0000321 return Owned(E);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000322 }
John McCall27584242010-12-06 20:48:59 +0000323
324 // We don't want to throw lvalue-to-rvalue casts on top of
325 // expressions of certain types in C++.
326 if (getLangOptions().CPlusPlus &&
327 (E->getType() == Context.OverloadTy ||
328 T->isDependentType() ||
329 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000330 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000331
332 // The C standard is actually really unclear on this point, and
333 // DR106 tells us what the result should be but not why. It's
334 // generally best to say that void types just doesn't undergo
335 // lvalue-to-rvalue at all. Note that expressions of unqualified
336 // 'void' type are never l-values, but qualified void can be.
337 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000338 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000339
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000340 CheckForNullPointerDereference(*this, E);
341
John McCall27584242010-12-06 20:48:59 +0000342 // C++ [conv.lval]p1:
343 // [...] If T is a non-class type, the type of the prvalue is the
344 // cv-unqualified version of T. Otherwise, the type of the
345 // rvalue is T.
346 //
347 // C99 6.3.2.1p2:
348 // If the lvalue has qualified type, the value has the unqualified
349 // version of the type of the lvalue; otherwise, the value has the
350 // type of the lvalue.
351 if (T.hasQualifiers())
352 T = T.getUnqualifiedType();
353
Ted Kremenekdf26df72011-03-01 18:41:00 +0000354 CheckArrayAccess(E);
Ted Kremenek64699be2011-02-16 01:57:07 +0000355
John Wiegley01296292011-04-08 18:41:53 +0000356 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
357 E, 0, VK_RValue));
John McCall27584242010-12-06 20:48:59 +0000358}
359
John Wiegley01296292011-04-08 18:41:53 +0000360ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
361 ExprResult Res = DefaultFunctionArrayConversion(E);
362 if (Res.isInvalid())
363 return ExprError();
364 Res = DefaultLvalueConversion(Res.take());
365 if (Res.isInvalid())
366 return ExprError();
367 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000368}
369
370
Chris Lattner513165e2008-07-25 21:10:04 +0000371/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000372/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000373/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000374/// apply if the array is an argument to the sizeof or address (&) operators.
375/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000376ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000377 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000378 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
379 if (Res.isInvalid())
380 return Owned(E);
381 E = Res.take();
John McCallf3735e02010-12-01 04:43:34 +0000382
383 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000384 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
John McCallf3735e02010-12-01 04:43:34 +0000385
386 // Try to perform integral promotions if the object has a theoretically
387 // promotable type.
388 if (Ty->isIntegralOrUnscopedEnumerationType()) {
389 // C99 6.3.1.1p2:
390 //
391 // The following may be used in an expression wherever an int or
392 // unsigned int may be used:
393 // - an object or expression with an integer type whose integer
394 // conversion rank is less than or equal to the rank of int
395 // and unsigned int.
396 // - A bit-field of type _Bool, int, signed int, or unsigned int.
397 //
398 // If an int can represent all values of the original type, the
399 // value is converted to an int; otherwise, it is converted to an
400 // unsigned int. These are called the integer promotions. All
401 // other types are unchanged by the integer promotions.
402
403 QualType PTy = Context.isPromotableBitField(E);
404 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000405 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
406 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000407 }
408 if (Ty->isPromotableIntegerType()) {
409 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000410 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
411 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000412 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000413 }
John Wiegley01296292011-04-08 18:41:53 +0000414 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000415}
416
Chris Lattner2ce500f2008-07-25 22:25:12 +0000417/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000418/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000419/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000420ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
421 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000422 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000423
John Wiegley01296292011-04-08 18:41:53 +0000424 ExprResult Res = UsualUnaryConversions(E);
425 if (Res.isInvalid())
426 return Owned(E);
427 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000428
Chris Lattner2ce500f2008-07-25 22:25:12 +0000429 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000430 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000431 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
432
433 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000434}
435
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000436/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
437/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000438/// interfaces passed by value.
439ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000440 FunctionDecl *FDecl) {
John Wiegley01296292011-04-08 18:41:53 +0000441 ExprResult ExprRes = DefaultArgumentPromotion(E);
442 if (ExprRes.isInvalid())
443 return ExprError();
444 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000445
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000446 // __builtin_va_start takes the second argument as a "varargs" argument, but
447 // it doesn't actually do anything with it. It doesn't need to be non-pod
448 // etc.
449 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
John Wiegley01296292011-04-08 18:41:53 +0000450 return Owned(E);
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000451
John Wiegley01296292011-04-08 18:41:53 +0000452 if (E->getType()->isObjCObjectType() &&
453 DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000454 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
John Wiegley01296292011-04-08 18:41:53 +0000455 << E->getType() << CT))
456 return ExprError();
Douglas Gregor7ca84af2009-12-12 07:25:49 +0000457
Douglas Gregor253cadf2011-05-21 16:27:21 +0000458 // C++ [expr.call]p7 prohibits non-POD types.
459 if (!E->getType()->isPODType()) {
460 // C++0x [expr.call]p7:
461 // Passing a potentially-evaluated argument of class type (Clause 9)
462 // having a non-trivial copy constructor, a non-trivial move constructor,
463 // or a non-trivial destructor, with no corresponding parameter,
464 // is conditionally-supported with implementation-defined semantics.
465 bool TrivialEnough = false;
466 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
467 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
468 if (Record->hasTrivialCopyConstructor() &&
469 Record->hasTrivialMoveConstructor() &&
470 Record->hasTrivialDestructor())
471 TrivialEnough = true;
472 }
473 }
474
475 if (TrivialEnough) {
476 // Nothing to diagnose. This is okay.
477 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000478 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor253cadf2011-05-21 16:27:21 +0000479 << getLangOptions().CPlusPlus0x << E->getType()
480 << CT))
481 return ExprError();
482 }
483
John Wiegley01296292011-04-08 18:41:53 +0000484 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000485}
486
Chris Lattner513165e2008-07-25 21:10:04 +0000487/// UsualArithmeticConversions - Performs various conversions that are common to
488/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000489/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000490/// responsible for emitting appropriate error diagnostics.
491/// FIXME: verify the conversion rules for "complex int" are consistent with
492/// GCC.
John Wiegley01296292011-04-08 18:41:53 +0000493QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr, ExprResult &rhsExpr,
Chris Lattner513165e2008-07-25 21:10:04 +0000494 bool isCompAssign) {
John Wiegley01296292011-04-08 18:41:53 +0000495 if (!isCompAssign) {
496 lhsExpr = UsualUnaryConversions(lhsExpr.take());
497 if (lhsExpr.isInvalid())
498 return QualType();
499 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000500
John Wiegley01296292011-04-08 18:41:53 +0000501 rhsExpr = UsualUnaryConversions(rhsExpr.take());
502 if (rhsExpr.isInvalid())
503 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000504
Mike Stump11289f42009-09-09 15:08:12 +0000505 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000506 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000507 QualType lhs =
John Wiegley01296292011-04-08 18:41:53 +0000508 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000509 QualType rhs =
John Wiegley01296292011-04-08 18:41:53 +0000510 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000511
512 // If both types are identical, no conversion is needed.
513 if (lhs == rhs)
514 return lhs;
515
516 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
517 // The caller can deal with this (e.g. pointer + int).
518 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
519 return lhs;
520
John McCalld005ac92010-11-13 08:17:45 +0000521 // Apply unary and bitfield promotions to the LHS's type.
522 QualType lhs_unpromoted = lhs;
523 if (lhs->isPromotableIntegerType())
524 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley01296292011-04-08 18:41:53 +0000525 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000526 if (!LHSBitfieldPromoteTy.isNull())
527 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000528 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000529 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000530
John McCalld005ac92010-11-13 08:17:45 +0000531 // If both types are identical, no conversion is needed.
532 if (lhs == rhs)
533 return lhs;
534
535 // At this point, we have two different arithmetic types.
536
537 // Handle complex types first (C99 6.3.1.8p1).
538 bool LHSComplexFloat = lhs->isComplexType();
539 bool RHSComplexFloat = rhs->isComplexType();
540 if (LHSComplexFloat || RHSComplexFloat) {
541 // if we have an integer operand, the result is the complex type.
542
John McCallc5e62b42010-11-13 09:02:35 +0000543 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
544 if (rhs->isIntegerType()) {
545 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000546 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
547 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000548 } else {
549 assert(rhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000550 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000551 }
John McCalld005ac92010-11-13 08:17:45 +0000552 return lhs;
553 }
554
John McCallc5e62b42010-11-13 09:02:35 +0000555 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
556 if (!isCompAssign) {
557 // int -> float -> _Complex float
558 if (lhs->isIntegerType()) {
559 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000560 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_IntegralToFloating);
561 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000562 } else {
563 assert(lhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000564 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000565 }
566 }
John McCalld005ac92010-11-13 08:17:45 +0000567 return rhs;
568 }
569
570 // This handles complex/complex, complex/float, or float/complex.
571 // When both operands are complex, the shorter operand is converted to the
572 // type of the longer, and that is the type of the result. This corresponds
573 // to what is done when combining two real floating-point operands.
574 // The fun begins when size promotion occur across type domains.
575 // From H&S 6.3.4: When one operand is complex and the other is a real
576 // floating-point type, the less precise type is converted, within it's
577 // real or complex domain, to the precision of the other type. For example,
578 // when combining a "long double" with a "double _Complex", the
579 // "double _Complex" is promoted to "long double _Complex".
580 int order = Context.getFloatingTypeOrder(lhs, rhs);
581
582 // If both are complex, just cast to the more precise type.
583 if (LHSComplexFloat && RHSComplexFloat) {
584 if (order > 0) {
585 // _Complex float -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000586 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000587 return lhs;
588
589 } else if (order < 0) {
590 // _Complex float -> _Complex double
591 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000592 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000593 return rhs;
594 }
595 return lhs;
596 }
597
598 // If just the LHS is complex, the RHS needs to be converted,
599 // and the LHS might need to be promoted.
600 if (LHSComplexFloat) {
601 if (order > 0) { // LHS is wider
602 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000603 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000604 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
605 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000606 return lhs;
607 }
608
609 // RHS is at least as wide. Find its corresponding complex type.
610 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
611
612 // double -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000613 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000614
615 // _Complex float -> _Complex double
616 if (!isCompAssign && order < 0)
John Wiegley01296292011-04-08 18:41:53 +0000617 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000618
619 return result;
620 }
621
622 // Just the RHS is complex, so the LHS needs to be converted
623 // and the RHS might need to be promoted.
624 assert(RHSComplexFloat);
625
626 if (order < 0) { // RHS is wider
627 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000628 if (!isCompAssign) {
Argyrios Kyrtzidise84389b2011-01-18 18:49:33 +0000629 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000630 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
631 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000632 }
John McCalld005ac92010-11-13 08:17:45 +0000633 return rhs;
634 }
635
636 // LHS is at least as wide. Find its corresponding complex type.
637 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
638
639 // double -> _Complex double
640 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000641 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000642
643 // _Complex float -> _Complex double
644 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +0000645 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000646
647 return result;
648 }
649
650 // Now handle "real" floating types (i.e. float, double, long double).
651 bool LHSFloat = lhs->isRealFloatingType();
652 bool RHSFloat = rhs->isRealFloatingType();
653 if (LHSFloat || RHSFloat) {
654 // If we have two real floating types, convert the smaller operand
655 // to the bigger result.
656 if (LHSFloat && RHSFloat) {
657 int order = Context.getFloatingTypeOrder(lhs, rhs);
658 if (order > 0) {
John Wiegley01296292011-04-08 18:41:53 +0000659 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000660 return lhs;
661 }
662
663 assert(order < 0 && "illegal float comparison");
664 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000665 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000666 return rhs;
667 }
668
669 // If we have an integer operand, the result is the real floating type.
670 if (LHSFloat) {
671 if (rhs->isIntegerType()) {
672 // Convert rhs to the lhs floating point type.
John Wiegley01296292011-04-08 18:41:53 +0000673 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000674 return lhs;
675 }
676
677 // Convert both sides to the appropriate complex float.
678 assert(rhs->isComplexIntegerType());
679 QualType result = Context.getComplexType(lhs);
680
681 // _Complex int -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000682 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000683
684 // float -> _Complex float
685 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000686 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000687
688 return result;
689 }
690
691 assert(RHSFloat);
692 if (lhs->isIntegerType()) {
693 // Convert lhs to the rhs floating point type.
694 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000695 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000696 return rhs;
697 }
698
699 // Convert both sides to the appropriate complex float.
700 assert(lhs->isComplexIntegerType());
701 QualType result = Context.getComplexType(rhs);
702
703 // _Complex int -> _Complex float
704 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000705 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000706
707 // float -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000708 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000709
710 return result;
711 }
712
713 // Handle GCC complex int extension.
714 // FIXME: if the operands are (int, _Complex long), we currently
715 // don't promote the complex. Also, signedness?
716 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
717 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
718 if (lhsComplexInt && rhsComplexInt) {
719 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
720 rhsComplexInt->getElementType());
721 assert(order && "inequal types with equal element ordering");
722 if (order > 0) {
723 // _Complex int -> _Complex long
John Wiegley01296292011-04-08 18:41:53 +0000724 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000725 return lhs;
726 }
727
728 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000729 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000730 return rhs;
731 } else if (lhsComplexInt) {
732 // int -> _Complex int
John Wiegley01296292011-04-08 18:41:53 +0000733 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000734 return lhs;
735 } else if (rhsComplexInt) {
736 // int -> _Complex int
737 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000738 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000739 return rhs;
740 }
741
742 // Finally, we have two differing integer types.
743 // The rules for this case are in C99 6.3.1.8
744 int compare = Context.getIntegerTypeOrder(lhs, rhs);
745 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
746 rhsSigned = rhs->hasSignedIntegerRepresentation();
747 if (lhsSigned == rhsSigned) {
748 // Same signedness; use the higher-ranked type
749 if (compare >= 0) {
John Wiegley01296292011-04-08 18:41:53 +0000750 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000751 return lhs;
752 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000753 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000754 return rhs;
755 } else if (compare != (lhsSigned ? 1 : -1)) {
756 // The unsigned type has greater than or equal rank to the
757 // signed type, so use the unsigned type
758 if (rhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000759 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000760 return lhs;
761 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000762 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000763 return rhs;
764 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
765 // The two types are different widths; if we are here, that
766 // means the signed type is larger than the unsigned type, so
767 // use the signed type.
768 if (lhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000769 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000770 return lhs;
771 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000772 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000773 return rhs;
774 } else {
775 // The signed type is higher-ranked than the unsigned type,
776 // but isn't actually any bigger (like unsigned int and long
777 // on most 32-bit systems). Use the unsigned type corresponding
778 // to the signed type.
779 QualType result =
780 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley01296292011-04-08 18:41:53 +0000781 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000782 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000783 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000784 return result;
785 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000786}
787
Chris Lattner513165e2008-07-25 21:10:04 +0000788//===----------------------------------------------------------------------===//
789// Semantic Analysis for various Expression Types
790//===----------------------------------------------------------------------===//
791
792
Peter Collingbourne91147592011-04-15 00:35:48 +0000793ExprResult
794Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
795 SourceLocation DefaultLoc,
796 SourceLocation RParenLoc,
797 Expr *ControllingExpr,
798 MultiTypeArg types,
799 MultiExprArg exprs) {
800 unsigned NumAssocs = types.size();
801 assert(NumAssocs == exprs.size());
802
803 ParsedType *ParsedTypes = types.release();
804 Expr **Exprs = exprs.release();
805
806 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
807 for (unsigned i = 0; i < NumAssocs; ++i) {
808 if (ParsedTypes[i])
809 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
810 else
811 Types[i] = 0;
812 }
813
814 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
815 ControllingExpr, Types, Exprs,
816 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000817 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000818 return ER;
819}
820
821ExprResult
822Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
823 SourceLocation DefaultLoc,
824 SourceLocation RParenLoc,
825 Expr *ControllingExpr,
826 TypeSourceInfo **Types,
827 Expr **Exprs,
828 unsigned NumAssocs) {
829 bool TypeErrorFound = false,
830 IsResultDependent = ControllingExpr->isTypeDependent(),
831 ContainsUnexpandedParameterPack
832 = ControllingExpr->containsUnexpandedParameterPack();
833
834 for (unsigned i = 0; i < NumAssocs; ++i) {
835 if (Exprs[i]->containsUnexpandedParameterPack())
836 ContainsUnexpandedParameterPack = true;
837
838 if (Types[i]) {
839 if (Types[i]->getType()->containsUnexpandedParameterPack())
840 ContainsUnexpandedParameterPack = true;
841
842 if (Types[i]->getType()->isDependentType()) {
843 IsResultDependent = true;
844 } else {
845 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
846 // complete object type other than a variably modified type."
847 unsigned D = 0;
848 if (Types[i]->getType()->isIncompleteType())
849 D = diag::err_assoc_type_incomplete;
850 else if (!Types[i]->getType()->isObjectType())
851 D = diag::err_assoc_type_nonobject;
852 else if (Types[i]->getType()->isVariablyModifiedType())
853 D = diag::err_assoc_type_variably_modified;
854
855 if (D != 0) {
856 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
857 << Types[i]->getTypeLoc().getSourceRange()
858 << Types[i]->getType();
859 TypeErrorFound = true;
860 }
861
862 // C1X 6.5.1.1p2 "No two generic associations in the same generic
863 // selection shall specify compatible types."
864 for (unsigned j = i+1; j < NumAssocs; ++j)
865 if (Types[j] && !Types[j]->getType()->isDependentType() &&
866 Context.typesAreCompatible(Types[i]->getType(),
867 Types[j]->getType())) {
868 Diag(Types[j]->getTypeLoc().getBeginLoc(),
869 diag::err_assoc_compatible_types)
870 << Types[j]->getTypeLoc().getSourceRange()
871 << Types[j]->getType()
872 << Types[i]->getType();
873 Diag(Types[i]->getTypeLoc().getBeginLoc(),
874 diag::note_compat_assoc)
875 << Types[i]->getTypeLoc().getSourceRange()
876 << Types[i]->getType();
877 TypeErrorFound = true;
878 }
879 }
880 }
881 }
882 if (TypeErrorFound)
883 return ExprError();
884
885 // If we determined that the generic selection is result-dependent, don't
886 // try to compute the result expression.
887 if (IsResultDependent)
888 return Owned(new (Context) GenericSelectionExpr(
889 Context, KeyLoc, ControllingExpr,
890 Types, Exprs, NumAssocs, DefaultLoc,
891 RParenLoc, ContainsUnexpandedParameterPack));
892
893 llvm::SmallVector<unsigned, 1> CompatIndices;
894 unsigned DefaultIndex = -1U;
895 for (unsigned i = 0; i < NumAssocs; ++i) {
896 if (!Types[i])
897 DefaultIndex = i;
898 else if (Context.typesAreCompatible(ControllingExpr->getType(),
899 Types[i]->getType()))
900 CompatIndices.push_back(i);
901 }
902
903 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
904 // type compatible with at most one of the types named in its generic
905 // association list."
906 if (CompatIndices.size() > 1) {
907 // We strip parens here because the controlling expression is typically
908 // parenthesized in macro definitions.
909 ControllingExpr = ControllingExpr->IgnoreParens();
910 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
911 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
912 << (unsigned) CompatIndices.size();
913 for (llvm::SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
914 E = CompatIndices.end(); I != E; ++I) {
915 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
916 diag::note_compat_assoc)
917 << Types[*I]->getTypeLoc().getSourceRange()
918 << Types[*I]->getType();
919 }
920 return ExprError();
921 }
922
923 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
924 // its controlling expression shall have type compatible with exactly one of
925 // the types named in its generic association list."
926 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
927 // We strip parens here because the controlling expression is typically
928 // parenthesized in macro definitions.
929 ControllingExpr = ControllingExpr->IgnoreParens();
930 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
931 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
932 return ExprError();
933 }
934
935 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
936 // type name that is compatible with the type of the controlling expression,
937 // then the result expression of the generic selection is the expression
938 // in that generic association. Otherwise, the result expression of the
939 // generic selection is the expression in the default generic association."
940 unsigned ResultIndex =
941 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
942
943 return Owned(new (Context) GenericSelectionExpr(
944 Context, KeyLoc, ControllingExpr,
945 Types, Exprs, NumAssocs, DefaultLoc,
946 RParenLoc, ContainsUnexpandedParameterPack,
947 ResultIndex));
948}
949
Steve Naroff83895f72007-09-16 03:34:24 +0000950/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000951/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
952/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
953/// multiple tokens. However, the common case is that StringToks points to one
954/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000955///
John McCalldadc5752010-08-24 06:29:42 +0000956ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +0000957Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000958 assert(NumStringToks && "Must have at least one string!");
959
Chris Lattner8a24e582009-01-16 18:51:42 +0000960 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000961 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000962 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000963
Chris Lattner23b7eb62007-06-15 23:05:46 +0000964 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000965 for (unsigned i = 0; i != NumStringToks; ++i)
966 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000967
Chris Lattner36fc8792008-02-11 00:02:17 +0000968 QualType StrTy = Context.CharTy;
Anders Carlsson6b06e182011-04-06 18:42:48 +0000969 if (Literal.AnyWide)
970 StrTy = Context.getWCharType();
971 else if (Literal.Pascal)
972 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000973
974 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +0000975 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000976 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000977
Chris Lattner36fc8792008-02-11 00:02:17 +0000978 // Get an array type for the string, according to C99 6.4.5. This includes
979 // the nul terminator character as well as the string length for pascal
980 // strings.
981 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000982 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000983 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000984
Chris Lattner5b183d82006-11-10 05:03:26 +0000985 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +0000986 return Owned(StringLiteral::Create(Context, Literal.GetString(),
987 Literal.GetStringLength(),
Anders Carlsson75245402011-04-14 00:40:03 +0000988 Literal.AnyWide, Literal.Pascal, StrTy,
Alexis Hunt3b791862010-08-30 17:47:05 +0000989 &StringTokLocs[0],
990 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000991}
992
John McCallc63de662011-02-02 13:00:07 +0000993enum CaptureResult {
994 /// No capture is required.
995 CR_NoCapture,
996
997 /// A capture is required.
998 CR_Capture,
999
John McCall351762c2011-02-07 10:33:21 +00001000 /// A by-ref capture is required.
1001 CR_CaptureByRef,
1002
John McCallc63de662011-02-02 13:00:07 +00001003 /// An error occurred when trying to capture the given variable.
1004 CR_Error
1005};
1006
1007/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +00001008///
John McCallc63de662011-02-02 13:00:07 +00001009/// \param var - the variable referenced
1010/// \param DC - the context which we couldn't capture through
1011static CaptureResult
John McCall351762c2011-02-07 10:33:21 +00001012diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001013 VarDecl *var, DeclContext *DC) {
1014 switch (S.ExprEvalContexts.back().Context) {
1015 case Sema::Unevaluated:
1016 // The argument will never be evaluated, so don't complain.
1017 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +00001018
John McCallc63de662011-02-02 13:00:07 +00001019 case Sema::PotentiallyEvaluated:
1020 case Sema::PotentiallyEvaluatedIfUsed:
1021 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +00001022
John McCallc63de662011-02-02 13:00:07 +00001023 case Sema::PotentiallyPotentiallyEvaluated:
1024 // FIXME: delay these!
1025 break;
Chris Lattner497d7b02009-04-21 22:26:47 +00001026 }
Mike Stump11289f42009-09-09 15:08:12 +00001027
John McCallc63de662011-02-02 13:00:07 +00001028 // Don't diagnose about capture if we're not actually in code right
1029 // now; in general, there are more appropriate places that will
1030 // diagnose this.
1031 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1032
John McCall92d627e2011-03-22 23:15:50 +00001033 // Certain madnesses can happen with parameter declarations, which
1034 // we want to ignore.
1035 if (isa<ParmVarDecl>(var)) {
1036 // - If the parameter still belongs to the translation unit, then
1037 // we're actually just using one parameter in the declaration of
1038 // the next. This is useful in e.g. VLAs.
1039 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1040 return CR_NoCapture;
1041
1042 // - This particular madness can happen in ill-formed default
1043 // arguments; claim it's okay and let downstream code handle it.
1044 if (S.CurContext == var->getDeclContext()->getParent())
1045 return CR_NoCapture;
1046 }
John McCallc63de662011-02-02 13:00:07 +00001047
1048 DeclarationName functionName;
1049 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1050 functionName = fn->getDeclName();
1051 // FIXME: variable from enclosing block that we couldn't capture from!
1052
1053 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1054 << var->getIdentifier() << functionName;
1055 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1056 << var->getIdentifier();
1057
1058 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +00001059}
1060
John McCall351762c2011-02-07 10:33:21 +00001061/// There is a well-formed capture at a particular scope level;
1062/// propagate it through all the nested blocks.
1063static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1064 const BlockDecl::Capture &capture) {
1065 VarDecl *var = capture.getVariable();
1066
1067 // Update all the inner blocks with the capture information.
1068 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1069 i != e; ++i) {
1070 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1071 innerBlock->Captures.push_back(
1072 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1073 /*nested*/ true, capture.getCopyExpr()));
1074 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1075 }
1076
1077 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1078}
1079
1080/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +00001081/// given value in the current context requires a variable capture.
1082///
1083/// This also keeps the captures set in the BlockScopeInfo records
1084/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +00001085static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001086 ValueDecl *value) {
1087 // Only variables ever require capture.
1088 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +00001089 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +00001090
1091 // Fast path: variables from the current context never require capture.
1092 DeclContext *DC = S.CurContext;
1093 if (var->getDeclContext() == DC) return CR_NoCapture;
1094
1095 // Only variables with local storage require capture.
1096 // FIXME: What about 'const' variables in C++?
1097 if (!var->hasLocalStorage()) return CR_NoCapture;
1098
1099 // Otherwise, we need to capture.
1100
1101 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +00001102 do {
1103 // Only blocks (and eventually C++0x closures) can capture; other
1104 // scopes don't work.
1105 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +00001106 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +00001107
1108 BlockScopeInfo *blockScope =
1109 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1110 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1111
John McCall351762c2011-02-07 10:33:21 +00001112 // Check whether we've already captured it in this block. If so,
1113 // we're done.
1114 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1115 return propagateCapture(S, functionScopesIndex,
1116 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +00001117
1118 functionScopesIndex--;
1119 DC = cast<BlockDecl>(DC)->getDeclContext();
1120 } while (var->getDeclContext() != DC);
1121
John McCall351762c2011-02-07 10:33:21 +00001122 // Okay, we descended all the way to the block that defines the variable.
1123 // Actually try to capture it.
1124 QualType type = var->getType();
1125
1126 // Prohibit variably-modified types.
1127 if (type->isVariablyModifiedType()) {
1128 S.Diag(loc, diag::err_ref_vm_type);
1129 S.Diag(var->getLocation(), diag::note_declared_at);
1130 return CR_Error;
1131 }
1132
1133 // Prohibit arrays, even in __block variables, but not references to
1134 // them.
1135 if (type->isArrayType()) {
1136 S.Diag(loc, diag::err_ref_array_type);
1137 S.Diag(var->getLocation(), diag::note_declared_at);
1138 return CR_Error;
1139 }
1140
1141 S.MarkDeclarationReferenced(loc, var);
1142
1143 // The BlocksAttr indicates the variable is bound by-reference.
1144 bool byRef = var->hasAttr<BlocksAttr>();
1145
1146 // Build a copy expression.
1147 Expr *copyExpr = 0;
John McCalla85af562011-04-28 02:15:35 +00001148 const RecordType *rtype;
1149 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1150 (rtype = type->getAs<RecordType>())) {
1151
1152 // The capture logic needs the destructor, so make sure we mark it.
1153 // Usually this is unnecessary because most local variables have
1154 // their destructors marked at declaration time, but parameters are
1155 // an exception because it's technically only the call site that
1156 // actually requires the destructor.
1157 if (isa<ParmVarDecl>(var))
1158 S.FinalizeVarWithDestructor(var, rtype);
1159
John McCall351762c2011-02-07 10:33:21 +00001160 // According to the blocks spec, the capture of a variable from
1161 // the stack requires a const copy constructor. This is not true
1162 // of the copy/move done to move a __block variable to the heap.
1163 type.addConst();
1164
1165 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1166 ExprResult result =
1167 S.PerformCopyInitialization(
1168 InitializedEntity::InitializeBlock(var->getLocation(),
1169 type, false),
1170 loc, S.Owned(declRef));
1171
1172 // Build a full-expression copy expression if initialization
1173 // succeeded and used a non-trivial constructor. Recover from
1174 // errors by pretending that the copy isn't necessary.
1175 if (!result.isInvalid() &&
1176 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1177 result = S.MaybeCreateExprWithCleanups(result);
1178 copyExpr = result.take();
1179 }
1180 }
1181
1182 // We're currently at the declarer; go back to the closure.
1183 functionScopesIndex++;
1184 BlockScopeInfo *blockScope =
1185 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1186
1187 // Build a valid capture in this scope.
1188 blockScope->Captures.push_back(
1189 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1190 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1191
1192 // Propagate that to inner captures if necessary.
1193 return propagateCapture(S, functionScopesIndex,
1194 blockScope->Captures.back());
1195}
1196
1197static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1198 const DeclarationNameInfo &NameInfo,
1199 bool byRef) {
1200 assert(isa<VarDecl>(vd) && "capturing non-variable");
1201
1202 VarDecl *var = cast<VarDecl>(vd);
1203 assert(var->hasLocalStorage() && "capturing non-local");
1204 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1205
1206 QualType exprType = var->getType().getNonReferenceType();
1207
1208 BlockDeclRefExpr *BDRE;
1209 if (!byRef) {
1210 // The variable will be bound by copy; make it const within the
1211 // closure, but record that this was done in the expression.
1212 bool constAdded = !exprType.isConstQualified();
1213 exprType.addConst();
1214
1215 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1216 NameInfo.getLoc(), false,
1217 constAdded);
1218 } else {
1219 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1220 NameInfo.getLoc(), true);
1221 }
1222
1223 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001224}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001225
John McCalldadc5752010-08-24 06:29:42 +00001226ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001227Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001228 SourceLocation Loc,
1229 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001230 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001231 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001232}
1233
John McCallf4cd4f92011-02-09 01:13:10 +00001234/// BuildDeclRefExpr - Build an expression that references a
1235/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001236ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001237Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001238 const DeclarationNameInfo &NameInfo,
1239 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001240 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001241
John McCall086a4642010-11-24 05:12:34 +00001242 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001243 SS? SS->getWithLocInContext(Context)
1244 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001245 D, NameInfo, Ty, VK);
1246
1247 // Just in case we're building an illegal pointer-to-member.
1248 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1249 E->setObjectKind(OK_BitField);
1250
1251 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001252}
1253
John McCallfeb624a2010-11-23 20:48:44 +00001254static ExprResult
1255BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1256 const CXXScopeSpec &SS, FieldDecl *Field,
1257 DeclAccessPair FoundDecl,
1258 const DeclarationNameInfo &MemberNameInfo);
1259
John McCalldadc5752010-08-24 06:29:42 +00001260ExprResult
John McCallf3a88602011-02-03 08:15:49 +00001261Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
1262 SourceLocation loc,
1263 IndirectFieldDecl *indirectField,
1264 Expr *baseObjectExpr,
1265 SourceLocation opLoc) {
1266 // First, build the expression that refers to the base object.
1267
1268 bool baseObjectIsPointer = false;
1269 Qualifiers baseQuals;
1270
1271 // Case 1: the base of the indirect field is not a field.
1272 VarDecl *baseVariable = indirectField->getVarDecl();
Douglas Gregore10f36d2011-02-18 02:44:58 +00001273 CXXScopeSpec EmptySS;
John McCallf3a88602011-02-03 08:15:49 +00001274 if (baseVariable) {
1275 assert(baseVariable->getType()->isRecordType());
1276
1277 // In principle we could have a member access expression that
1278 // accesses an anonymous struct/union that's a static member of
1279 // the base object's class. However, under the current standard,
1280 // static data members cannot be anonymous structs or unions.
1281 // Supporting this is as easy as building a MemberExpr here.
1282 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1283
1284 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1285
1286 ExprResult result =
Douglas Gregore10f36d2011-02-18 02:44:58 +00001287 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
John McCallf3a88602011-02-03 08:15:49 +00001288 if (result.isInvalid()) return ExprError();
1289
1290 baseObjectExpr = result.take();
1291 baseObjectIsPointer = false;
1292 baseQuals = baseObjectExpr->getType().getQualifiers();
1293
1294 // Case 2: the base of the indirect field is a field and the user
1295 // wrote a member expression.
1296 } else if (baseObjectExpr) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001297 // The caller provided the base object expression. Determine
1298 // whether its a pointer and whether it adds any qualifiers to the
1299 // anonymous struct/union fields we're looking into.
John McCallf3a88602011-02-03 08:15:49 +00001300 QualType objectType = baseObjectExpr->getType();
1301
1302 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1303 baseObjectIsPointer = true;
1304 objectType = ptr->getPointeeType();
1305 } else {
1306 baseObjectIsPointer = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001307 }
John McCallf3a88602011-02-03 08:15:49 +00001308 baseQuals = objectType.getQualifiers();
1309
1310 // Case 3: the base of the indirect field is a field and we should
1311 // build an implicit member access.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001312 } else {
1313 // We've found a member of an anonymous struct/union that is
1314 // inside a non-anonymous struct/union, so in a well-formed
1315 // program our base object expression is "this".
John McCallf3a88602011-02-03 08:15:49 +00001316 CXXMethodDecl *method = tryCaptureCXXThis();
1317 if (!method) {
1318 Diag(loc, diag::err_invalid_member_use_in_static_method)
1319 << indirectField->getDeclName();
1320 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001321 }
1322
John McCallf3a88602011-02-03 08:15:49 +00001323 // Our base object expression is "this".
1324 baseObjectExpr =
1325 new (Context) CXXThisExpr(loc, method->getThisType(Context),
1326 /*isImplicit=*/ true);
1327 baseObjectIsPointer = true;
1328 baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001329 }
1330
1331 // Build the implicit member references to the field of the
1332 // anonymous struct/union.
John McCallf3a88602011-02-03 08:15:49 +00001333 Expr *result = baseObjectExpr;
1334 IndirectFieldDecl::chain_iterator
1335 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCallfeb624a2010-11-23 20:48:44 +00001336
John McCallf3a88602011-02-03 08:15:49 +00001337 // Build the first member access in the chain with full information.
1338 if (!baseVariable) {
1339 FieldDecl *field = cast<FieldDecl>(*FI);
John McCallfeb624a2010-11-23 20:48:44 +00001340
John McCallf3a88602011-02-03 08:15:49 +00001341 // FIXME: use the real found-decl info!
1342 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall8ccfcb52009-09-24 19:53:00 +00001343
John McCallf3a88602011-02-03 08:15:49 +00001344 // Make a nameInfo that properly uses the anonymous name.
1345 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall8ccfcb52009-09-24 19:53:00 +00001346
John McCallf3a88602011-02-03 08:15:49 +00001347 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001348 EmptySS, field, foundDecl,
John McCallf3a88602011-02-03 08:15:49 +00001349 memberNameInfo).take();
1350 baseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +00001351
John McCallf3a88602011-02-03 08:15:49 +00001352 // FIXME: check qualified member access
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001353 }
1354
John McCallf3a88602011-02-03 08:15:49 +00001355 // In all cases, we should now skip the first declaration in the chain.
1356 ++FI;
1357
Douglas Gregore10f36d2011-02-18 02:44:58 +00001358 while (FI != FEnd) {
1359 FieldDecl *field = cast<FieldDecl>(*FI++);
John McCallf3a88602011-02-03 08:15:49 +00001360
1361 // FIXME: these are somewhat meaningless
1362 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1363 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCallf3a88602011-02-03 08:15:49 +00001364
1365 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001366 (FI == FEnd? SS : EmptySS), field,
1367 foundDecl, memberNameInfo)
John McCallf3a88602011-02-03 08:15:49 +00001368 .take();
1369 }
1370
1371 return Owned(result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001372}
1373
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001374/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001375/// possibly a list of template arguments.
1376///
1377/// If this produces template arguments, it is permitted to call
1378/// DecomposeTemplateName.
1379///
1380/// This actually loses a lot of source location information for
1381/// non-standard name kinds; we should consider preserving that in
1382/// some way.
1383static void DecomposeUnqualifiedId(Sema &SemaRef,
1384 const UnqualifiedId &Id,
1385 TemplateArgumentListInfo &Buffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001386 DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00001387 const TemplateArgumentListInfo *&TemplateArgs) {
1388 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1389 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1390 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1391
1392 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1393 Id.TemplateId->getTemplateArgs(),
1394 Id.TemplateId->NumArgs);
1395 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1396 TemplateArgsPtr.release();
1397
John McCall3e56fd42010-08-23 07:28:44 +00001398 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001399 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1400 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001401 TemplateArgs = &Buffer;
1402 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001403 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001404 TemplateArgs = 0;
1405 }
1406}
1407
John McCall2d74de92009-12-01 22:10:20 +00001408/// Determines if the given class is provably not derived from all of
1409/// the prospective base classes.
1410static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1411 CXXRecordDecl *Record,
1412 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +00001413 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +00001414 return false;
1415
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001416 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +00001417 if (!RD) return false;
1418 Record = cast<CXXRecordDecl>(RD);
1419
John McCall2d74de92009-12-01 22:10:20 +00001420 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1421 E = Record->bases_end(); I != E; ++I) {
1422 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1423 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1424 if (!BaseRT) return false;
1425
1426 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +00001427 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1428 return false;
1429 }
1430
1431 return true;
1432}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001433
John McCall2d74de92009-12-01 22:10:20 +00001434enum IMAKind {
1435 /// The reference is definitely not an instance member access.
1436 IMA_Static,
1437
1438 /// The reference may be an implicit instance member access.
1439 IMA_Mixed,
1440
1441 /// The reference may be to an instance member, but it is invalid if
1442 /// so, because the context is not an instance method.
1443 IMA_Mixed_StaticContext,
1444
1445 /// The reference may be to an instance member, but it is invalid if
1446 /// so, because the context is from an unrelated class.
1447 IMA_Mixed_Unrelated,
1448
1449 /// The reference is definitely an implicit instance member access.
1450 IMA_Instance,
1451
1452 /// The reference may be to an unresolved using declaration.
1453 IMA_Unresolved,
1454
1455 /// The reference may be to an unresolved using declaration and the
1456 /// context is not an instance method.
1457 IMA_Unresolved_StaticContext,
1458
John McCall2d74de92009-12-01 22:10:20 +00001459 /// All possible referrents are instance members and the current
1460 /// context is not an instance method.
1461 IMA_Error_StaticContext,
1462
1463 /// All possible referrents are instance members of an unrelated
1464 /// class.
1465 IMA_Error_Unrelated
1466};
1467
1468/// The given lookup names class member(s) and is not being used for
1469/// an address-of-member expression. Classify the type of access
1470/// according to whether it's possible that this reference names an
1471/// instance member. This is best-effort; it is okay to
1472/// conservatively answer "yes", in which case some errors will simply
1473/// not be caught until template-instantiation.
1474static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1475 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +00001476 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +00001477
John McCall87fe5d52010-05-20 01:18:31 +00001478 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
John McCall2d74de92009-12-01 22:10:20 +00001479 bool isStaticContext =
John McCall87fe5d52010-05-20 01:18:31 +00001480 (!isa<CXXMethodDecl>(DC) ||
1481 cast<CXXMethodDecl>(DC)->isStatic());
John McCall2d74de92009-12-01 22:10:20 +00001482
1483 if (R.isUnresolvableResult())
1484 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1485
1486 // Collect all the declaring classes of instance members we find.
1487 bool hasNonInstance = false;
Sebastian Redl34620312010-11-26 16:28:07 +00001488 bool hasField = false;
John McCall2d74de92009-12-01 22:10:20 +00001489 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1490 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCalla8ae2222010-04-06 21:38:20 +00001491 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00001492
John McCalla8ae2222010-04-06 21:38:20 +00001493 if (D->isCXXInstanceMember()) {
Sebastian Redl34620312010-11-26 16:28:07 +00001494 if (dyn_cast<FieldDecl>(D))
1495 hasField = true;
1496
John McCall2d74de92009-12-01 22:10:20 +00001497 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCall2d74de92009-12-01 22:10:20 +00001498 Classes.insert(R->getCanonicalDecl());
1499 }
1500 else
1501 hasNonInstance = true;
1502 }
1503
1504 // If we didn't find any instance members, it can't be an implicit
1505 // member reference.
1506 if (Classes.empty())
1507 return IMA_Static;
1508
1509 // If the current context is not an instance method, it can't be
1510 // an implicit member reference.
Sebastian Redl34620312010-11-26 16:28:07 +00001511 if (isStaticContext) {
1512 if (hasNonInstance)
1513 return IMA_Mixed_StaticContext;
1514
1515 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1516 // C++0x [expr.prim.general]p10:
1517 // An id-expression that denotes a non-static data member or non-static
1518 // member function of a class can only be used:
1519 // (...)
1520 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1521 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1522 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1523 if (isUnevaluatedExpression)
1524 return IMA_Mixed_StaticContext;
1525 }
1526
1527 return IMA_Error_StaticContext;
1528 }
John McCall2d74de92009-12-01 22:10:20 +00001529
Argyrios Kyrtzidis36e4ae32011-04-14 00:46:47 +00001530 CXXRecordDecl *
1531 contextClass = cast<CXXMethodDecl>(DC)->getParent()->getCanonicalDecl();
1532
1533 // [class.mfct.non-static]p3:
1534 // ...is used in the body of a non-static member function of class X,
1535 // if name lookup (3.4.1) resolves the name in the id-expression to a
1536 // non-static non-type member of some class C [...]
1537 // ...if C is not X or a base class of X, the class member access expression
1538 // is ill-formed.
1539 if (R.getNamingClass() &&
1540 contextClass != R.getNamingClass()->getCanonicalDecl() &&
1541 contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
1542 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1543
John McCall2d74de92009-12-01 22:10:20 +00001544 // If we can prove that the current context is unrelated to all the
1545 // declaring classes, it can't be an implicit member reference (in
1546 // which case it's an error if any of those members are selected).
Argyrios Kyrtzidis36e4ae32011-04-14 00:46:47 +00001547 if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
John McCall2d74de92009-12-01 22:10:20 +00001548 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1549
1550 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1551}
1552
1553/// Diagnose a reference to a field with no object available.
1554static void DiagnoseInstanceReference(Sema &SemaRef,
1555 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00001556 NamedDecl *rep,
1557 const DeclarationNameInfo &nameInfo) {
1558 SourceLocation Loc = nameInfo.getLoc();
John McCall2d74de92009-12-01 22:10:20 +00001559 SourceRange Range(Loc);
1560 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1561
John McCallf3a88602011-02-03 08:15:49 +00001562 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCall2d74de92009-12-01 22:10:20 +00001563 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1564 if (MD->isStatic()) {
1565 // "invalid use of member 'x' in static member function"
1566 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCallf3a88602011-02-03 08:15:49 +00001567 << Range << nameInfo.getName();
John McCall2d74de92009-12-01 22:10:20 +00001568 return;
1569 }
1570 }
1571
1572 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCallf3a88602011-02-03 08:15:49 +00001573 << nameInfo.getName() << Range;
John McCall2d74de92009-12-01 22:10:20 +00001574 return;
1575 }
1576
1577 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +00001578}
1579
John McCalld681c392009-12-16 08:11:27 +00001580/// Diagnose an empty lookup.
1581///
1582/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001583bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1584 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001585 DeclarationName Name = R.getLookupName();
1586
John McCalld681c392009-12-16 08:11:27 +00001587 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001588 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001589 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1590 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001591 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001592 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001593 diagnostic_suggest = diag::err_undeclared_use_suggest;
1594 }
John McCalld681c392009-12-16 08:11:27 +00001595
Douglas Gregor598b08f2009-12-31 05:20:13 +00001596 // If the original lookup was an unqualified lookup, fake an
1597 // unqualified lookup. This is useful when (for example) the
1598 // original lookup would not have found something because it was a
1599 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001600 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001601 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001602 if (isa<CXXRecordDecl>(DC)) {
1603 LookupQualifiedName(R, DC);
1604
1605 if (!R.empty()) {
1606 // Don't give errors about ambiguities in this lookup.
1607 R.suppressDiagnostics();
1608
1609 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1610 bool isInstance = CurMethod &&
1611 CurMethod->isInstance() &&
1612 DC == CurMethod->getParent();
1613
1614 // Give a code modification hint to insert 'this->'.
1615 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1616 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001617 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001618 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1619 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001620 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001621 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001622 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001623 Diag(R.getNameLoc(), diagnostic) << Name
1624 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1625 QualType DepThisType = DepMethod->getThisType(Context);
1626 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1627 R.getNameLoc(), DepThisType, false);
1628 TemplateArgumentListInfo TList;
1629 if (ULE->hasExplicitTemplateArgs())
1630 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001631
Douglas Gregore16af532011-02-28 18:50:33 +00001632 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001633 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001634 CXXDependentScopeMemberExpr *DepExpr =
1635 CXXDependentScopeMemberExpr::Create(
1636 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001637 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyfe712382010-08-20 20:54:15 +00001638 R.getLookupNameInfo(), &TList);
1639 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001640 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001641 // FIXME: we should be able to handle this case too. It is correct
1642 // to add this-> here. This is a workaround for PR7947.
1643 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001644 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001645 } else {
John McCalld681c392009-12-16 08:11:27 +00001646 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001647 }
John McCalld681c392009-12-16 08:11:27 +00001648
1649 // Do we really want to note all of these?
1650 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1651 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1652
1653 // Tell the callee to try to recover.
1654 return false;
1655 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001656
1657 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001658 }
1659 }
1660
Douglas Gregor598b08f2009-12-31 05:20:13 +00001661 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001662 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +00001663 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001664 if (!R.empty()) {
1665 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1666 if (SS.isEmpty())
1667 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1668 << FixItHint::CreateReplacement(R.getNameLoc(),
1669 R.getLookupName().getAsString());
1670 else
1671 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1672 << Name << computeDeclContext(SS, false) << R.getLookupName()
1673 << SS.getRange()
1674 << FixItHint::CreateReplacement(R.getNameLoc(),
1675 R.getLookupName().getAsString());
1676 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1677 Diag(ND->getLocation(), diag::note_previous_decl)
1678 << ND->getDeclName();
1679
1680 // Tell the callee to try to recover.
1681 return false;
1682 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001683
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001684 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1685 // FIXME: If we ended up with a typo for a type name or
1686 // Objective-C class name, we're in trouble because the parser
1687 // is in the wrong place to recover. Suggest the typo
1688 // correction, but don't make it a fix-it since we're not going
1689 // to recover well anyway.
1690 if (SS.isEmpty())
1691 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1692 else
1693 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1694 << Name << computeDeclContext(SS, false) << R.getLookupName()
1695 << SS.getRange();
1696
1697 // Don't try to recover; it won't work.
1698 return true;
1699 }
1700 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001701 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001702 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001703 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001704 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001705 else
Douglas Gregor25363982010-01-01 00:15:04 +00001706 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001707 << Name << computeDeclContext(SS, false) << Corrected
1708 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001709 return true;
1710 }
Douglas Gregor25363982010-01-01 00:15:04 +00001711 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001712 }
1713
1714 // Emit a special diagnostic for failed member lookups.
1715 // FIXME: computing the declaration context might fail here (?)
1716 if (!SS.isEmpty()) {
1717 Diag(R.getNameLoc(), diag::err_no_member)
1718 << Name << computeDeclContext(SS, false)
1719 << SS.getRange();
1720 return true;
1721 }
1722
John McCalld681c392009-12-16 08:11:27 +00001723 // Give up, we can't recover.
1724 Diag(R.getNameLoc(), diagnostic) << Name;
1725 return true;
1726}
1727
Douglas Gregor05fcf842010-11-02 20:36:02 +00001728ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1729 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001730 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1731 if (!IDecl)
1732 return 0;
1733 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1734 if (!ClassImpDecl)
1735 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001736 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001737 if (!property)
1738 return 0;
1739 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001740 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1741 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001742 return 0;
1743 return property;
1744}
1745
Douglas Gregor05fcf842010-11-02 20:36:02 +00001746bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1747 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1748 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1749 if (!IDecl)
1750 return false;
1751 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1752 if (!ClassImpDecl)
1753 return false;
1754 if (ObjCPropertyImplDecl *PIDecl
1755 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1756 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1757 PIDecl->getPropertyIvarDecl())
1758 return false;
1759
1760 return true;
1761}
1762
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001763ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1764 IdentifierInfo *II,
1765 SourceLocation NameLoc) {
1766 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001767 bool LookForIvars;
1768 if (Lookup.empty())
1769 LookForIvars = true;
1770 else if (CurMeth->isClassMethod())
1771 LookForIvars = false;
1772 else
1773 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001774 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1775 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001776 if (!LookForIvars)
1777 return 0;
1778
Fariborz Jahanian18722982010-07-17 00:59:30 +00001779 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1780 if (!IDecl)
1781 return 0;
1782 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001783 if (!ClassImpDecl)
1784 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001785 bool DynamicImplSeen = false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001786 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian18722982010-07-17 00:59:30 +00001787 if (!property)
1788 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001789 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001790 DynamicImplSeen =
1791 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001792 // property implementation has a designated ivar. No need to assume a new
1793 // one.
1794 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1795 return 0;
1796 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001797 if (!DynamicImplSeen) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001798 QualType PropType = Context.getCanonicalType(property->getType());
1799 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001800 NameLoc, NameLoc,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001801 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001802 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001803 (Expr *)0, true);
1804 ClassImpDecl->addDecl(Ivar);
1805 IDecl->makeDeclVisibleInContext(Ivar, false);
1806 property->setPropertyIvarDecl(Ivar);
1807 return Ivar;
1808 }
1809 return 0;
1810}
1811
John McCalldadc5752010-08-24 06:29:42 +00001812ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001813 CXXScopeSpec &SS,
1814 UnqualifiedId &Id,
1815 bool HasTrailingLParen,
1816 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001817 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1818 "cannot be direct & operand and have a trailing lparen");
1819
1820 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001821 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001822
John McCall10eae182009-11-30 22:42:35 +00001823 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001824
1825 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001826 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001827 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001828 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001829
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001830 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001831 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001832 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001833
John McCalle66edc12009-11-24 19:00:30 +00001834 // C++ [temp.dep.expr]p3:
1835 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001836 // -- an identifier that was declared with a dependent type,
1837 // (note: handled after lookup)
1838 // -- a template-id that is dependent,
1839 // (note: handled in BuildTemplateIdExpr)
1840 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001841 // -- a nested-name-specifier that contains a class-name that
1842 // names a dependent type.
1843 // Determine whether this is a member of an unknown specialization;
1844 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001845 bool DependentID = false;
1846 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1847 Name.getCXXNameType()->isDependentType()) {
1848 DependentID = true;
1849 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001850 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001851 if (RequireCompleteDeclContext(SS, DC))
1852 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001853 } else {
1854 DependentID = true;
1855 }
1856 }
1857
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001858 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001859 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001860 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001861
Fariborz Jahanian86151342010-07-22 23:33:21 +00001862 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001863 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001864 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001865 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001866 // Lookup the template name again to correctly establish the context in
1867 // which it was found. This is really unfortunate as we already did the
1868 // lookup to determine that it was a template name in the first place. If
1869 // this becomes a performance hit, we can work harder to preserve those
1870 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001871 bool MemberOfUnknownSpecialization;
1872 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1873 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001874
1875 if (MemberOfUnknownSpecialization ||
1876 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1877 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1878 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001879 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001880 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001881 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001882
Douglas Gregora5226932011-02-04 13:35:07 +00001883 // If the result might be in a dependent base class, this is a dependent
1884 // id-expression.
1885 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1886 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1887 TemplateArgs);
1888
John McCalle66edc12009-11-24 19:00:30 +00001889 // If this reference is in an Objective-C method, then we need to do
1890 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001891 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001892 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001893 if (E.isInvalid())
1894 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001895
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001896 if (Expr *Ex = E.takeAs<Expr>())
1897 return Owned(Ex);
1898
1899 // Synthesize ivars lazily.
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001900 if (getLangOptions().ObjCDefaultSynthProperties &&
1901 getLangOptions().ObjCNonFragileABI2) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001902 if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001903 if (const ObjCPropertyDecl *Property =
1904 canSynthesizeProvisionalIvar(II)) {
1905 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1906 Diag(Property->getLocation(), diag::note_property_declare);
1907 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001908 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1909 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001910 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001911 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001912 // for further use, this must be set to false if in class method.
1913 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001914 }
Chris Lattner59a25942008-03-31 00:36:02 +00001915 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001916
John McCalle66edc12009-11-24 19:00:30 +00001917 if (R.isAmbiguous())
1918 return ExprError();
1919
Douglas Gregor171c45a2009-02-18 21:56:37 +00001920 // Determine whether this name might be a candidate for
1921 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001922 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001923
John McCalle66edc12009-11-24 19:00:30 +00001924 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001925 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001926 // in C90, extension in C99, forbidden in C++).
1927 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1928 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1929 if (D) R.addDecl(D);
1930 }
1931
1932 // If this name wasn't predeclared and if this is not a function
1933 // call, diagnose the problem.
1934 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001935 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001936 return ExprError();
1937
1938 assert(!R.empty() &&
1939 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001940
1941 // If we found an Objective-C instance variable, let
1942 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001943 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001944 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1945 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001946 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001947 assert(E.isInvalid() || E.get());
1948 return move(E);
1949 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001950 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001951 }
Mike Stump11289f42009-09-09 15:08:12 +00001952
John McCalle66edc12009-11-24 19:00:30 +00001953 // This is guaranteed from this point on.
1954 assert(!R.empty() || ADL);
1955
John McCall2d74de92009-12-01 22:10:20 +00001956 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001957 // C++ [class.mfct.non-static]p3:
1958 // When an id-expression that is not part of a class member access
1959 // syntax and not used to form a pointer to member is used in the
1960 // body of a non-static member function of class X, if name lookup
1961 // resolves the name in the id-expression to a non-static non-type
1962 // member of some class C, the id-expression is transformed into a
1963 // class member access expression using (*this) as the
1964 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001965 //
1966 // But we don't actually need to do this for '&' operands if R
1967 // resolved to a function or overloaded function set, because the
1968 // expression is ill-formed if it actually works out to be a
1969 // non-static member function:
1970 //
1971 // C++ [expr.ref]p4:
1972 // Otherwise, if E1.E2 refers to a non-static member function. . .
1973 // [t]he expression can be used only as the left-hand operand of a
1974 // member function call.
1975 //
1976 // There are other safeguards against such uses, but it's important
1977 // to get this right here so that we don't end up making a
1978 // spuriously dependent expression if we're inside a dependent
1979 // instance method.
John McCall57500772009-12-16 12:17:52 +00001980 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001981 bool MightBeImplicitMember;
1982 if (!isAddressOfOperand)
1983 MightBeImplicitMember = true;
1984 else if (!SS.isEmpty())
1985 MightBeImplicitMember = false;
1986 else if (R.isOverloadedResult())
1987 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001988 else if (R.isUnresolvableResult())
1989 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001990 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001991 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1992 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001993
1994 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00001995 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001996 }
1997
John McCalle66edc12009-11-24 19:00:30 +00001998 if (TemplateArgs)
1999 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00002000
John McCalle66edc12009-11-24 19:00:30 +00002001 return BuildDeclarationNameExpr(SS, R, ADL);
2002}
2003
John McCall57500772009-12-16 12:17:52 +00002004/// Builds an expression which might be an implicit member expression.
John McCalldadc5752010-08-24 06:29:42 +00002005ExprResult
John McCall57500772009-12-16 12:17:52 +00002006Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
2007 LookupResult &R,
2008 const TemplateArgumentListInfo *TemplateArgs) {
2009 switch (ClassifyImplicitMemberAccess(*this, R)) {
2010 case IMA_Instance:
2011 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
2012
John McCall57500772009-12-16 12:17:52 +00002013 case IMA_Mixed:
2014 case IMA_Mixed_Unrelated:
2015 case IMA_Unresolved:
2016 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
2017
2018 case IMA_Static:
2019 case IMA_Mixed_StaticContext:
2020 case IMA_Unresolved_StaticContext:
2021 if (TemplateArgs)
2022 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
2023 return BuildDeclarationNameExpr(SS, R, false);
2024
2025 case IMA_Error_StaticContext:
2026 case IMA_Error_Unrelated:
John McCallf3a88602011-02-03 08:15:49 +00002027 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
2028 R.getLookupNameInfo());
John McCall57500772009-12-16 12:17:52 +00002029 return ExprError();
2030 }
2031
2032 llvm_unreachable("unexpected instance member access kind");
2033 return ExprError();
2034}
2035
John McCall10eae182009-11-30 22:42:35 +00002036/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2037/// declaration name, generally during template instantiation.
2038/// There's a large number of things which don't need to be done along
2039/// this path.
John McCalldadc5752010-08-24 06:29:42 +00002040ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002041Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002042 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00002043 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00002044 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002045 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00002046
John McCall0b66eb32010-05-01 00:40:08 +00002047 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00002048 return ExprError();
2049
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002050 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00002051 LookupQualifiedName(R, DC);
2052
2053 if (R.isAmbiguous())
2054 return ExprError();
2055
2056 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002057 Diag(NameInfo.getLoc(), diag::err_no_member)
2058 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002059 return ExprError();
2060 }
2061
2062 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
2063}
2064
2065/// LookupInObjCMethod - The parser has read a name in, and Sema has
2066/// detected that we're currently inside an ObjC method. Perform some
2067/// additional lookup.
2068///
2069/// Ideally, most of this would be done by lookup, but there's
2070/// actually quite a lot of extra work involved.
2071///
2072/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00002073ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002074Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00002075 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00002076 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00002077 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00002078
John McCalle66edc12009-11-24 19:00:30 +00002079 // There are two cases to handle here. 1) scoped lookup could have failed,
2080 // in which case we should look for an ivar. 2) scoped lookup could have
2081 // found a decl, but that decl is outside the current instance method (i.e.
2082 // a global variable). In these two cases, we do a lookup for an ivar with
2083 // this name, if the lookup sucedes, we replace it our current decl.
2084
2085 // If we're in a class method, we don't normally want to look for
2086 // ivars. But if we don't find anything else, and there's an
2087 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00002088 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00002089
2090 bool LookForIvars;
2091 if (Lookup.empty())
2092 LookForIvars = true;
2093 else if (IsClassMethod)
2094 LookForIvars = false;
2095 else
2096 LookForIvars = (Lookup.isSingleResult() &&
2097 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00002098 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00002099 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00002100 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00002101 ObjCInterfaceDecl *ClassDeclared;
2102 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2103 // Diagnose using an ivar in a class method.
2104 if (IsClassMethod)
2105 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2106 << IV->getDeclName());
2107
2108 // If we're referencing an invalid decl, just return this as a silent
2109 // error node. The error diagnostic was already emitted on the decl.
2110 if (IV->isInvalidDecl())
2111 return ExprError();
2112
2113 // Check if referencing a field with __attribute__((deprecated)).
2114 if (DiagnoseUseOfDecl(IV, Loc))
2115 return ExprError();
2116
2117 // Diagnose the use of an ivar outside of the declaring class.
2118 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2119 ClassDeclared != IFace)
2120 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2121
2122 // FIXME: This should use a new expr for a direct reference, don't
2123 // turn this into Self->ivar, just return a BareIVarExpr or something.
2124 IdentifierInfo &II = Context.Idents.get("self");
2125 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002126 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00002127 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00002128 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00002129 SelfName, false, false);
2130 if (SelfExpr.isInvalid())
2131 return ExprError();
2132
John Wiegley01296292011-04-08 18:41:53 +00002133 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2134 if (SelfExpr.isInvalid())
2135 return ExprError();
John McCall27584242010-12-06 20:48:59 +00002136
John McCalle66edc12009-11-24 19:00:30 +00002137 MarkDeclarationReferenced(Loc, IV);
Fariborz Jahanian82bc4362011-04-12 23:39:33 +00002138 Expr *base = SelfExpr.take();
2139 base = base->IgnoreParenImpCasts();
2140 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(base)) {
2141 const NamedDecl *ND = DE->getDecl();
2142 if (!isa<ImplicitParamDecl>(ND)) {
Fariborz Jahanian66a6c062011-04-15 17:04:42 +00002143 // relax the rule such that it is allowed to have a shadow 'self'
2144 // where stand-alone ivar can be found in this 'self' object.
2145 // This is to match gcc's behavior.
2146 ObjCInterfaceDecl *selfIFace = 0;
2147 if (const ObjCObjectPointerType *OPT =
2148 base->getType()->getAsObjCInterfacePointerType())
2149 selfIFace = OPT->getInterfaceDecl();
2150 if (!selfIFace ||
2151 !selfIFace->lookupInstanceVariable(IV->getIdentifier())) {
Fariborz Jahanian82bc4362011-04-12 23:39:33 +00002152 Diag(Loc, diag::error_implicit_ivar_access)
2153 << IV->getDeclName();
2154 Diag(ND->getLocation(), diag::note_declared_at);
2155 return ExprError();
2156 }
Fariborz Jahanian66a6c062011-04-15 17:04:42 +00002157 }
Fariborz Jahanian82bc4362011-04-12 23:39:33 +00002158 }
John McCalle66edc12009-11-24 19:00:30 +00002159 return Owned(new (Context)
2160 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00002161 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00002162 }
Chris Lattner87313662010-04-12 05:10:17 +00002163 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00002164 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00002165 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00002166 ObjCInterfaceDecl *ClassDeclared;
2167 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2168 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2169 IFace == ClassDeclared)
2170 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2171 }
2172 }
2173
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002174 if (Lookup.empty() && II && AllowBuiltinCreation) {
2175 // FIXME. Consolidate this with similar code in LookupName.
2176 if (unsigned BuiltinID = II->getBuiltinID()) {
2177 if (!(getLangOptions().CPlusPlus &&
2178 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2179 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2180 S, Lookup.isForRedeclaration(),
2181 Lookup.getNameLoc());
2182 if (D) Lookup.addDecl(D);
2183 }
2184 }
2185 }
John McCalle66edc12009-11-24 19:00:30 +00002186 // Sentinel value saying that we didn't do anything special.
2187 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00002188}
John McCalld14a8642009-11-21 08:51:07 +00002189
John McCall16df1e52010-03-30 21:47:33 +00002190/// \brief Cast a base object to a member's actual type.
2191///
2192/// Logically this happens in three phases:
2193///
2194/// * First we cast from the base type to the naming class.
2195/// The naming class is the class into which we were looking
2196/// when we found the member; it's the qualifier type if a
2197/// qualifier was provided, and otherwise it's the base type.
2198///
2199/// * Next we cast from the naming class to the declaring class.
2200/// If the member we found was brought into a class's scope by
2201/// a using declaration, this is that class; otherwise it's
2202/// the class declaring the member.
2203///
2204/// * Finally we cast from the declaring class to the "true"
2205/// declaring class of the member. This conversion does not
2206/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00002207ExprResult
2208Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002209 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002210 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002211 NamedDecl *Member) {
2212 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2213 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00002214 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002215
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002216 QualType DestRecordType;
2217 QualType DestType;
2218 QualType FromRecordType;
2219 QualType FromType = From->getType();
2220 bool PointerConversions = false;
2221 if (isa<FieldDecl>(Member)) {
2222 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002223
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002224 if (FromType->getAs<PointerType>()) {
2225 DestType = Context.getPointerType(DestRecordType);
2226 FromRecordType = FromType->getPointeeType();
2227 PointerConversions = true;
2228 } else {
2229 DestType = DestRecordType;
2230 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002231 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002232 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2233 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00002234 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002235
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002236 DestType = Method->getThisType(Context);
2237 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002238
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002239 if (FromType->getAs<PointerType>()) {
2240 FromRecordType = FromType->getPointeeType();
2241 PointerConversions = true;
2242 } else {
2243 FromRecordType = FromType;
2244 DestType = DestRecordType;
2245 }
2246 } else {
2247 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00002248 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002249 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002250
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002251 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002252 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002253
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002254 // If the unqualified types are the same, no conversion is necessary.
2255 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002256 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002257
John McCall16df1e52010-03-30 21:47:33 +00002258 SourceRange FromRange = From->getSourceRange();
2259 SourceLocation FromLoc = FromRange.getBegin();
2260
John McCall2536c6d2010-08-25 10:28:54 +00002261 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002262
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002263 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002264 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002265 // class name.
2266 //
2267 // If the member was a qualified name and the qualified referred to a
2268 // specific base subobject type, we'll cast to that intermediate type
2269 // first and then to the object in which the member is declared. That allows
2270 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2271 //
2272 // class Base { public: int x; };
2273 // class Derived1 : public Base { };
2274 // class Derived2 : public Base { };
2275 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2276 //
2277 // void VeryDerived::f() {
2278 // x = 17; // error: ambiguous base subobjects
2279 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2280 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002281 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002282 QualType QType = QualType(Qualifier->getAsType(), 0);
2283 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2284 assert(QType->isRecordType() && "lookup done with non-record type");
2285
2286 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2287
2288 // In C++98, the qualifier type doesn't actually have to be a base
2289 // type of the object type, in which case we just ignore it.
2290 // Otherwise build the appropriate casts.
2291 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002292 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002293 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002294 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002295 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002296
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002297 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002298 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002299 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2300 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002301
2302 FromType = QType;
2303 FromRecordType = QRecordType;
2304
2305 // If the qualifier type was the same as the destination type,
2306 // we're done.
2307 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002308 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002309 }
2310 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002311
John McCall16df1e52010-03-30 21:47:33 +00002312 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002313
John McCall16df1e52010-03-30 21:47:33 +00002314 // If we actually found the member through a using declaration, cast
2315 // down to the using declaration's type.
2316 //
2317 // Pointer equality is fine here because only one declaration of a
2318 // class ever has member declarations.
2319 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2320 assert(isa<UsingShadowDecl>(FoundDecl));
2321 QualType URecordType = Context.getTypeDeclType(
2322 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2323
2324 // We only need to do this if the naming-class to declaring-class
2325 // conversion is non-trivial.
2326 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2327 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002328 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002329 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002330 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002331 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002332
John McCall16df1e52010-03-30 21:47:33 +00002333 QualType UType = URecordType;
2334 if (PointerConversions)
2335 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002336 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2337 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002338 FromType = UType;
2339 FromRecordType = URecordType;
2340 }
2341
2342 // We don't do access control for the conversion from the
2343 // declaring class to the true declaring class.
2344 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002345 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002346
John McCallcf142162010-08-07 06:22:56 +00002347 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002348 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2349 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002350 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002351 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002352
John Wiegley01296292011-04-08 18:41:53 +00002353 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2354 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002355}
Douglas Gregor3256d042009-06-30 15:47:41 +00002356
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002357/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00002358static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00002359 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00002360 DeclAccessPair FoundDecl,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002361 const DeclarationNameInfo &MemberNameInfo,
2362 QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +00002363 ExprValueKind VK, ExprObjectKind OK,
John McCalle66edc12009-11-24 19:00:30 +00002364 const TemplateArgumentListInfo *TemplateArgs = 0) {
Douglas Gregorea972d32011-02-28 21:54:11 +00002365 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002366 Member, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002367 TemplateArgs, Ty, VK, OK);
Douglas Gregorc1905232009-08-26 22:36:53 +00002368}
2369
John McCallfeb624a2010-11-23 20:48:44 +00002370static ExprResult
2371BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2372 const CXXScopeSpec &SS, FieldDecl *Field,
2373 DeclAccessPair FoundDecl,
2374 const DeclarationNameInfo &MemberNameInfo) {
2375 // x.a is an l-value if 'a' has a reference type. Otherwise:
2376 // x.a is an l-value/x-value/pr-value if the base is (and note
2377 // that *x is always an l-value), except that if the base isn't
2378 // an ordinary object then we must have an rvalue.
2379 ExprValueKind VK = VK_LValue;
2380 ExprObjectKind OK = OK_Ordinary;
2381 if (!IsArrow) {
2382 if (BaseExpr->getObjectKind() == OK_Ordinary)
2383 VK = BaseExpr->getValueKind();
2384 else
2385 VK = VK_RValue;
2386 }
2387 if (VK != VK_RValue && Field->isBitField())
2388 OK = OK_BitField;
2389
2390 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2391 QualType MemberType = Field->getType();
2392 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2393 MemberType = Ref->getPointeeType();
2394 VK = VK_LValue;
2395 } else {
2396 QualType BaseType = BaseExpr->getType();
2397 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2398
2399 Qualifiers BaseQuals = BaseType.getQualifiers();
2400
2401 // GC attributes are never picked up by members.
2402 BaseQuals.removeObjCGCAttr();
2403
2404 // CVR attributes from the base are picked up by members,
2405 // except that 'mutable' members don't pick up 'const'.
2406 if (Field->isMutable()) BaseQuals.removeConst();
2407
2408 Qualifiers MemberQuals
2409 = S.Context.getCanonicalType(MemberType).getQualifiers();
2410
2411 // TR 18037 does not allow fields to be declared with address spaces.
2412 assert(!MemberQuals.hasAddressSpace());
2413
2414 Qualifiers Combined = BaseQuals + MemberQuals;
2415 if (Combined != MemberQuals)
2416 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2417 }
2418
2419 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
John Wiegley01296292011-04-08 18:41:53 +00002420 ExprResult Base =
2421 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2422 FoundDecl, Field);
2423 if (Base.isInvalid())
John McCallfeb624a2010-11-23 20:48:44 +00002424 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00002425 return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
John McCallfeb624a2010-11-23 20:48:44 +00002426 Field, FoundDecl, MemberNameInfo,
2427 MemberType, VK, OK));
2428}
2429
John McCall2d74de92009-12-01 22:10:20 +00002430/// Builds an implicit member access expression. The current context
2431/// is known to be an instance method, and the given unqualified lookup
2432/// set is known to contain only instance members, at least one of which
2433/// is from an appropriate type.
John McCalldadc5752010-08-24 06:29:42 +00002434ExprResult
John McCall2d74de92009-12-01 22:10:20 +00002435Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2436 LookupResult &R,
2437 const TemplateArgumentListInfo *TemplateArgs,
2438 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00002439 assert(!R.empty() && !R.isAmbiguous());
2440
John McCallf3a88602011-02-03 08:15:49 +00002441 SourceLocation loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00002442
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002443 // We may have found a field within an anonymous union or struct
2444 // (C++ [class.union]).
John McCalle66edc12009-11-24 19:00:30 +00002445 // FIXME: template-ids inside anonymous structs?
Francois Pichet783dd6e2010-11-21 06:08:52 +00002446 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCallf3a88602011-02-03 08:15:49 +00002447 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002448
John McCallf3a88602011-02-03 08:15:49 +00002449 // If this is known to be an instance access, go ahead and build an
2450 // implicit 'this' expression now.
John McCall2d74de92009-12-01 22:10:20 +00002451 // 'this' expression now.
John McCallf3a88602011-02-03 08:15:49 +00002452 CXXMethodDecl *method = tryCaptureCXXThis();
2453 assert(method && "didn't correctly pre-flight capture of 'this'");
2454
2455 QualType thisType = method->getThisType(Context);
2456 Expr *baseExpr = 0; // null signifies implicit access
John McCall2d74de92009-12-01 22:10:20 +00002457 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00002458 SourceLocation Loc = R.getNameLoc();
2459 if (SS.getRange().isValid())
2460 Loc = SS.getRange().getBegin();
John McCallf3a88602011-02-03 08:15:49 +00002461 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002462 }
2463
John McCallf3a88602011-02-03 08:15:49 +00002464 return BuildMemberReferenceExpr(baseExpr, thisType,
John McCall2d74de92009-12-01 22:10:20 +00002465 /*OpLoc*/ SourceLocation(),
2466 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00002467 SS,
2468 /*FirstQualifierInScope*/ 0,
2469 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00002470}
2471
John McCalle66edc12009-11-24 19:00:30 +00002472bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002473 const LookupResult &R,
2474 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002475 // Only when used directly as the postfix-expression of a call.
2476 if (!HasTrailingLParen)
2477 return false;
2478
2479 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002480 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002481 return false;
2482
2483 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002484 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002485 return false;
2486
2487 // Turn off ADL when we find certain kinds of declarations during
2488 // normal lookup:
2489 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2490 NamedDecl *D = *I;
2491
2492 // C++0x [basic.lookup.argdep]p3:
2493 // -- a declaration of a class member
2494 // Since using decls preserve this property, we check this on the
2495 // original decl.
John McCall57500772009-12-16 12:17:52 +00002496 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002497 return false;
2498
2499 // C++0x [basic.lookup.argdep]p3:
2500 // -- a block-scope function declaration that is not a
2501 // using-declaration
2502 // NOTE: we also trigger this for function templates (in fact, we
2503 // don't check the decl type at all, since all other decl types
2504 // turn off ADL anyway).
2505 if (isa<UsingShadowDecl>(D))
2506 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2507 else if (D->getDeclContext()->isFunctionOrMethod())
2508 return false;
2509
2510 // C++0x [basic.lookup.argdep]p3:
2511 // -- a declaration that is neither a function or a function
2512 // template
2513 // And also for builtin functions.
2514 if (isa<FunctionDecl>(D)) {
2515 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2516
2517 // But also builtin functions.
2518 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2519 return false;
2520 } else if (!isa<FunctionTemplateDecl>(D))
2521 return false;
2522 }
2523
2524 return true;
2525}
2526
2527
John McCalld14a8642009-11-21 08:51:07 +00002528/// Diagnoses obvious problems with the use of the given declaration
2529/// as an expression. This is only actually called for lookups that
2530/// were not overloaded, and it doesn't promise that the declaration
2531/// will in fact be used.
2532static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002533 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002534 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2535 return true;
2536 }
2537
2538 if (isa<ObjCInterfaceDecl>(D)) {
2539 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2540 return true;
2541 }
2542
2543 if (isa<NamespaceDecl>(D)) {
2544 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2545 return true;
2546 }
2547
2548 return false;
2549}
2550
John McCalldadc5752010-08-24 06:29:42 +00002551ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002552Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002553 LookupResult &R,
2554 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002555 // If this is a single, fully-resolved result and we don't need ADL,
2556 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002557 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002558 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2559 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002560
2561 // We only need to check the declaration if there's exactly one
2562 // result, because in the overloaded case the results can only be
2563 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002564 if (R.isSingleResult() &&
2565 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002566 return ExprError();
2567
John McCall58cc69d2010-01-27 01:50:18 +00002568 // Otherwise, just build an unresolved lookup expression. Suppress
2569 // any lookup-related diagnostics; we'll hash these out later, when
2570 // we've picked a target.
2571 R.suppressDiagnostics();
2572
John McCalld14a8642009-11-21 08:51:07 +00002573 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002574 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002575 SS.getWithLocInContext(Context),
2576 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002577 NeedsADL, R.isOverloadedResult(),
2578 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002579
2580 return Owned(ULE);
2581}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002582
John McCalld14a8642009-11-21 08:51:07 +00002583/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002584ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002585Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002586 const DeclarationNameInfo &NameInfo,
2587 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002588 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002589 assert(!isa<FunctionTemplateDecl>(D) &&
2590 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002591
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002592 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002593 if (CheckDeclInExpr(*this, Loc, D))
2594 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002595
Douglas Gregore7488b92009-12-01 16:58:18 +00002596 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2597 // Specifically diagnose references to class templates that are missing
2598 // a template argument list.
2599 Diag(Loc, diag::err_template_decl_ref)
2600 << Template << SS.getRange();
2601 Diag(Template->getLocation(), diag::note_template_decl_here);
2602 return ExprError();
2603 }
2604
2605 // Make sure that we're referring to a value.
2606 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2607 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002608 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002609 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002610 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002611 return ExprError();
2612 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002613
Douglas Gregor171c45a2009-02-18 21:56:37 +00002614 // Check whether this declaration can be used. Note that we suppress
2615 // this check when we're going to perform argument-dependent lookup
2616 // on this function name, because this might not be the function
2617 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002618 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002619 return ExprError();
2620
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002621 // Only create DeclRefExpr's for valid Decl's.
2622 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002623 return ExprError();
2624
John McCallf3a88602011-02-03 08:15:49 +00002625 // Handle members of anonymous structs and unions. If we got here,
2626 // and the reference is to a class member indirect field, then this
2627 // must be the subject of a pointer-to-member expression.
2628 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2629 if (!indirectField->isCXXClassMember())
2630 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2631 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002632
Chris Lattner2a9d9892008-10-20 05:16:36 +00002633 // If the identifier reference is inside a block, and it refers to a value
2634 // that is outside the block, create a BlockDeclRefExpr instead of a
2635 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2636 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002637 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002638 // We do not do this for things like enum constants, global variables, etc,
2639 // as they do not get snapshotted.
2640 //
John McCall351762c2011-02-07 10:33:21 +00002641 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002642 case CR_Error:
2643 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002644
John McCallc63de662011-02-02 13:00:07 +00002645 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002646 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2647 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2648
2649 case CR_CaptureByRef:
2650 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2651 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002652
2653 case CR_NoCapture: {
2654 // If this reference is not in a block or if the referenced
2655 // variable is within the block, create a normal DeclRefExpr.
2656
2657 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002658 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002659
2660 switch (D->getKind()) {
2661 // Ignore all the non-ValueDecl kinds.
2662#define ABSTRACT_DECL(kind)
2663#define VALUE(type, base)
2664#define DECL(type, base) \
2665 case Decl::type:
2666#include "clang/AST/DeclNodes.inc"
2667 llvm_unreachable("invalid value decl kind");
2668 return ExprError();
2669
2670 // These shouldn't make it here.
2671 case Decl::ObjCAtDefsField:
2672 case Decl::ObjCIvar:
2673 llvm_unreachable("forming non-member reference to ivar?");
2674 return ExprError();
2675
2676 // Enum constants are always r-values and never references.
2677 // Unresolved using declarations are dependent.
2678 case Decl::EnumConstant:
2679 case Decl::UnresolvedUsingValue:
2680 valueKind = VK_RValue;
2681 break;
2682
2683 // Fields and indirect fields that got here must be for
2684 // pointer-to-member expressions; we just call them l-values for
2685 // internal consistency, because this subexpression doesn't really
2686 // exist in the high-level semantics.
2687 case Decl::Field:
2688 case Decl::IndirectField:
2689 assert(getLangOptions().CPlusPlus &&
2690 "building reference to field in C?");
2691
2692 // These can't have reference type in well-formed programs, but
2693 // for internal consistency we do this anyway.
2694 type = type.getNonReferenceType();
2695 valueKind = VK_LValue;
2696 break;
2697
2698 // Non-type template parameters are either l-values or r-values
2699 // depending on the type.
2700 case Decl::NonTypeTemplateParm: {
2701 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2702 type = reftype->getPointeeType();
2703 valueKind = VK_LValue; // even if the parameter is an r-value reference
2704 break;
2705 }
2706
2707 // For non-references, we need to strip qualifiers just in case
2708 // the template parameter was declared as 'const int' or whatever.
2709 valueKind = VK_RValue;
2710 type = type.getUnqualifiedType();
2711 break;
2712 }
2713
2714 case Decl::Var:
2715 // In C, "extern void blah;" is valid and is an r-value.
2716 if (!getLangOptions().CPlusPlus &&
2717 !type.hasQualifiers() &&
2718 type->isVoidType()) {
2719 valueKind = VK_RValue;
2720 break;
2721 }
2722 // fallthrough
2723
2724 case Decl::ImplicitParam:
2725 case Decl::ParmVar:
2726 // These are always l-values.
2727 valueKind = VK_LValue;
2728 type = type.getNonReferenceType();
2729 break;
2730
2731 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002732 const FunctionType *fty = type->castAs<FunctionType>();
2733
2734 // If we're referring to a function with an __unknown_anytype
2735 // result type, make the entire expression __unknown_anytype.
2736 if (fty->getResultType() == Context.UnknownAnyTy) {
2737 type = Context.UnknownAnyTy;
2738 valueKind = VK_RValue;
2739 break;
2740 }
2741
John McCallf4cd4f92011-02-09 01:13:10 +00002742 // Functions are l-values in C++.
2743 if (getLangOptions().CPlusPlus) {
2744 valueKind = VK_LValue;
2745 break;
2746 }
2747
2748 // C99 DR 316 says that, if a function type comes from a
2749 // function definition (without a prototype), that type is only
2750 // used for checking compatibility. Therefore, when referencing
2751 // the function, we pretend that we don't have the full function
2752 // type.
John McCall2979fe02011-04-12 00:42:48 +00002753 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2754 isa<FunctionProtoType>(fty))
2755 type = Context.getFunctionNoProtoType(fty->getResultType(),
2756 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002757
2758 // Functions are r-values in C.
2759 valueKind = VK_RValue;
2760 break;
2761 }
2762
2763 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002764 // If we're referring to a method with an __unknown_anytype
2765 // result type, make the entire expression __unknown_anytype.
2766 // This should only be possible with a type written directly.
2767 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(VD->getType()))
2768 if (proto->getResultType() == Context.UnknownAnyTy) {
2769 type = Context.UnknownAnyTy;
2770 valueKind = VK_RValue;
2771 break;
2772 }
2773
John McCallf4cd4f92011-02-09 01:13:10 +00002774 // C++ methods are l-values if static, r-values if non-static.
2775 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2776 valueKind = VK_LValue;
2777 break;
2778 }
2779 // fallthrough
2780
2781 case Decl::CXXConversion:
2782 case Decl::CXXDestructor:
2783 case Decl::CXXConstructor:
2784 valueKind = VK_RValue;
2785 break;
2786 }
2787
2788 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2789 }
2790
John McCallc63de662011-02-02 13:00:07 +00002791 }
John McCall7decc9e2010-11-18 06:31:45 +00002792
John McCall351762c2011-02-07 10:33:21 +00002793 llvm_unreachable("unknown capture result");
2794 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002795}
Chris Lattnere168f762006-11-10 05:29:30 +00002796
John McCall2979fe02011-04-12 00:42:48 +00002797ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002798 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002799
Chris Lattnere168f762006-11-10 05:29:30 +00002800 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002801 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002802 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2803 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2804 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002805 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002806
Chris Lattnera81a0272008-01-12 08:14:25 +00002807 // Pre-defined identifiers are of type char[x], where x is the length of the
2808 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002809
Anders Carlsson2fb08242009-09-08 18:24:21 +00002810 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002811 if (!currentDecl && getCurBlock())
2812 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002813 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002814 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002815 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002816 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002817
Anders Carlsson0b209a82009-09-11 01:22:35 +00002818 QualType ResTy;
2819 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2820 ResTy = Context.DependentTy;
2821 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002822 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002823
Anders Carlsson0b209a82009-09-11 01:22:35 +00002824 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002825 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002826 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2827 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002828 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002829}
2830
John McCalldadc5752010-08-24 06:29:42 +00002831ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002832 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002833 bool Invalid = false;
2834 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2835 if (Invalid)
2836 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002837
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002838 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2839 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002840 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002841 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002842
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002843 QualType Ty;
2844 if (!getLangOptions().CPlusPlus)
2845 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2846 else if (Literal.isWide())
2847 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002848 else if (Literal.isMultiChar())
2849 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002850 else
2851 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002852
Sebastian Redl20614a72009-01-20 22:23:13 +00002853 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2854 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002855 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002856}
2857
John McCalldadc5752010-08-24 06:29:42 +00002858ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002859 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002860 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2861 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002862 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002863 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002864 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002865 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002866 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002867
Chris Lattner23b7eb62007-06-15 23:05:46 +00002868 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002869 // Add padding so that NumericLiteralParser can overread by one character.
2870 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002871 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002872
Chris Lattner67ca9252007-05-21 01:08:44 +00002873 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002874 bool Invalid = false;
2875 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2876 if (Invalid)
2877 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002878
Mike Stump11289f42009-09-09 15:08:12 +00002879 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002880 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002881 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002882 return ExprError();
2883
Chris Lattner1c20a172007-08-26 03:42:43 +00002884 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002885
Chris Lattner1c20a172007-08-26 03:42:43 +00002886 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002887 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002888 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002889 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002890 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002891 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002892 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002893 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002894
2895 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2896
John McCall53b93a02009-12-24 09:08:04 +00002897 using llvm::APFloat;
2898 APFloat Val(Format);
2899
2900 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002901
2902 // Overflow is always an error, but underflow is only an error if
2903 // we underflowed to zero (APFloat reports denormals as underflow).
2904 if ((result & APFloat::opOverflow) ||
2905 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002906 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002907 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002908 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002909 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002910 APFloat::getLargest(Format).toString(buffer);
2911 } else {
John McCall62abc942010-02-26 23:35:57 +00002912 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002913 APFloat::getSmallest(Format).toString(buffer);
2914 }
2915
2916 Diag(Tok.getLocation(), diagnostic)
2917 << Ty
2918 << llvm::StringRef(buffer.data(), buffer.size());
2919 }
2920
2921 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002922 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002923
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002924 if (Ty == Context.DoubleTy) {
2925 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002926 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002927 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2928 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002929 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002930 }
2931 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002932 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002933 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002934 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002935 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002936
Neil Boothac582c52007-08-29 22:00:19 +00002937 // long long is a C99 feature.
2938 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002939 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002940 Diag(Tok.getLocation(), diag::ext_longlong);
2941
Chris Lattner67ca9252007-05-21 01:08:44 +00002942 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002943 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002944
Chris Lattner67ca9252007-05-21 01:08:44 +00002945 if (Literal.GetIntegerValue(ResultVal)) {
2946 // If this value didn't fit into uintmax_t, warn and force to ull.
2947 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002948 Ty = Context.UnsignedLongLongTy;
2949 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002950 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002951 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002952 // If this value fits into a ULL, try to figure out what else it fits into
2953 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002954
Chris Lattner67ca9252007-05-21 01:08:44 +00002955 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2956 // be an unsigned int.
2957 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2958
2959 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002960 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002961 if (!Literal.isLong && !Literal.isLongLong) {
2962 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002963 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002964
Chris Lattner67ca9252007-05-21 01:08:44 +00002965 // Does it fit in a unsigned int?
2966 if (ResultVal.isIntN(IntSize)) {
2967 // Does it fit in a signed int?
2968 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002969 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002970 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002971 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002972 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002973 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002974 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002975
Chris Lattner67ca9252007-05-21 01:08:44 +00002976 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002977 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002978 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002979
Chris Lattner67ca9252007-05-21 01:08:44 +00002980 // Does it fit in a unsigned long?
2981 if (ResultVal.isIntN(LongSize)) {
2982 // Does it fit in a signed long?
2983 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002984 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002985 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002986 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002987 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002988 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002989 }
2990
Chris Lattner67ca9252007-05-21 01:08:44 +00002991 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002992 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00002993 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002994
Chris Lattner67ca9252007-05-21 01:08:44 +00002995 // Does it fit in a unsigned long long?
2996 if (ResultVal.isIntN(LongLongSize)) {
2997 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002998 // To be compatible with MSVC, hex integer literals ending with the
2999 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00003000 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3001 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003002 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00003003 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003004 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00003005 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00003006 }
3007 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003008
Chris Lattner67ca9252007-05-21 01:08:44 +00003009 // If we still couldn't decide a type, we probably have something that
3010 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003011 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00003012 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003013 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00003014 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00003015 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003016
Chris Lattner55258cf2008-05-09 05:59:00 +00003017 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00003018 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00003019 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003020 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00003021 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003022
Chris Lattner1c20a172007-08-26 03:42:43 +00003023 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3024 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00003025 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00003026 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00003027
3028 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00003029}
3030
John McCalldadc5752010-08-24 06:29:42 +00003031ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00003032 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003033 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00003034 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00003035}
3036
Steve Naroff71b59a92007-06-04 22:22:31 +00003037/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003038/// See C99 6.3.2.1p[2-4] for more details.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003039bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
3040 SourceLocation OpLoc,
3041 SourceRange ExprRange,
3042 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003043 if (exprType->isDependentType())
3044 return false;
3045
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003046 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3047 // the result is the size of the referenced type."
3048 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3049 // result shall be the alignment of the referenced type."
3050 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
3051 exprType = Ref->getPointeeType();
3052
Peter Collingbournee190dee2011-03-11 19:24:49 +00003053 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3054 // scalar or vector data type argument..."
3055 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3056 // type (C99 6.2.5p18) or void.
3057 if (ExprKind == UETT_VecStep) {
3058 if (!(exprType->isArithmeticType() || exprType->isVoidType() ||
3059 exprType->isVectorType())) {
3060 Diag(OpLoc, diag::err_vecstep_non_scalar_vector_type)
3061 << exprType << ExprRange;
3062 return true;
3063 }
3064 }
3065
Steve Naroff043d45d2007-05-15 02:32:35 +00003066 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00003067 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00003068 // alignof(function) is allowed as an extension.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003069 if (ExprKind == UETT_SizeOf)
3070 Diag(OpLoc, diag::ext_sizeof_function_type)
3071 << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00003072 return false;
3073 }
Mike Stump11289f42009-09-09 15:08:12 +00003074
Peter Collingbournee190dee2011-03-11 19:24:49 +00003075 // Allow sizeof(void)/alignof(void) as an extension. vec_step(void) is not
3076 // an extension, as void is a built-in scalar type (OpenCL 1.1 6.1.1).
Chris Lattnerb1355b12009-01-24 19:46:37 +00003077 if (exprType->isVoidType()) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00003078 if (ExprKind != UETT_VecStep)
3079 Diag(OpLoc, diag::ext_sizeof_void_type)
3080 << ExprKind << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00003081 return false;
3082 }
Mike Stump11289f42009-09-09 15:08:12 +00003083
Chris Lattner62975a72009-04-24 00:30:45 +00003084 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00003085 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00003086 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00003087 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003088
Chris Lattner62975a72009-04-24 00:30:45 +00003089 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
John McCall8b07ec22010-05-15 11:32:37 +00003090 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00003091 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Peter Collingbournee190dee2011-03-11 19:24:49 +00003092 << exprType << (ExprKind == UETT_SizeOf)
3093 << ExprRange;
Chris Lattnercd2a8c52009-04-24 22:30:50 +00003094 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00003095 }
Mike Stump11289f42009-09-09 15:08:12 +00003096
Chris Lattner62975a72009-04-24 00:30:45 +00003097 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00003098}
3099
John McCall36e7fe32010-10-12 00:20:44 +00003100static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
3101 SourceRange ExprRange) {
Chris Lattner8dff0172009-01-24 20:17:12 +00003102 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003103
Mike Stump11289f42009-09-09 15:08:12 +00003104 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00003105 if (isa<DeclRefExpr>(E))
3106 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003107
3108 // Cannot know anything else if the expression is dependent.
3109 if (E->isTypeDependent())
3110 return false;
3111
Douglas Gregor71235ec2009-05-02 02:18:30 +00003112 if (E->getBitField()) {
John McCall36e7fe32010-10-12 00:20:44 +00003113 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Douglas Gregor71235ec2009-05-02 02:18:30 +00003114 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00003115 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00003116
3117 // Alignment of a field access is always okay, so long as it isn't a
3118 // bit-field.
3119 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00003120 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003121 return false;
3122
Peter Collingbournee190dee2011-03-11 19:24:49 +00003123 return S.CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
3124 UETT_AlignOf);
3125}
3126
3127bool Sema::CheckVecStepExpr(Expr *E, SourceLocation OpLoc,
3128 SourceRange ExprRange) {
3129 E = E->IgnoreParens();
3130
3131 // Cannot know anything else if the expression is dependent.
3132 if (E->isTypeDependent())
3133 return false;
3134
3135 return CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, ExprRange,
3136 UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00003137}
3138
Douglas Gregor0950e412009-03-13 21:01:28 +00003139/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00003140ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003141Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3142 SourceLocation OpLoc,
3143 UnaryExprOrTypeTrait ExprKind,
3144 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00003145 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00003146 return ExprError();
3147
John McCallbcd03502009-12-07 02:54:59 +00003148 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00003149
Douglas Gregor0950e412009-03-13 21:01:28 +00003150 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00003151 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00003152 return ExprError();
3153
3154 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003155 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3156 Context.getSizeType(),
3157 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003158}
3159
3160/// \brief Build a sizeof or alignof expression given an expression
3161/// operand.
John McCalldadc5752010-08-24 06:29:42 +00003162ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003163Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3164 UnaryExprOrTypeTrait ExprKind,
3165 SourceRange R) {
Douglas Gregor0950e412009-03-13 21:01:28 +00003166 // Verify that the operand is valid.
3167 bool isInvalid = false;
3168 if (E->isTypeDependent()) {
3169 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003170 } else if (ExprKind == UETT_AlignOf) {
John McCall36e7fe32010-10-12 00:20:44 +00003171 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003172 } else if (ExprKind == UETT_VecStep) {
3173 isInvalid = CheckVecStepExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00003174 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00003175 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
3176 isInvalid = true;
John McCall36226622010-10-12 02:09:17 +00003177 } else if (E->getType()->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00003178 ExprResult PE = CheckPlaceholderExpr(E);
John McCall36226622010-10-12 02:09:17 +00003179 if (PE.isInvalid()) return ExprError();
Peter Collingbournee190dee2011-03-11 19:24:49 +00003180 return CreateUnaryExprOrTypeTraitExpr(PE.take(), OpLoc, ExprKind, R);
Douglas Gregor0950e412009-03-13 21:01:28 +00003181 } else {
Peter Collingbournee190dee2011-03-11 19:24:49 +00003182 isInvalid = CheckUnaryExprOrTypeTraitOperand(E->getType(), OpLoc, R,
3183 UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00003184 }
3185
3186 if (isInvalid)
3187 return ExprError();
3188
3189 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003190 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, E,
3191 Context.getSizeType(),
3192 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003193}
3194
Peter Collingbournee190dee2011-03-11 19:24:49 +00003195/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3196/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00003197/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00003198ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003199Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3200 UnaryExprOrTypeTrait ExprKind, bool isType,
3201 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00003202 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003203 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00003204
Sebastian Redl6f282892008-11-11 17:56:53 +00003205 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00003206 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00003207 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003208 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00003209 }
Sebastian Redl6f282892008-11-11 17:56:53 +00003210
Douglas Gregor0950e412009-03-13 21:01:28 +00003211 Expr *ArgEx = (Expr *)TyOrEx;
John McCalldadc5752010-08-24 06:29:42 +00003212 ExprResult Result
Peter Collingbournee190dee2011-03-11 19:24:49 +00003213 = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind,
3214 ArgEx->getSourceRange());
Douglas Gregor0950e412009-03-13 21:01:28 +00003215
Douglas Gregor0950e412009-03-13 21:01:28 +00003216 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00003217}
3218
John Wiegley01296292011-04-08 18:41:53 +00003219static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall4bc41ae2010-11-18 19:01:18 +00003220 bool isReal) {
John Wiegley01296292011-04-08 18:41:53 +00003221 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00003222 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00003223
John McCall34376a62010-12-04 03:47:34 +00003224 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00003225 if (V.get()->getObjectKind() != OK_Ordinary) {
3226 V = S.DefaultLvalueConversion(V.take());
3227 if (V.isInvalid())
3228 return QualType();
3229 }
John McCall34376a62010-12-04 03:47:34 +00003230
Chris Lattnere267f5d2007-08-26 05:39:26 +00003231 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00003232 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00003233 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00003234
Chris Lattnere267f5d2007-08-26 05:39:26 +00003235 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00003236 if (V.get()->getType()->isArithmeticType())
3237 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003238
John McCall36226622010-10-12 02:09:17 +00003239 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00003240 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00003241 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003242 if (PR.get() != V.get()) {
3243 V = move(PR);
John McCall4bc41ae2010-11-18 19:01:18 +00003244 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00003245 }
3246
Chris Lattnere267f5d2007-08-26 05:39:26 +00003247 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003248 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00003249 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003250 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003251}
3252
3253
Chris Lattnere168f762006-11-10 05:29:30 +00003254
John McCalldadc5752010-08-24 06:29:42 +00003255ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003256Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003257 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003258 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003259 switch (Kind) {
3260 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003261 case tok::plusplus: Opc = UO_PostInc; break;
3262 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003263 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003264
John McCallb268a282010-08-23 23:25:46 +00003265 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003266}
3267
John McCall4bc41ae2010-11-18 19:01:18 +00003268/// Expressions of certain arbitrary types are forbidden by C from
3269/// having l-value type. These are:
3270/// - 'void', but not qualified void
3271/// - function types
3272///
3273/// The exact rule here is C99 6.3.2.1:
3274/// An lvalue is an expression with an object type or an incomplete
3275/// type other than void.
3276static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
3277 return ((T->isVoidType() && !T.hasQualifiers()) ||
3278 T->isFunctionType());
3279}
3280
John McCalldadc5752010-08-24 06:29:42 +00003281ExprResult
John McCallb268a282010-08-23 23:25:46 +00003282Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3283 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003284 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003285 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003286 if (Result.isInvalid()) return ExprError();
3287 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003288
John McCallb268a282010-08-23 23:25:46 +00003289 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003290
Douglas Gregor40412ac2008-11-19 17:17:41 +00003291 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003292 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003293 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003294 Context.DependentTy,
3295 VK_LValue, OK_Ordinary,
3296 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003297 }
3298
Mike Stump11289f42009-09-09 15:08:12 +00003299 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003300 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003301 LHSExp->getType()->isEnumeralType() ||
3302 RHSExp->getType()->isRecordType() ||
3303 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00003304 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003305 }
3306
John McCallb268a282010-08-23 23:25:46 +00003307 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003308}
3309
3310
John McCalldadc5752010-08-24 06:29:42 +00003311ExprResult
John McCallb268a282010-08-23 23:25:46 +00003312Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3313 Expr *Idx, SourceLocation RLoc) {
3314 Expr *LHSExp = Base;
3315 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003316
Chris Lattner36d572b2007-07-16 00:14:47 +00003317 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003318 if (!LHSExp->getType()->getAs<VectorType>()) {
3319 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3320 if (Result.isInvalid())
3321 return ExprError();
3322 LHSExp = Result.take();
3323 }
3324 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3325 if (Result.isInvalid())
3326 return ExprError();
3327 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003328
Chris Lattner36d572b2007-07-16 00:14:47 +00003329 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003330 ExprValueKind VK = VK_LValue;
3331 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003332
Steve Naroffc1aadb12007-03-28 21:49:40 +00003333 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003334 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003335 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003336 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003337 Expr *BaseExpr, *IndexExpr;
3338 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003339 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3340 BaseExpr = LHSExp;
3341 IndexExpr = RHSExp;
3342 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003343 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003344 BaseExpr = LHSExp;
3345 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003346 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003347 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003348 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003349 BaseExpr = RHSExp;
3350 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003351 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003352 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003353 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003354 BaseExpr = LHSExp;
3355 IndexExpr = RHSExp;
3356 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003357 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003358 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003359 // Handle the uncommon case of "123[Ptr]".
3360 BaseExpr = RHSExp;
3361 IndexExpr = LHSExp;
3362 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003363 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003364 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003365 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003366 VK = LHSExp->getValueKind();
3367 if (VK != VK_RValue)
3368 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003369
Chris Lattner36d572b2007-07-16 00:14:47 +00003370 // FIXME: need to deal with const...
3371 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003372 } else if (LHSTy->isArrayType()) {
3373 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003374 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003375 // wasn't promoted because of the C90 rule that doesn't
3376 // allow promoting non-lvalue arrays. Warn, then
3377 // force the promotion here.
3378 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3379 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003380 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3381 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003382 LHSTy = LHSExp->getType();
3383
3384 BaseExpr = LHSExp;
3385 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003386 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003387 } else if (RHSTy->isArrayType()) {
3388 // Same as previous, except for 123[f().a] case
3389 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3390 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003391 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3392 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003393 RHSTy = RHSExp->getType();
3394
3395 BaseExpr = RHSExp;
3396 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003397 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003398 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003399 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3400 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003401 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003402 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003403 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003404 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3405 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003406
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003407 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003408 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3409 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003410 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3411
Douglas Gregorac1fb652009-03-24 19:52:54 +00003412 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003413 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3414 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003415 // incomplete types are not object types.
3416 if (ResultType->isFunctionType()) {
3417 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3418 << ResultType << BaseExpr->getSourceRange();
3419 return ExprError();
3420 }
Mike Stump11289f42009-09-09 15:08:12 +00003421
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003422 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3423 // GNU extension: subscripting on pointer to void
3424 Diag(LLoc, diag::ext_gnu_void_ptr)
3425 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003426
3427 // C forbids expressions of unqualified void type from being l-values.
3428 // See IsCForbiddenLValueType.
3429 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003430 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003431 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003432 PDiag(diag::err_subscript_incomplete_type)
3433 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003434 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003435
Chris Lattner62975a72009-04-24 00:30:45 +00003436 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003437 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003438 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3439 << ResultType << BaseExpr->getSourceRange();
3440 return ExprError();
3441 }
Mike Stump11289f42009-09-09 15:08:12 +00003442
John McCall4bc41ae2010-11-18 19:01:18 +00003443 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3444 !IsCForbiddenLValueType(Context, ResultType));
3445
Mike Stump4e1f26a2009-02-19 03:04:26 +00003446 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003447 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003448}
3449
John McCall4bc41ae2010-11-18 19:01:18 +00003450/// Check an ext-vector component access expression.
3451///
3452/// VK should be set in advance to the value kind of the base
3453/// expression.
3454static QualType
3455CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3456 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00003457 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00003458 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3459 // see FIXME there.
3460 //
3461 // FIXME: This logic can be greatly simplified by splitting it along
3462 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00003463 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00003464
Steve Narofff8fd09e2007-07-27 22:15:19 +00003465 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003466 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003467
Mike Stump4e1f26a2009-02-19 03:04:26 +00003468 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00003469 // special names that indicate a subset of exactly half the elements are
3470 // to be selected.
3471 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003472
Nate Begemanbb70bf62009-01-18 01:47:54 +00003473 // This flag determines whether or not CompName has an 's' char prefix,
3474 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00003475 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00003476
John McCall4bc41ae2010-11-18 19:01:18 +00003477 bool HasRepeated = false;
3478 bool HasIndex[16] = {};
3479
3480 int Idx;
3481
Nate Begemanf322eab2008-05-09 06:41:27 +00003482 // Check that we've found one of the special components, or that the component
3483 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003484 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00003485 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3486 HalvingSwizzle = true;
John McCall4bc41ae2010-11-18 19:01:18 +00003487 } else if (!HexSwizzle &&
3488 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3489 do {
3490 if (HasIndex[Idx]) HasRepeated = true;
3491 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003492 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003493 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3494 } else {
3495 if (HexSwizzle) compStr++;
3496 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3497 if (HasIndex[Idx]) HasRepeated = true;
3498 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003499 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003500 }
Chris Lattner7e152db2007-08-02 22:33:49 +00003501 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00003502
Mike Stump4e1f26a2009-02-19 03:04:26 +00003503 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00003504 // We didn't get to the end of the string. This means the component names
3505 // didn't come from the same set *or* we encountered an illegal name.
John McCall4bc41ae2010-11-18 19:01:18 +00003506 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramere8394df2010-08-11 14:47:12 +00003507 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00003508 return QualType();
3509 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003510
Nate Begemanbb70bf62009-01-18 01:47:54 +00003511 // Ensure no component accessor exceeds the width of the vector type it
3512 // operates on.
3513 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003514 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003515
3516 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00003517 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00003518
3519 while (*compStr) {
3520 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall4bc41ae2010-11-18 19:01:18 +00003521 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begemanbb70bf62009-01-18 01:47:54 +00003522 << baseType << SourceRange(CompLoc);
3523 return QualType();
3524 }
3525 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00003526 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003527
Steve Narofff8fd09e2007-07-27 22:15:19 +00003528 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003529 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00003530 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00003531 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00003532 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00003533 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00003534 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003535 if (HexSwizzle)
3536 CompSize--;
3537
Steve Narofff8fd09e2007-07-27 22:15:19 +00003538 if (CompSize == 1)
3539 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003540
John McCall4bc41ae2010-11-18 19:01:18 +00003541 if (HasRepeated) VK = VK_RValue;
3542
3543 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003544 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00003545 // diagostics look bad. We want extended vector types to appear built-in.
John McCall4bc41ae2010-11-18 19:01:18 +00003546 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3547 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3548 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00003549 }
3550 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00003551}
3552
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003553static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00003554 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003555 const Selector &Sel,
3556 ASTContext &Context) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003557 if (Member)
3558 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3559 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003560 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003561 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00003562
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003563 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3564 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003565 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3566 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003567 return D;
3568 }
3569 return 0;
3570}
3571
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003572static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3573 IdentifierInfo *Member,
3574 const Selector &Sel,
3575 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003576 // Check protocols on qualified interfaces.
3577 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00003578 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003579 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003580 if (Member)
3581 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3582 GDecl = PD;
3583 break;
3584 }
3585 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003586 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003587 GDecl = OMD;
3588 break;
3589 }
3590 }
3591 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00003592 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003593 E = QIdTy->qual_end(); I != E; ++I) {
3594 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003595 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3596 Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003597 if (GDecl)
3598 return GDecl;
3599 }
3600 }
3601 return GDecl;
3602}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00003603
John McCalldadc5752010-08-24 06:29:42 +00003604ExprResult
John McCallb268a282010-08-23 23:25:46 +00003605Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCall2d74de92009-12-01 22:10:20 +00003606 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003607 const CXXScopeSpec &SS,
3608 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003609 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003610 const TemplateArgumentListInfo *TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00003611 // Even in dependent contexts, try to diagnose base expressions with
3612 // obviously wrong types, e.g.:
3613 //
3614 // T* t;
3615 // t.f;
3616 //
3617 // In Obj-C++, however, the above expression is valid, since it could be
3618 // accessing the 'f' property if T is an Obj-C interface. The extra check
3619 // allows this, while still reporting an error if T is a struct pointer.
3620 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00003621 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00003622 if (PT && (!getLangOptions().ObjC1 ||
3623 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00003624 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003625 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00003626 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00003627 return ExprError();
3628 }
3629 }
3630
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003631 assert(BaseType->isDependentType() ||
3632 NameInfo.getName().isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00003633 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00003634
3635 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3636 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00003637 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003638 IsArrow, OpLoc,
Douglas Gregore16af532011-02-28 18:50:33 +00003639 SS.getWithLocInContext(Context),
John McCall10eae182009-11-30 22:42:35 +00003640 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003641 NameInfo, TemplateArgs));
John McCall10eae182009-11-30 22:42:35 +00003642}
3643
3644/// We know that the given qualified member reference points only to
3645/// declarations which do not belong to the static type of the base
3646/// expression. Diagnose the problem.
3647static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3648 Expr *BaseExpr,
3649 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003650 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00003651 NamedDecl *rep,
3652 const DeclarationNameInfo &nameInfo) {
John McCallcd4b4772009-12-02 03:53:29 +00003653 // If this is an implicit member access, use a different set of
3654 // diagnostics.
3655 if (!BaseExpr)
John McCallf3a88602011-02-03 08:15:49 +00003656 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall10eae182009-11-30 22:42:35 +00003657
John McCallf3a88602011-02-03 08:15:49 +00003658 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3659 << SS.getRange() << rep << BaseType;
John McCall10eae182009-11-30 22:42:35 +00003660}
3661
3662// Check whether the declarations we found through a nested-name
3663// specifier in a member expression are actually members of the base
3664// type. The restriction here is:
3665//
3666// C++ [expr.ref]p2:
3667// ... In these cases, the id-expression shall name a
3668// member of the class or of one of its base classes.
3669//
3670// So it's perfectly legitimate for the nested-name specifier to name
3671// an unrelated class, and for us to find an overload set including
3672// decls from classes which are not superclasses, as long as the decl
3673// we actually pick through overload resolution is from a superclass.
3674bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3675 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003676 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003677 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00003678 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3679 if (!BaseRT) {
3680 // We can't check this yet because the base type is still
3681 // dependent.
3682 assert(BaseType->isDependentType());
3683 return false;
3684 }
3685 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00003686
3687 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00003688 // If this is an implicit member reference and we find a
3689 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00003690 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00003691 return false;
John McCall10eae182009-11-30 22:42:35 +00003692
John McCall2d74de92009-12-01 22:10:20 +00003693 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman75300492010-07-27 20:51:02 +00003694 DeclContext *DC = (*I)->getDeclContext();
3695 while (DC->isTransparentContext())
3696 DC = DC->getParent();
John McCall2d74de92009-12-01 22:10:20 +00003697
Douglas Gregora9c3e822010-07-28 22:27:52 +00003698 if (!DC->isRecord())
3699 continue;
3700
John McCall2d74de92009-12-01 22:10:20 +00003701 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman75300492010-07-27 20:51:02 +00003702 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCall2d74de92009-12-01 22:10:20 +00003703
3704 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3705 return false;
3706 }
3707
John McCallf3a88602011-02-03 08:15:49 +00003708 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3709 R.getRepresentativeDecl(),
3710 R.getLookupNameInfo());
John McCall2d74de92009-12-01 22:10:20 +00003711 return true;
3712}
3713
3714static bool
3715LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3716 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00003717 SourceLocation OpLoc, CXXScopeSpec &SS,
3718 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00003719 RecordDecl *RDecl = RTy->getDecl();
3720 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00003721 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00003722 << BaseRange))
3723 return true;
3724
John McCalle9cccd82010-06-16 08:42:20 +00003725 if (HasTemplateArgs) {
3726 // LookupTemplateName doesn't expect these both to exist simultaneously.
3727 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3728
3729 bool MOUS;
3730 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3731 return false;
3732 }
3733
John McCall2d74de92009-12-01 22:10:20 +00003734 DeclContext *DC = RDecl;
3735 if (SS.isSet()) {
3736 // If the member name was a qualified-id, look into the
3737 // nested-name-specifier.
3738 DC = SemaRef.computeDeclContext(SS, false);
3739
John McCall0b66eb32010-05-01 00:40:08 +00003740 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00003741 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3742 << SS.getRange() << DC;
3743 return true;
3744 }
3745
John McCall2d74de92009-12-01 22:10:20 +00003746 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003747
John McCall2d74de92009-12-01 22:10:20 +00003748 if (!isa<TypeDecl>(DC)) {
3749 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3750 << DC << SS.getRange();
3751 return true;
John McCall10eae182009-11-30 22:42:35 +00003752 }
3753 }
3754
John McCall2d74de92009-12-01 22:10:20 +00003755 // The record definition is complete, now look up the member.
3756 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00003757
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003758 if (!R.empty())
3759 return false;
3760
3761 // We didn't find anything with the given name, so try to correct
3762 // for typos.
3763 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00003764 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003765 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003766 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3767 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3768 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003769 << FixItHint::CreateReplacement(R.getNameLoc(),
3770 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003771 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3772 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3773 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003774 return false;
3775 } else {
3776 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003777 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003778 }
3779
John McCall10eae182009-11-30 22:42:35 +00003780 return false;
3781}
3782
John McCalldadc5752010-08-24 06:29:42 +00003783ExprResult
John McCallb268a282010-08-23 23:25:46 +00003784Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00003785 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003786 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003787 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003788 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003789 const TemplateArgumentListInfo *TemplateArgs) {
John McCallcd4b4772009-12-02 03:53:29 +00003790 if (BaseType->isDependentType() ||
3791 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallb268a282010-08-23 23:25:46 +00003792 return ActOnDependentMemberExpr(Base, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003793 IsArrow, OpLoc,
3794 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003795 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003796
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003797 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00003798
John McCall2d74de92009-12-01 22:10:20 +00003799 // Implicit member accesses.
3800 if (!Base) {
3801 QualType RecordTy = BaseType;
3802 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3803 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3804 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00003805 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00003806 return ExprError();
3807
3808 // Explicit member accesses.
3809 } else {
John Wiegley01296292011-04-08 18:41:53 +00003810 ExprResult BaseResult = Owned(Base);
John McCalldadc5752010-08-24 06:29:42 +00003811 ExprResult Result =
John Wiegley01296292011-04-08 18:41:53 +00003812 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCall48871652010-08-21 09:40:31 +00003813 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00003814
John Wiegley01296292011-04-08 18:41:53 +00003815 if (BaseResult.isInvalid())
3816 return ExprError();
3817 Base = BaseResult.take();
3818
John McCall2d74de92009-12-01 22:10:20 +00003819 if (Result.isInvalid()) {
3820 Owned(Base);
3821 return ExprError();
3822 }
3823
3824 if (Result.get())
3825 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00003826
3827 // LookupMemberExpr can modify Base, and thus change BaseType
3828 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00003829 }
3830
John McCallb268a282010-08-23 23:25:46 +00003831 return BuildMemberReferenceExpr(Base, BaseType,
John McCall38836f02010-01-15 08:34:02 +00003832 OpLoc, IsArrow, SS, FirstQualifierInScope,
3833 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003834}
3835
John McCalldadc5752010-08-24 06:29:42 +00003836ExprResult
John McCallb268a282010-08-23 23:25:46 +00003837Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCall2d74de92009-12-01 22:10:20 +00003838 SourceLocation OpLoc, bool IsArrow,
3839 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00003840 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00003841 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00003842 const TemplateArgumentListInfo *TemplateArgs,
3843 bool SuppressQualifierCheck) {
John McCall2d74de92009-12-01 22:10:20 +00003844 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00003845 if (IsArrow) {
3846 assert(BaseType->isPointerType());
3847 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3848 }
John McCalla8ae2222010-04-06 21:38:20 +00003849 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00003850
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003851 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3852 DeclarationName MemberName = MemberNameInfo.getName();
3853 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall10eae182009-11-30 22:42:35 +00003854
3855 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00003856 return ExprError();
3857
John McCall10eae182009-11-30 22:42:35 +00003858 if (R.empty()) {
3859 // Rederive where we looked up.
3860 DeclContext *DC = (SS.isSet()
3861 ? computeDeclContext(SS, false)
3862 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00003863
John McCall10eae182009-11-30 22:42:35 +00003864 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00003865 << MemberName << DC
3866 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00003867 return ExprError();
3868 }
3869
John McCall38836f02010-01-15 08:34:02 +00003870 // Diagnose lookups that find only declarations from a non-base
3871 // type. This is possible for either qualified lookups (which may
3872 // have been qualified with an unrelated type) or implicit member
3873 // expressions (which were found with unqualified lookup and thus
3874 // may have come from an enclosing scope). Note that it's okay for
3875 // lookup to find declarations from a non-base type as long as those
3876 // aren't the ones picked by overload resolution.
3877 if ((SS.isSet() || !BaseExpr ||
3878 (isa<CXXThisExpr>(BaseExpr) &&
3879 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00003880 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00003881 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00003882 return ExprError();
3883
3884 // Construct an unresolved result if we in fact got an unresolved
3885 // result.
3886 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall58cc69d2010-01-27 01:50:18 +00003887 // Suppress any lookup-related diagnostics; we'll do these when we
3888 // pick a member.
3889 R.suppressDiagnostics();
3890
John McCall10eae182009-11-30 22:42:35 +00003891 UnresolvedMemberExpr *MemExpr
Douglas Gregora6e053e2010-12-15 01:34:56 +00003892 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00003893 BaseExpr, BaseExprType,
3894 IsArrow, OpLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00003895 SS.getWithLocInContext(Context),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003896 MemberNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00003897 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00003898
3899 return Owned(MemExpr);
3900 }
3901
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003902 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00003903 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00003904 NamedDecl *MemberDecl = R.getFoundDecl();
3905
3906 // FIXME: diagnose the presence of template arguments now.
3907
3908 // If the decl being referenced had an error, return an error for this
3909 // sub-expr without emitting another error, in order to avoid cascading
3910 // error cases.
3911 if (MemberDecl->isInvalidDecl())
3912 return ExprError();
3913
John McCall2d74de92009-12-01 22:10:20 +00003914 // Handle the implicit-member-access case.
3915 if (!BaseExpr) {
3916 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00003917 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003918 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCall2d74de92009-12-01 22:10:20 +00003919
Douglas Gregorb15af892010-01-07 23:12:05 +00003920 SourceLocation Loc = R.getNameLoc();
3921 if (SS.getRange().isValid())
3922 Loc = SS.getRange().getBegin();
3923 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003924 }
3925
John McCall10eae182009-11-30 22:42:35 +00003926 bool ShouldCheckUse = true;
3927 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3928 // Don't diagnose the use of a virtual member function unless it's
3929 // explicitly qualified.
3930 if (MD->isVirtual() && !SS.isSet())
3931 ShouldCheckUse = false;
3932 }
3933
3934 // Check the use of this member.
3935 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3936 Owned(BaseExpr);
3937 return ExprError();
3938 }
3939
John McCall34376a62010-12-04 03:47:34 +00003940 // Perform a property load on the base regardless of whether we
3941 // actually need it for the declaration.
John Wiegley01296292011-04-08 18:41:53 +00003942 if (BaseExpr->getObjectKind() == OK_ObjCProperty) {
3943 ExprResult Result = ConvertPropertyForRValue(BaseExpr);
3944 if (Result.isInvalid())
3945 return ExprError();
3946 BaseExpr = Result.take();
3947 }
John McCall34376a62010-12-04 03:47:34 +00003948
John McCallfeb624a2010-11-23 20:48:44 +00003949 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3950 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3951 SS, FD, FoundDecl, MemberNameInfo);
John McCall10eae182009-11-30 22:42:35 +00003952
Francois Pichet783dd6e2010-11-21 06:08:52 +00003953 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3954 // We may have found a field within an anonymous union or struct
3955 // (C++ [class.union]).
John McCallf3a88602011-02-03 08:15:49 +00003956 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCall34376a62010-12-04 03:47:34 +00003957 BaseExpr, OpLoc);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003958
John McCall10eae182009-11-30 22:42:35 +00003959 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3960 MarkDeclarationReferenced(MemberLoc, Var);
3961 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003962 Var, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003963 Var->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00003964 VK_LValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003965 }
3966
John McCall7decc9e2010-11-18 06:31:45 +00003967 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall0009fcc2011-04-26 20:42:42 +00003968 ExprValueKind valueKind;
3969 QualType type;
3970 if (MemberFn->isInstance()) {
3971 valueKind = VK_RValue;
3972 type = Context.BoundMemberTy;
3973 } else {
3974 valueKind = VK_LValue;
3975 type = MemberFn->getType();
3976 }
3977
John McCall10eae182009-11-30 22:42:35 +00003978 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3979 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003980 MemberFn, FoundDecl, MemberNameInfo,
John McCall0009fcc2011-04-26 20:42:42 +00003981 type, valueKind, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003982 }
John McCall7decc9e2010-11-18 06:31:45 +00003983 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall10eae182009-11-30 22:42:35 +00003984
3985 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3986 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3987 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003988 Enum, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00003989 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00003990 }
3991
3992 Owned(BaseExpr);
3993
Douglas Gregor861eb802010-04-25 20:55:08 +00003994 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00003995 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003996 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregor861eb802010-04-25 20:55:08 +00003997 << MemberName << BaseType << int(IsArrow);
3998 else
3999 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
4000 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00004001
Douglas Gregor861eb802010-04-25 20:55:08 +00004002 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
4003 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00004004 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00004005 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00004006}
4007
John McCall68fc88ec2010-12-15 16:46:44 +00004008/// Given that normal member access failed on the given expression,
4009/// and given that the expression's type involves builtin-id or
4010/// builtin-Class, decide whether substituting in the redefinition
4011/// types would be profitable. The redefinition type is whatever
4012/// this translation unit tried to typedef to id/Class; we store
4013/// it to the side and then re-use it in places like this.
John Wiegley01296292011-04-08 18:41:53 +00004014static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
John McCall68fc88ec2010-12-15 16:46:44 +00004015 const ObjCObjectPointerType *opty
John Wiegley01296292011-04-08 18:41:53 +00004016 = base.get()->getType()->getAs<ObjCObjectPointerType>();
John McCall68fc88ec2010-12-15 16:46:44 +00004017 if (!opty) return false;
4018
4019 const ObjCObjectType *ty = opty->getObjectType();
4020
4021 QualType redef;
4022 if (ty->isObjCId()) {
4023 redef = S.Context.ObjCIdRedefinitionType;
4024 } else if (ty->isObjCClass()) {
4025 redef = S.Context.ObjCClassRedefinitionType;
4026 } else {
4027 return false;
4028 }
4029
4030 // Do the substitution as long as the redefinition type isn't just a
4031 // possibly-qualified pointer to builtin-id or builtin-Class again.
4032 opty = redef->getAs<ObjCObjectPointerType>();
4033 if (opty && !opty->getObjectType()->getInterface() != 0)
4034 return false;
4035
John Wiegley01296292011-04-08 18:41:53 +00004036 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
John McCall68fc88ec2010-12-15 16:46:44 +00004037 return true;
4038}
4039
John McCall10eae182009-11-30 22:42:35 +00004040/// Look up the given member of the given non-type-dependent
4041/// expression. This can return in one of two ways:
4042/// * If it returns a sentinel null-but-valid result, the caller will
4043/// assume that lookup was performed and the results written into
4044/// the provided structure. It will take over from there.
4045/// * Otherwise, the returned expression will be produced in place of
4046/// an ordinary member expression.
4047///
4048/// The ObjCImpDecl bit is a gross hack that will need to be properly
4049/// fixed for ObjC++.
John McCalldadc5752010-08-24 06:29:42 +00004050ExprResult
John Wiegley01296292011-04-08 18:41:53 +00004051Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00004052 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004053 CXXScopeSpec &SS,
John McCall48871652010-08-21 09:40:31 +00004054 Decl *ObjCImpDecl, bool HasTemplateArgs) {
John Wiegley01296292011-04-08 18:41:53 +00004055 assert(BaseExpr.get() && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00004056
Steve Naroffeaaae462007-12-16 21:42:28 +00004057 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00004058 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004059
John Wiegley01296292011-04-08 18:41:53 +00004060 if (IsArrow) {
4061 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4062 if (BaseExpr.isInvalid())
4063 return ExprError();
4064 }
4065
4066 QualType BaseType = BaseExpr.get()->getType();
John McCall10eae182009-11-30 22:42:35 +00004067 assert(!BaseType->isDependentType());
4068
4069 DeclarationName MemberName = R.getLookupName();
4070 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00004071
John McCall68fc88ec2010-12-15 16:46:44 +00004072 // For later type-checking purposes, turn arrow accesses into dot
4073 // accesses. The only access type we support that doesn't follow
4074 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
4075 // and those never use arrows, so this is unaffected.
4076 if (IsArrow) {
4077 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4078 BaseType = Ptr->getPointeeType();
4079 else if (const ObjCObjectPointerType *Ptr
4080 = BaseType->getAs<ObjCObjectPointerType>())
4081 BaseType = Ptr->getPointeeType();
4082 else if (BaseType->isRecordType()) {
4083 // Recover from arrow accesses to records, e.g.:
4084 // struct MyRecord foo;
4085 // foo->bar
4086 // This is actually well-formed in C++ if MyRecord has an
4087 // overloaded operator->, but that should have been dealt with
4088 // by now.
4089 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley01296292011-04-08 18:41:53 +00004090 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
John McCall68fc88ec2010-12-15 16:46:44 +00004091 << FixItHint::CreateReplacement(OpLoc, ".");
4092 IsArrow = false;
John McCall0009fcc2011-04-26 20:42:42 +00004093 } else if (BaseType == Context.BoundMemberTy) {
4094 goto fail;
John McCall68fc88ec2010-12-15 16:46:44 +00004095 } else {
4096 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
John Wiegley01296292011-04-08 18:41:53 +00004097 << BaseType << BaseExpr.get()->getSourceRange();
John McCall68fc88ec2010-12-15 16:46:44 +00004098 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00004099 }
4100 }
4101
John McCall68fc88ec2010-12-15 16:46:44 +00004102 // Handle field access to simple records.
4103 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John Wiegley01296292011-04-08 18:41:53 +00004104 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
John McCall68fc88ec2010-12-15 16:46:44 +00004105 RTy, OpLoc, SS, HasTemplateArgs))
4106 return ExprError();
4107
4108 // Returning valid-but-null is how we indicate to the caller that
4109 // the lookup result was filled in.
4110 return Owned((Expr*) 0);
David Chisnall9f57c292009-08-17 16:35:33 +00004111 }
John McCall10eae182009-11-30 22:42:35 +00004112
John McCall68fc88ec2010-12-15 16:46:44 +00004113 // Handle ivar access to Objective-C objects.
4114 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004115 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall68fc88ec2010-12-15 16:46:44 +00004116
4117 // There are three cases for the base type:
4118 // - builtin id (qualified or unqualified)
4119 // - builtin Class (qualified or unqualified)
4120 // - an interface
4121 ObjCInterfaceDecl *IDecl = OTy->getInterface();
4122 if (!IDecl) {
4123 // There's an implicit 'isa' ivar on all objects.
4124 // But we only actually find it this way on objects of type 'id',
4125 // apparently.
4126 if (OTy->isObjCId() && Member->isStr("isa"))
John Wiegley01296292011-04-08 18:41:53 +00004127 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
John McCall68fc88ec2010-12-15 16:46:44 +00004128 Context.getObjCClassType()));
4129
4130 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4131 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4132 ObjCImpDecl, HasTemplateArgs);
4133 goto fail;
4134 }
4135
4136 ObjCInterfaceDecl *ClassDeclared;
4137 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
4138
4139 if (!IV) {
4140 // Attempt to correct for typos in ivar names.
4141 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
4142 LookupMemberName);
4143 if (CorrectTypo(Res, 0, 0, IDecl, false,
4144 IsArrow ? CTC_ObjCIvarLookup
4145 : CTC_ObjCPropertyLookup) &&
4146 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
4147 Diag(R.getNameLoc(),
4148 diag::err_typecheck_member_reference_ivar_suggest)
4149 << IDecl->getDeclName() << MemberName << IV->getDeclName()
4150 << FixItHint::CreateReplacement(R.getNameLoc(),
4151 IV->getNameAsString());
4152 Diag(IV->getLocation(), diag::note_previous_decl)
4153 << IV->getDeclName();
4154 } else {
4155 Res.clear();
4156 Res.setLookupName(Member);
4157
4158 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
4159 << IDecl->getDeclName() << MemberName
John Wiegley01296292011-04-08 18:41:53 +00004160 << BaseExpr.get()->getSourceRange();
John McCall68fc88ec2010-12-15 16:46:44 +00004161 return ExprError();
4162 }
4163 }
4164
4165 // If the decl being referenced had an error, return an error for this
4166 // sub-expr without emitting another error, in order to avoid cascading
4167 // error cases.
4168 if (IV->isInvalidDecl())
4169 return ExprError();
4170
4171 // Check whether we can reference this field.
4172 if (DiagnoseUseOfDecl(IV, MemberLoc))
4173 return ExprError();
4174 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
4175 IV->getAccessControl() != ObjCIvarDecl::Package) {
4176 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
4177 if (ObjCMethodDecl *MD = getCurMethodDecl())
4178 ClassOfMethodDecl = MD->getClassInterface();
4179 else if (ObjCImpDecl && getCurFunctionDecl()) {
4180 // Case of a c-function declared inside an objc implementation.
4181 // FIXME: For a c-style function nested inside an objc implementation
4182 // class, there is no implementation context available, so we pass
4183 // down the context as argument to this routine. Ideally, this context
4184 // need be passed down in the AST node and somehow calculated from the
4185 // AST for a function decl.
4186 if (ObjCImplementationDecl *IMPD =
4187 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
4188 ClassOfMethodDecl = IMPD->getClassInterface();
4189 else if (ObjCCategoryImplDecl* CatImplClass =
4190 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
4191 ClassOfMethodDecl = CatImplClass->getClassInterface();
4192 }
4193
4194 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
4195 if (ClassDeclared != IDecl ||
4196 ClassOfMethodDecl != ClassDeclared)
4197 Diag(MemberLoc, diag::error_private_ivar_access)
4198 << IV->getDeclName();
4199 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
4200 // @protected
4201 Diag(MemberLoc, diag::error_protected_ivar_access)
4202 << IV->getDeclName();
4203 }
4204
4205 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
John Wiegley01296292011-04-08 18:41:53 +00004206 MemberLoc, BaseExpr.take(),
John McCall68fc88ec2010-12-15 16:46:44 +00004207 IsArrow));
4208 }
4209
4210 // Objective-C property access.
4211 const ObjCObjectPointerType *OPT;
4212 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
4213 // This actually uses the base as an r-value.
John Wiegley01296292011-04-08 18:41:53 +00004214 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4215 if (BaseExpr.isInvalid())
4216 return ExprError();
4217
4218 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
John McCall68fc88ec2010-12-15 16:46:44 +00004219
4220 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
4221
4222 const ObjCObjectType *OT = OPT->getObjectType();
4223
4224 // id, with and without qualifiers.
4225 if (OT->isObjCId()) {
4226 // Check protocols on qualified interfaces.
4227 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
4228 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
4229 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
4230 // Check the use of this declaration
4231 if (DiagnoseUseOfDecl(PD, MemberLoc))
4232 return ExprError();
4233
4234 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
4235 VK_LValue,
4236 OK_ObjCProperty,
4237 MemberLoc,
John Wiegley01296292011-04-08 18:41:53 +00004238 BaseExpr.take()));
John McCall68fc88ec2010-12-15 16:46:44 +00004239 }
4240
4241 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
4242 // Check the use of this method.
4243 if (DiagnoseUseOfDecl(OMD, MemberLoc))
4244 return ExprError();
4245 Selector SetterSel =
4246 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4247 PP.getSelectorTable(), Member);
4248 ObjCMethodDecl *SMD = 0;
4249 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
4250 SetterSel, Context))
4251 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
4252 QualType PType = OMD->getSendResultType();
4253
4254 ExprValueKind VK = VK_LValue;
4255 if (!getLangOptions().CPlusPlus &&
4256 IsCForbiddenLValueType(Context, PType))
4257 VK = VK_RValue;
4258 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4259
4260 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
4261 VK, OK,
John Wiegley01296292011-04-08 18:41:53 +00004262 MemberLoc, BaseExpr.take()));
John McCall68fc88ec2010-12-15 16:46:44 +00004263 }
4264 }
Fariborz Jahanianb03a4c22011-03-15 17:27:48 +00004265 // Use of id.member can only be for a property reference. Do not
4266 // use the 'id' redefinition in this case.
4267 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
John McCall68fc88ec2010-12-15 16:46:44 +00004268 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4269 ObjCImpDecl, HasTemplateArgs);
4270
4271 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
4272 << MemberName << BaseType);
4273 }
4274
4275 // 'Class', unqualified only.
4276 if (OT->isObjCClass()) {
4277 // Only works in a method declaration (??!).
4278 ObjCMethodDecl *MD = getCurMethodDecl();
4279 if (!MD) {
4280 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4281 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4282 ObjCImpDecl, HasTemplateArgs);
4283
4284 goto fail;
4285 }
4286
4287 // Also must look for a getter name which uses property syntax.
4288 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004289 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4290 ObjCMethodDecl *Getter;
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004291 if ((Getter = IFace->lookupClassMethod(Sel))) {
4292 // Check the use of this method.
4293 if (DiagnoseUseOfDecl(Getter, MemberLoc))
4294 return ExprError();
John McCall68fc88ec2010-12-15 16:46:44 +00004295 } else
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00004296 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004297 // If we found a getter then this may be a valid dot-reference, we
4298 // will look for the matching setter, in case it is needed.
4299 Selector SetterSel =
John McCall68fc88ec2010-12-15 16:46:44 +00004300 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4301 PP.getSelectorTable(), Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004302 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
4303 if (!Setter) {
4304 // If this reference is in an @implementation, also check for 'private'
4305 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00004306 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004307 }
4308 // Look through local category implementations associated with the class.
4309 if (!Setter)
4310 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004311
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004312 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
4313 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004314
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004315 if (Getter || Setter) {
4316 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004317
John McCall4bc41ae2010-11-18 19:01:18 +00004318 ExprValueKind VK = VK_LValue;
4319 if (Getter) {
Douglas Gregor603d81b2010-07-13 08:18:22 +00004320 PType = Getter->getSendResultType();
John McCall4bc41ae2010-11-18 19:01:18 +00004321 if (!getLangOptions().CPlusPlus &&
4322 IsCForbiddenLValueType(Context, PType))
4323 VK = VK_RValue;
4324 } else {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004325 // Get the expression type from Setter's incoming parameter.
4326 PType = (*(Setter->param_end() -1))->getType();
John McCall4bc41ae2010-11-18 19:01:18 +00004327 }
4328 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4329
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004330 // FIXME: we must check that the setter has property type.
John McCallb7bd14f2010-12-02 01:19:52 +00004331 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
4332 PType, VK, OK,
John Wiegley01296292011-04-08 18:41:53 +00004333 MemberLoc, BaseExpr.take()));
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004334 }
John McCall68fc88ec2010-12-15 16:46:44 +00004335
4336 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4337 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4338 ObjCImpDecl, HasTemplateArgs);
4339
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004340 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall68fc88ec2010-12-15 16:46:44 +00004341 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004342 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004343
John McCall68fc88ec2010-12-15 16:46:44 +00004344 // Normal property access.
John Wiegley01296292011-04-08 18:41:53 +00004345 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), MemberName, MemberLoc,
John McCall68fc88ec2010-12-15 16:46:44 +00004346 SourceLocation(), QualType(), false);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004347 }
Alexis Huntc46382e2010-04-28 23:02:27 +00004348
Chris Lattnerb63a7452008-07-21 04:28:12 +00004349 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00004350 if (BaseType->isExtVectorType()) {
John McCall15317a22010-12-15 04:42:30 +00004351 // FIXME: this expr should store IsArrow.
Anders Carlssonf571c112009-08-26 18:25:21 +00004352 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John Wiegley01296292011-04-08 18:41:53 +00004353 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
John McCall4bc41ae2010-11-18 19:01:18 +00004354 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
4355 Member, MemberLoc);
Chris Lattnerb63a7452008-07-21 04:28:12 +00004356 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004357 return ExprError();
John McCall4bc41ae2010-11-18 19:01:18 +00004358
John Wiegley01296292011-04-08 18:41:53 +00004359 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
John McCall4bc41ae2010-11-18 19:01:18 +00004360 *Member, MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00004361 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004362
John McCall68fc88ec2010-12-15 16:46:44 +00004363 // Adjust builtin-sel to the appropriate redefinition type if that's
4364 // not just a pointer to builtin-sel again.
4365 if (IsArrow &&
4366 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
4367 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
John Wiegley01296292011-04-08 18:41:53 +00004368 BaseExpr = ImpCastExprToType(BaseExpr.take(), Context.ObjCSelRedefinitionType,
4369 CK_BitCast);
John McCall68fc88ec2010-12-15 16:46:44 +00004370 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4371 ObjCImpDecl, HasTemplateArgs);
4372 }
4373
4374 // Failure cases.
4375 fail:
4376
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004377 // Recover from dot accesses to pointers, e.g.:
4378 // type *foo;
4379 // foo.bar
4380 // This is actually well-formed in two cases:
4381 // - 'type' is an Objective C type
4382 // - 'bar' is a pseudo-destructor name which happens to refer to
4383 // the appropriate pointer type
John McCall68fc88ec2010-12-15 16:46:44 +00004384 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004385 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
4386 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
John McCall68fc88ec2010-12-15 16:46:44 +00004387 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley01296292011-04-08 18:41:53 +00004388 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004389 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall68fc88ec2010-12-15 16:46:44 +00004390
4391 // Recurse as an -> access.
4392 IsArrow = true;
4393 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4394 ObjCImpDecl, HasTemplateArgs);
4395 }
John McCall68fc88ec2010-12-15 16:46:44 +00004396 }
4397
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004398 // If the user is trying to apply -> or . to a function name, it's probably
4399 // because they forgot parentheses to call that function.
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00004400 QualType ZeroArgCallTy;
4401 UnresolvedSet<4> Overloads;
4402 if (isExprCallable(*BaseExpr.get(), ZeroArgCallTy, Overloads)) {
4403 if (ZeroArgCallTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +00004404 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00004405 << (Overloads.size() > 1) << 0 << BaseExpr.get()->getSourceRange();
4406 UnresolvedSet<2> PlausibleOverloads;
4407 for (OverloadExpr::decls_iterator It = Overloads.begin(),
4408 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
4409 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
4410 QualType OverloadResultTy = OverloadDecl->getResultType();
4411 if ((!IsArrow && OverloadResultTy->isRecordType()) ||
4412 (IsArrow && OverloadResultTy->isPointerType() &&
4413 OverloadResultTy->getPointeeType()->isRecordType()))
4414 PlausibleOverloads.addDecl(It.getDecl());
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004415 }
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00004416 NoteOverloads(PlausibleOverloads, BaseExpr.get()->getExprLoc());
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004417 return ExprError();
4418 }
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00004419 if ((!IsArrow && ZeroArgCallTy->isRecordType()) ||
4420 (IsArrow && ZeroArgCallTy->isPointerType() &&
4421 ZeroArgCallTy->getPointeeType()->isRecordType())) {
4422 // At this point, we know BaseExpr looks like it's potentially callable
4423 // with 0 arguments, and that it returns something of a reasonable type,
4424 // so we can emit a fixit and carry on pretending that BaseExpr was
4425 // actually a CallExpr.
4426 SourceLocation ParenInsertionLoc =
4427 PP.getLocForEndOfToken(BaseExpr.get()->getLocEnd());
4428 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
4429 << (Overloads.size() > 1) << 1 << BaseExpr.get()->getSourceRange()
4430 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4431 // FIXME: Try this before emitting the fixit, and suppress diagnostics
4432 // while doing so.
4433 ExprResult NewBase =
4434 ActOnCallExpr(0, BaseExpr.take(), ParenInsertionLoc,
4435 MultiExprArg(*this, 0, 0),
4436 ParenInsertionLoc.getFileLocWithOffset(1));
4437 if (NewBase.isInvalid())
4438 return ExprError();
4439 BaseExpr = NewBase;
4440 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
4441 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4442 ObjCImpDecl, HasTemplateArgs);
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004443 }
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004444 }
4445
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004446 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
John Wiegley01296292011-04-08 18:41:53 +00004447 << BaseType << BaseExpr.get()->getSourceRange();
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004448
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004449 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00004450}
4451
John McCall10eae182009-11-30 22:42:35 +00004452/// The main callback when the parser finds something like
4453/// expression . [nested-name-specifier] identifier
4454/// expression -> [nested-name-specifier] identifier
4455/// where 'identifier' encompasses a fairly broad spectrum of
4456/// possibilities, including destructor and operator references.
4457///
4458/// \param OpKind either tok::arrow or tok::period
4459/// \param HasTrailingLParen whether the next token is '(', which
4460/// is used to diagnose mis-uses of special members that can
4461/// only be called
4462/// \param ObjCImpDecl the current ObjC @implementation decl;
4463/// this is an ugly hack around the fact that ObjC @implementations
4464/// aren't properly put in the context chain
John McCalldadc5752010-08-24 06:29:42 +00004465ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall15317a22010-12-15 04:42:30 +00004466 SourceLocation OpLoc,
4467 tok::TokenKind OpKind,
4468 CXXScopeSpec &SS,
4469 UnqualifiedId &Id,
4470 Decl *ObjCImpDecl,
4471 bool HasTrailingLParen) {
John McCall10eae182009-11-30 22:42:35 +00004472 if (SS.isSet() && SS.isInvalid())
4473 return ExprError();
4474
Francois Pichet64225792011-01-18 05:04:39 +00004475 // Warn about the explicit constructor calls Microsoft extension.
4476 if (getLangOptions().Microsoft &&
4477 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4478 Diag(Id.getSourceRange().getBegin(),
4479 diag::ext_ms_explicit_constructor_call);
4480
John McCall10eae182009-11-30 22:42:35 +00004481 TemplateArgumentListInfo TemplateArgsBuffer;
4482
4483 // Decompose the name into its component parts.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004484 DeclarationNameInfo NameInfo;
John McCall10eae182009-11-30 22:42:35 +00004485 const TemplateArgumentListInfo *TemplateArgs;
4486 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004487 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004488
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004489 DeclarationName Name = NameInfo.getName();
John McCall10eae182009-11-30 22:42:35 +00004490 bool IsArrow = (OpKind == tok::arrow);
4491
4492 NamedDecl *FirstQualifierInScope
4493 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4494 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4495
4496 // This is a postfix expression, so get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004497 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00004498 if (Result.isInvalid()) return ExprError();
4499 Base = Result.take();
John McCall10eae182009-11-30 22:42:35 +00004500
Douglas Gregor41f90302010-04-12 20:54:26 +00004501 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4502 isDependentScopeSpecifier(SS)) {
John McCallb268a282010-08-23 23:25:46 +00004503 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00004504 IsArrow, OpLoc,
4505 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004506 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004507 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004508 LookupResult R(*this, NameInfo, LookupMemberName);
John Wiegley01296292011-04-08 18:41:53 +00004509 ExprResult BaseResult = Owned(Base);
4510 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCalle9cccd82010-06-16 08:42:20 +00004511 SS, ObjCImpDecl, TemplateArgs != 0);
John Wiegley01296292011-04-08 18:41:53 +00004512 if (BaseResult.isInvalid())
4513 return ExprError();
4514 Base = BaseResult.take();
Alexis Huntc46382e2010-04-28 23:02:27 +00004515
John McCalle9cccd82010-06-16 08:42:20 +00004516 if (Result.isInvalid()) {
4517 Owned(Base);
4518 return ExprError();
4519 }
John McCall10eae182009-11-30 22:42:35 +00004520
John McCalle9cccd82010-06-16 08:42:20 +00004521 if (Result.get()) {
4522 // The only way a reference to a destructor can be used is to
4523 // immediately call it, which falls into this case. If the
4524 // next token is not a '(', produce a diagnostic and build the
4525 // call now.
4526 if (!HasTrailingLParen &&
4527 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCallb268a282010-08-23 23:25:46 +00004528 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall10eae182009-11-30 22:42:35 +00004529
John McCalle9cccd82010-06-16 08:42:20 +00004530 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00004531 }
4532
John McCallb268a282010-08-23 23:25:46 +00004533 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00004534 OpLoc, IsArrow, SS, FirstQualifierInScope,
4535 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004536 }
4537
4538 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00004539}
4540
John McCalldadc5752010-08-24 06:29:42 +00004541ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00004542 FunctionDecl *FD,
4543 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00004544 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004545 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00004546 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00004547 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004548 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00004549 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004550 return ExprError();
4551 }
4552
4553 if (Param->hasUninstantiatedDefaultArg()) {
4554 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00004555
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004556 // Instantiate the expression.
4557 MultiLevelTemplateArgumentList ArgList
4558 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00004559
Nico Weber44887f62010-11-29 18:19:25 +00004560 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004561 = ArgList.getInnermost();
4562 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4563 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00004564
Nico Weber44887f62010-11-29 18:19:25 +00004565 ExprResult Result;
4566 {
4567 // C++ [dcl.fct.default]p5:
4568 // The names in the [default argument] expression are bound, and
4569 // the semantic constraints are checked, at the point where the
4570 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00004571 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00004572 Result = SubstExpr(UninstExpr, ArgList);
4573 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004574 if (Result.isInvalid())
4575 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004576
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004577 // Check the expression as an initializer for the parameter.
4578 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004579 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004580 InitializationKind Kind
4581 = InitializationKind::CreateCopy(Param->getLocation(),
4582 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4583 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00004584
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004585 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4586 Result = InitSeq.Perform(*this, Entity, Kind,
4587 MultiExprArg(*this, &ResultE, 1));
4588 if (Result.isInvalid())
4589 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004590
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004591 // Build the default argument expression.
4592 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4593 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00004594 }
4595
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004596 // If the default expression creates temporaries, we need to
4597 // push them to the current stack of expression temporaries so they'll
4598 // be properly destroyed.
4599 // FIXME: We should really be rebuilding the default argument with new
4600 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00004601 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4602 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4603 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4604 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4605 ExprTemporaries.push_back(Temporary);
4606 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004607
4608 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00004609 // Just mark all of the declarations in this potentially-evaluated expression
4610 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004611 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00004612 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00004613}
4614
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004615/// ConvertArgumentsForCall - Converts the arguments specified in
4616/// Args/NumArgs to the parameter types of the function FDecl with
4617/// function prototype Proto. Call is the call expression itself, and
4618/// Fn is the function expression. For a C++ member function, this
4619/// routine does not attempt to convert the object argument. Returns
4620/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004621bool
4622Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004623 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004624 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004625 Expr **Args, unsigned NumArgs,
4626 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00004627 // Bail out early if calling a builtin with custom typechecking.
4628 // We don't need to do this in the
4629 if (FDecl)
4630 if (unsigned ID = FDecl->getBuiltinID())
4631 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4632 return false;
4633
Mike Stump4e1f26a2009-02-19 03:04:26 +00004634 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004635 // assignment, to the types of the corresponding parameter, ...
4636 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00004637 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004638
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004639 // If too few arguments are available (and we don't have default
4640 // arguments for the remaining parameters), don't make the call.
4641 if (NumArgs < NumArgsInProto) {
4642 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4643 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004644 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00004645 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00004646 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004647 }
4648
4649 // If too many are passed and not variadic, error on the extras and drop
4650 // them.
4651 if (NumArgs > NumArgsInProto) {
4652 if (!Proto->isVariadic()) {
4653 Diag(Args[NumArgsInProto]->getLocStart(),
4654 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004655 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004656 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004657 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4658 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00004659
4660 // Emit the location of the prototype.
4661 if (FDecl && !FDecl->getBuiltinID())
4662 Diag(FDecl->getLocStart(),
4663 diag::note_typecheck_call_too_many_args)
4664 << FDecl;
4665
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004666 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00004667 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004668 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004669 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004670 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004671 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004672 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004673 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4674 if (Fn->getType()->isBlockPointerType())
4675 CallType = VariadicBlock; // Block
4676 else if (isa<MemberExpr>(Fn))
4677 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004678 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004679 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004680 if (Invalid)
4681 return true;
4682 unsigned TotalNumArgs = AllArgs.size();
4683 for (unsigned i = 0; i < TotalNumArgs; ++i)
4684 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004685
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004686 return false;
4687}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004688
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004689bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4690 FunctionDecl *FDecl,
4691 const FunctionProtoType *Proto,
4692 unsigned FirstProtoArg,
4693 Expr **Args, unsigned NumArgs,
4694 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004695 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004696 unsigned NumArgsInProto = Proto->getNumArgs();
4697 unsigned NumArgsToCheck = NumArgs;
4698 bool Invalid = false;
4699 if (NumArgs != NumArgsInProto)
4700 // Use default arguments for missing arguments
4701 NumArgsToCheck = NumArgsInProto;
4702 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004703 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004704 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004705 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004706
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004707 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004708 if (ArgIx < NumArgs) {
4709 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004710
Eli Friedman3164fb12009-03-22 22:00:50 +00004711 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4712 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00004713 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004714 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00004715 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004716
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004717 // Pass the argument
4718 ParmVarDecl *Param = 0;
4719 if (FDecl && i < FDecl->getNumParams())
4720 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00004721
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004722 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004723 Param? InitializedEntity::InitializeParameter(Context, Param)
4724 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCalldadc5752010-08-24 06:29:42 +00004725 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00004726 SourceLocation(),
4727 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004728 if (ArgE.isInvalid())
4729 return true;
4730
4731 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004732 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00004733 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004734
John McCalldadc5752010-08-24 06:29:42 +00004735 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004736 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004737 if (ArgExpr.isInvalid())
4738 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004739
Anders Carlsson355933d2009-08-25 03:49:14 +00004740 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004741 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004742 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004743 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004744
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004745 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004746 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00004747
4748 // Assume that extern "C" functions with variadic arguments that
4749 // return __unknown_anytype aren't *really* variadic.
4750 if (Proto->getResultType() == Context.UnknownAnyTy &&
4751 FDecl && FDecl->isExternC()) {
4752 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4753 ExprResult arg;
4754 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
4755 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
4756 else
4757 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4758 Invalid |= arg.isInvalid();
4759 AllArgs.push_back(arg.take());
4760 }
4761
4762 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4763 } else {
4764 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4765 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4766 Invalid |= Arg.isInvalid();
4767 AllArgs.push_back(Arg.take());
4768 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004769 }
4770 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004771 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004772}
4773
John McCall2979fe02011-04-12 00:42:48 +00004774/// Given a function expression of unknown-any type, try to rebuild it
4775/// to have a function type.
4776static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4777
Steve Naroff83895f72007-09-16 03:34:24 +00004778/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00004779/// This provides the location of the left/right parens and a list of comma
4780/// locations.
John McCalldadc5752010-08-24 06:29:42 +00004781ExprResult
John McCallb268a282010-08-23 23:25:46 +00004782Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004783 MultiExprArg args, SourceLocation RParenLoc,
4784 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004785 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00004786
4787 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004788 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00004789 if (Result.isInvalid()) return ExprError();
4790 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00004791
John McCallb268a282010-08-23 23:25:46 +00004792 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00004793
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004794 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004795 // If this is a pseudo-destructor expression, build the call immediately.
4796 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4797 if (NumArgs > 0) {
4798 // Pseudo-destructor calls should not have any arguments.
4799 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00004800 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00004801 SourceRange(Args[0]->getLocStart(),
4802 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00004803
Douglas Gregorad8a3362009-09-04 17:36:40 +00004804 NumArgs = 0;
4805 }
Mike Stump11289f42009-09-09 15:08:12 +00004806
Douglas Gregorad8a3362009-09-04 17:36:40 +00004807 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00004808 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004809 }
Mike Stump11289f42009-09-09 15:08:12 +00004810
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004811 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00004812 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00004813 // FIXME: Will need to cache the results of name lookup (including ADL) in
4814 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004815 bool Dependent = false;
4816 if (Fn->isTypeDependent())
4817 Dependent = true;
4818 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4819 Dependent = true;
4820
Peter Collingbourne41f85462011-02-09 21:07:24 +00004821 if (Dependent) {
4822 if (ExecConfig) {
4823 return Owned(new (Context) CUDAKernelCallExpr(
4824 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4825 Context.DependentTy, VK_RValue, RParenLoc));
4826 } else {
4827 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4828 Context.DependentTy, VK_RValue,
4829 RParenLoc));
4830 }
4831 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004832
4833 // Determine whether this is a call to an object (C++ [over.call.object]).
4834 if (Fn->getType()->isRecordType())
4835 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004836 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004837
John McCall2979fe02011-04-12 00:42:48 +00004838 if (Fn->getType() == Context.UnknownAnyTy) {
4839 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4840 if (result.isInvalid()) return ExprError();
4841 Fn = result.take();
4842 }
4843
John McCall0009fcc2011-04-26 20:42:42 +00004844 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00004845 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004846 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00004847 }
John McCall0009fcc2011-04-26 20:42:42 +00004848 }
John McCall10eae182009-11-30 22:42:35 +00004849
John McCall0009fcc2011-04-26 20:42:42 +00004850 // Check for overloaded calls. This can happen even in C due to extensions.
4851 if (Fn->getType() == Context.OverloadTy) {
4852 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4853
4854 // We aren't supposed to apply this logic if there's an '&' involved.
4855 if (!find.IsAddressOfOperand) {
4856 OverloadExpr *ovl = find.Expression;
4857 if (isa<UnresolvedLookupExpr>(ovl)) {
4858 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4859 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
4860 RParenLoc, ExecConfig);
4861 } else {
John McCall2d74de92009-12-01 22:10:20 +00004862 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004863 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00004864 }
4865 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004866 }
4867
Douglas Gregore254f902009-02-04 00:32:51 +00004868 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004869
Eli Friedmane14b1992009-12-26 03:35:45 +00004870 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00004871
John McCall57500772009-12-16 12:17:52 +00004872 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00004873 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4874 if (UnOp->getOpcode() == UO_AddrOf)
4875 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4876
John McCall57500772009-12-16 12:17:52 +00004877 if (isa<DeclRefExpr>(NakedFn))
4878 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00004879 else if (isa<MemberExpr>(NakedFn))
4880 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00004881
Peter Collingbourne41f85462011-02-09 21:07:24 +00004882 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4883 ExecConfig);
4884}
4885
4886ExprResult
4887Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4888 MultiExprArg execConfig, SourceLocation GGGLoc) {
4889 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4890 if (!ConfigDecl)
4891 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4892 << "cudaConfigureCall");
4893 QualType ConfigQTy = ConfigDecl->getType();
4894
4895 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4896 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4897
4898 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00004899}
4900
John McCall57500772009-12-16 12:17:52 +00004901/// BuildResolvedCallExpr - Build a call to a resolved expression,
4902/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00004903/// unary-convert to an expression of function-pointer or
4904/// block-pointer type.
4905///
4906/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00004907ExprResult
John McCall2d74de92009-12-01 22:10:20 +00004908Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4909 SourceLocation LParenLoc,
4910 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004911 SourceLocation RParenLoc,
4912 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00004913 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4914
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004915 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00004916 ExprResult Result = UsualUnaryConversions(Fn);
4917 if (Result.isInvalid())
4918 return ExprError();
4919 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00004920
Chris Lattner08464942007-12-28 05:29:59 +00004921 // Make the call expr early, before semantic checks. This guarantees cleanup
4922 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00004923 CallExpr *TheCall;
4924 if (Config) {
4925 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4926 cast<CallExpr>(Config),
4927 Args, NumArgs,
4928 Context.BoolTy,
4929 VK_RValue,
4930 RParenLoc);
4931 } else {
4932 TheCall = new (Context) CallExpr(Context, Fn,
4933 Args, NumArgs,
4934 Context.BoolTy,
4935 VK_RValue,
4936 RParenLoc);
4937 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004938
John McCallbebede42011-02-26 05:39:39 +00004939 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4940
4941 // Bail out early if calling a builtin with custom typechecking.
4942 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4943 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4944
John McCall31996342011-04-07 08:22:57 +00004945 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004946 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00004947 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004948 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4949 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00004950 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00004951 if (FuncT == 0)
4952 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4953 << Fn->getType() << Fn->getSourceRange());
4954 } else if (const BlockPointerType *BPT =
4955 Fn->getType()->getAs<BlockPointerType>()) {
4956 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4957 } else {
John McCall31996342011-04-07 08:22:57 +00004958 // Handle calls to expressions of unknown-any type.
4959 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00004960 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00004961 if (rewrite.isInvalid()) return ExprError();
4962 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00004963 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00004964 goto retry;
4965 }
4966
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004967 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4968 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00004969 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004970
Peter Collingbourne4b66c472011-02-23 01:53:29 +00004971 if (getLangOptions().CUDA) {
4972 if (Config) {
4973 // CUDA: Kernel calls must be to global functions
4974 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4975 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4976 << FDecl->getName() << Fn->getSourceRange());
4977
4978 // CUDA: Kernel function must have 'void' return type
4979 if (!FuncT->getResultType()->isVoidType())
4980 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4981 << Fn->getType() << Fn->getSourceRange());
4982 }
4983 }
4984
Eli Friedman3164fb12009-03-22 22:00:50 +00004985 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004986 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00004987 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004988 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00004989 return ExprError();
4990
Chris Lattner08464942007-12-28 05:29:59 +00004991 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00004992 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00004993 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004994
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004995 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00004996 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004997 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004998 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00004999 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005000 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005001
Douglas Gregord8e97de2009-04-02 15:37:10 +00005002 if (FDecl) {
5003 // Check if we have too few/too many template arguments, based
5004 // on our knowledge of the function definition.
5005 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00005006 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00005007 const FunctionProtoType *Proto
5008 = Def->getType()->getAs<FunctionProtoType>();
5009 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00005010 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5011 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00005012 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00005013
5014 // If the function we're calling isn't a function prototype, but we have
5015 // a function prototype from a prior declaratiom, use that prototype.
5016 if (!FDecl->hasPrototype())
5017 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00005018 }
5019
Steve Naroff0b661582007-08-28 23:30:39 +00005020 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00005021 for (unsigned i = 0; i != NumArgs; i++) {
5022 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00005023
5024 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00005025 InitializedEntity Entity
5026 = InitializedEntity::InitializeParameter(Context,
5027 Proto->getArgType(i));
5028 ExprResult ArgE = PerformCopyInitialization(Entity,
5029 SourceLocation(),
5030 Owned(Arg));
5031 if (ArgE.isInvalid())
5032 return true;
5033
5034 Arg = ArgE.takeAs<Expr>();
5035
5036 } else {
John Wiegley01296292011-04-08 18:41:53 +00005037 ExprResult ArgE = DefaultArgumentPromotion(Arg);
5038
5039 if (ArgE.isInvalid())
5040 return true;
5041
5042 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00005043 }
5044
Douglas Gregor83025412010-10-26 05:45:40 +00005045 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
5046 Arg->getType(),
5047 PDiag(diag::err_call_incomplete_argument)
5048 << Arg->getSourceRange()))
5049 return ExprError();
5050
Chris Lattner08464942007-12-28 05:29:59 +00005051 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00005052 }
Steve Naroffae4143e2007-04-26 20:39:23 +00005053 }
Chris Lattner08464942007-12-28 05:29:59 +00005054
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005055 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5056 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005057 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5058 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005059
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00005060 // Check for sentinels
5061 if (NDecl)
5062 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00005063
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005064 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005065 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00005066 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005067 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00005068
John McCallbebede42011-02-26 05:39:39 +00005069 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00005070 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005071 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00005072 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005073 return ExprError();
5074 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005075
John McCallb268a282010-08-23 23:25:46 +00005076 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00005077}
5078
John McCalldadc5752010-08-24 06:29:42 +00005079ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005080Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005081 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00005082 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00005083 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00005084 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00005085
5086 TypeSourceInfo *TInfo;
5087 QualType literalType = GetTypeFromParser(Ty, &TInfo);
5088 if (!TInfo)
5089 TInfo = Context.getTrivialTypeSourceInfo(literalType);
5090
John McCallb268a282010-08-23 23:25:46 +00005091 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00005092}
5093
John McCalldadc5752010-08-24 06:29:42 +00005094ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00005095Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00005096 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00005097 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00005098
Eli Friedman37a186d2008-05-20 05:22:08 +00005099 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00005100 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5101 PDiag(diag::err_illegal_decl_array_incomplete_type)
5102 << SourceRange(LParenLoc,
5103 literalExpr->getSourceRange().getEnd())))
5104 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00005105 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005106 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5107 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00005108 } else if (!literalType->isDependentType() &&
5109 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00005110 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00005111 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00005112 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005113 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00005114
Douglas Gregor85dabae2009-12-16 01:38:02 +00005115 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00005116 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005117 InitializationKind Kind
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005118 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor85dabae2009-12-16 01:38:02 +00005119 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00005120 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00005121 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00005122 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00005123 &literalType);
5124 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005125 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00005126 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00005127
Chris Lattner79413952008-12-04 23:50:19 +00005128 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00005129 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00005130 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005131 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00005132 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00005133
John McCall7decc9e2010-11-18 06:31:45 +00005134 // In C, compound literals are l-values for some reason.
5135 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
5136
John McCall5d7aa7f2010-01-19 22:33:45 +00005137 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCall7decc9e2010-11-18 06:31:45 +00005138 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00005139}
5140
John McCalldadc5752010-08-24 06:29:42 +00005141ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00005142Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00005143 SourceLocation RBraceLoc) {
5144 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00005145 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00005146
Steve Naroff30d242c2007-09-15 18:49:24 +00005147 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00005148 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005149
Ted Kremenekac034612010-04-13 23:39:13 +00005150 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
5151 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005152 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005153 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00005154}
5155
John McCalld7646252010-11-14 08:17:51 +00005156/// Prepares for a scalar cast, performing all the necessary stages
5157/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00005158static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00005159 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5160 // Also, callers should have filtered out the invalid cases with
5161 // pointers. Everything else should be possible.
5162
John Wiegley01296292011-04-08 18:41:53 +00005163 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00005164 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00005165 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00005166
John McCall8cb679e2010-11-15 09:13:47 +00005167 switch (SrcTy->getScalarTypeKind()) {
5168 case Type::STK_MemberPointer:
5169 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00005170
John McCall8cb679e2010-11-15 09:13:47 +00005171 case Type::STK_Pointer:
5172 switch (DestTy->getScalarTypeKind()) {
5173 case Type::STK_Pointer:
5174 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00005175 CK_AnyPointerToObjCPointerCast :
5176 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00005177 case Type::STK_Bool:
5178 return CK_PointerToBoolean;
5179 case Type::STK_Integral:
5180 return CK_PointerToIntegral;
5181 case Type::STK_Floating:
5182 case Type::STK_FloatingComplex:
5183 case Type::STK_IntegralComplex:
5184 case Type::STK_MemberPointer:
5185 llvm_unreachable("illegal cast from pointer");
5186 }
5187 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005188
John McCall8cb679e2010-11-15 09:13:47 +00005189 case Type::STK_Bool: // casting from bool is like casting from an integer
5190 case Type::STK_Integral:
5191 switch (DestTy->getScalarTypeKind()) {
5192 case Type::STK_Pointer:
John Wiegley01296292011-04-08 18:41:53 +00005193 if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00005194 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00005195 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005196 case Type::STK_Bool:
5197 return CK_IntegralToBoolean;
5198 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00005199 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00005200 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00005201 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00005202 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00005203 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5204 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00005205 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005206 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00005207 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5208 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00005209 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005210 case Type::STK_MemberPointer:
5211 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005212 }
5213 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005214
John McCall8cb679e2010-11-15 09:13:47 +00005215 case Type::STK_Floating:
5216 switch (DestTy->getScalarTypeKind()) {
5217 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00005218 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00005219 case Type::STK_Bool:
5220 return CK_FloatingToBoolean;
5221 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00005222 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00005223 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00005224 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5225 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00005226 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005227 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00005228 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5229 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00005230 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005231 case Type::STK_Pointer:
5232 llvm_unreachable("valid float->pointer cast?");
5233 case Type::STK_MemberPointer:
5234 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005235 }
5236 break;
5237
John McCall8cb679e2010-11-15 09:13:47 +00005238 case Type::STK_FloatingComplex:
5239 switch (DestTy->getScalarTypeKind()) {
5240 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005241 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00005242 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005243 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00005244 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00005245 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005246 if (S.Context.hasSameType(ET, DestTy))
5247 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00005248 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00005249 return CK_FloatingCast;
5250 }
John McCall8cb679e2010-11-15 09:13:47 +00005251 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005252 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005253 case Type::STK_Integral:
John Wiegley01296292011-04-08 18:41:53 +00005254 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5255 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00005256 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00005257 case Type::STK_Pointer:
5258 llvm_unreachable("valid complex float->pointer cast?");
5259 case Type::STK_MemberPointer:
5260 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005261 }
5262 break;
5263
John McCall8cb679e2010-11-15 09:13:47 +00005264 case Type::STK_IntegralComplex:
5265 switch (DestTy->getScalarTypeKind()) {
5266 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005267 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005268 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005269 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00005270 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00005271 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005272 if (S.Context.hasSameType(ET, DestTy))
5273 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00005274 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00005275 return CK_IntegralCast;
5276 }
John McCall8cb679e2010-11-15 09:13:47 +00005277 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005278 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005279 case Type::STK_Floating:
John Wiegley01296292011-04-08 18:41:53 +00005280 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5281 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00005282 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00005283 case Type::STK_Pointer:
5284 llvm_unreachable("valid complex int->pointer cast?");
5285 case Type::STK_MemberPointer:
5286 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005287 }
5288 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00005289 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005290
John McCalld7646252010-11-14 08:17:51 +00005291 llvm_unreachable("Unhandled scalar cast");
5292 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00005293}
5294
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005295/// CheckCastTypes - Check type constraints for casting between types.
John Wiegley01296292011-04-08 18:41:53 +00005296ExprResult Sema::CheckCastTypes(SourceRange TyR, QualType castType,
5297 Expr *castExpr, CastKind& Kind, ExprValueKind &VK,
5298 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall31996342011-04-07 08:22:57 +00005299 if (castExpr->getType() == Context.UnknownAnyTy)
5300 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
5301
Sebastian Redl9f831db2009-07-25 15:41:38 +00005302 if (getLangOptions().CPlusPlus)
Douglas Gregor15417cf2010-11-03 00:35:38 +00005303 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
5304 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00005305 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00005306 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00005307
John McCall3aef3d82011-04-10 19:13:55 +00005308 assert(!castExpr->getType()->isPlaceholderType());
5309
John McCall7decc9e2010-11-18 06:31:45 +00005310 // We only support r-value casts in C.
5311 VK = VK_RValue;
5312
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005313 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
5314 // type needs to be scalar.
5315 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00005316 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley01296292011-04-08 18:41:53 +00005317 ExprResult castExprRes = IgnoredValueConversions(castExpr);
5318 if (castExprRes.isInvalid())
5319 return ExprError();
5320 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00005321
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005322 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00005323 Kind = CK_ToVoid;
John Wiegley01296292011-04-08 18:41:53 +00005324 return Owned(castExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00005325 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005326
John Wiegley01296292011-04-08 18:41:53 +00005327 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
5328 if (castExprRes.isInvalid())
5329 return ExprError();
5330 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00005331
Eli Friedmane98194d2010-07-17 20:43:49 +00005332 if (RequireCompleteType(TyR.getBegin(), castType,
5333 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00005334 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00005335
Anders Carlssonef918ac2009-10-16 02:35:04 +00005336 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005337 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005338 (castType->isStructureType() || castType->isUnionType())) {
5339 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00005340 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005341 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
5342 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005343 Kind = CK_NoOp;
John Wiegley01296292011-04-08 18:41:53 +00005344 return Owned(castExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00005345 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005346
Anders Carlsson525b76b2009-10-16 02:48:28 +00005347 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005348 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005349 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005350 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005351 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005352 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005353 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00005354 castExpr->getType()) &&
5355 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005356 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5357 << castExpr->getSourceRange();
5358 break;
5359 }
5360 }
John Wiegley01296292011-04-08 18:41:53 +00005361 if (Field == FieldEnd) {
5362 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005363 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005364 return ExprError();
5365 }
John McCalle3027922010-08-25 11:45:40 +00005366 Kind = CK_ToUnion;
John Wiegley01296292011-04-08 18:41:53 +00005367 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005368 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005369
Anders Carlsson525b76b2009-10-16 02:48:28 +00005370 // Reject any other conversions to non-scalar types.
John Wiegley01296292011-04-08 18:41:53 +00005371 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlsson525b76b2009-10-16 02:48:28 +00005372 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005373 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005374 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005375
John McCalld7646252010-11-14 08:17:51 +00005376 // The type we're casting to is known to be a scalar or vector.
5377
5378 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005379 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00005380 !castExpr->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005381 Diag(castExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00005382 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005383 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005384 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005385 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005386
5387 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00005388 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005389
Anton Yartsev28ccef72011-03-27 09:32:40 +00005390 if (castType->isVectorType()) {
5391 if (castType->getAs<VectorType>()->getVectorKind() ==
5392 VectorType::AltiVecVector &&
5393 (castExpr->getType()->isIntegerType() ||
5394 castExpr->getType()->isFloatingType())) {
5395 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00005396 return Owned(castExpr);
5397 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
5398 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00005399 } else
John Wiegley01296292011-04-08 18:41:53 +00005400 return Owned(castExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00005401 }
John Wiegley01296292011-04-08 18:41:53 +00005402 if (castExpr->getType()->isVectorType()) {
5403 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
5404 return ExprError();
5405 else
5406 return Owned(castExpr);
5407 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00005408
John McCalld7646252010-11-14 08:17:51 +00005409 // The source and target types are both scalars, i.e.
5410 // - arithmetic types (fundamental, enum, and complex)
5411 // - all kinds of pointers
5412 // Note that member pointers were filtered out with C++, above.
5413
John Wiegley01296292011-04-08 18:41:53 +00005414 if (isa<ObjCSelectorExpr>(castExpr)) {
5415 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
5416 return ExprError();
5417 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005418
John McCalld7646252010-11-14 08:17:51 +00005419 // If either type is a pointer, the other type has to be either an
5420 // integer or a pointer.
Anders Carlsson525b76b2009-10-16 02:48:28 +00005421 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005422 QualType castExprType = castExpr->getType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005423 if (!castExprType->isIntegralType(Context) &&
John Wiegley01296292011-04-08 18:41:53 +00005424 castExprType->isArithmeticType()) {
5425 Diag(castExpr->getLocStart(),
5426 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005427 << castExprType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005428 return ExprError();
5429 }
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005430 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley01296292011-04-08 18:41:53 +00005431 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
5432 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005433 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005434 return ExprError();
5435 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005436 }
Anders Carlsson094c4592009-10-18 18:12:03 +00005437
John Wiegley01296292011-04-08 18:41:53 +00005438 castExprRes = Owned(castExpr);
5439 Kind = PrepareScalarCast(*this, castExprRes, castType);
5440 if (castExprRes.isInvalid())
5441 return ExprError();
5442 castExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00005443
John McCalld7646252010-11-14 08:17:51 +00005444 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00005445 CheckCastAlign(castExpr, castType, TyR);
5446
John Wiegley01296292011-04-08 18:41:53 +00005447 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005448}
5449
Anders Carlsson525b76b2009-10-16 02:48:28 +00005450bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00005451 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00005452 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005453
Anders Carlssonde71adf2007-11-27 05:51:55 +00005454 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00005455 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00005456 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00005457 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00005458 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00005459 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005460 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005461 } else
5462 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00005463 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005464 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005465
John McCalle3027922010-08-25 11:45:40 +00005466 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005467 return false;
5468}
5469
John Wiegley01296292011-04-08 18:41:53 +00005470ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5471 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00005472 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005473
Anders Carlsson43d70f82009-10-16 05:23:41 +00005474 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005475
Nate Begemanc8961a42009-06-27 22:05:55 +00005476 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5477 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00005478 if (SrcTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005479 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
5480 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00005481 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00005482 return ExprError();
5483 }
John McCalle3027922010-08-25 11:45:40 +00005484 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00005485 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00005486 }
5487
Nate Begemanbd956c42009-06-28 02:36:38 +00005488 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00005489 // conversion will take place first from scalar to elt type, and then
5490 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00005491 if (SrcTy->isPointerType())
5492 return Diag(R.getBegin(),
5493 diag::err_invalid_conversion_between_vector_and_scalar)
5494 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00005495
5496 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00005497 ExprResult CastExprRes = Owned(CastExpr);
5498 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
5499 if (CastExprRes.isInvalid())
5500 return ExprError();
5501 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005502
John McCalle3027922010-08-25 11:45:40 +00005503 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00005504 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00005505}
5506
John McCalldadc5752010-08-24 06:29:42 +00005507ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005508Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005509 SourceLocation RParenLoc, Expr *castExpr) {
5510 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00005511 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00005512
John McCall97513962010-01-15 18:39:57 +00005513 TypeSourceInfo *castTInfo;
5514 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5515 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00005516 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00005517
Nate Begeman5ec4b312009-08-10 23:49:36 +00005518 // If the Expr being casted is a ParenListExpr, handle it specially.
5519 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00005520 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00005521 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00005522
John McCallb268a282010-08-23 23:25:46 +00005523 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00005524}
5525
John McCalldadc5752010-08-24 06:29:42 +00005526ExprResult
John McCallebe54742010-01-15 18:56:44 +00005527Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00005528 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00005529 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00005530 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00005531 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00005532 ExprResult CastResult =
5533 CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
5534 Kind, VK, BasePath);
5535 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005536 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00005537 castExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00005538
John McCallcf142162010-08-07 06:22:56 +00005539 return Owned(CStyleCastExpr::Create(Context,
John Wiegley01296292011-04-08 18:41:53 +00005540 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00005541 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00005542 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00005543}
5544
Nate Begeman5ec4b312009-08-10 23:49:36 +00005545/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5546/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00005547ExprResult
John McCallb268a282010-08-23 23:25:46 +00005548Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005549 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5550 if (!E)
5551 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00005552
John McCalldadc5752010-08-24 06:29:42 +00005553 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00005554
Nate Begeman5ec4b312009-08-10 23:49:36 +00005555 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00005556 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5557 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00005558
John McCallb268a282010-08-23 23:25:46 +00005559 if (Result.isInvalid()) return ExprError();
5560
5561 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005562}
5563
John McCalldadc5752010-08-24 06:29:42 +00005564ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00005565Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00005566 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00005567 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00005568 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00005569 QualType Ty = TInfo->getType();
Anton Yartsev28ccef72011-03-27 09:32:40 +00005570 bool isVectorLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00005571
Anton Yartsev28ccef72011-03-27 09:32:40 +00005572 // Check for an altivec or OpenCL literal,
John Thompson781ad172010-06-30 22:55:51 +00005573 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005574 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5575 if (PE->getNumExprs() == 0) {
5576 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5577 return ExprError();
5578 }
John Thompson781ad172010-06-30 22:55:51 +00005579 if (PE->getNumExprs() == 1) {
5580 if (!PE->getExpr(0)->getType()->isVectorType())
Anton Yartsev28ccef72011-03-27 09:32:40 +00005581 isVectorLiteral = true;
John Thompson781ad172010-06-30 22:55:51 +00005582 }
5583 else
Anton Yartsev28ccef72011-03-27 09:32:40 +00005584 isVectorLiteral = true;
John Thompson781ad172010-06-30 22:55:51 +00005585 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00005586
Anton Yartsev28ccef72011-03-27 09:32:40 +00005587 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
John Thompson781ad172010-06-30 22:55:51 +00005588 // then handle it as such.
Anton Yartsev28ccef72011-03-27 09:32:40 +00005589 if (isVectorLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005590 llvm::SmallVector<Expr *, 8> initExprs;
Anton Yartsev28ccef72011-03-27 09:32:40 +00005591 // '(...)' form of vector initialization in AltiVec: the number of
5592 // initializers must be one or must match the size of the vector.
5593 // If a single value is specified in the initializer then it will be
5594 // replicated to all the components of the vector
5595 if (Ty->getAs<VectorType>()->getVectorKind() ==
5596 VectorType::AltiVecVector) {
5597 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5598 // The number of initializers must be one or must match the size of the
5599 // vector. If a single value is specified in the initializer then it will
5600 // be replicated to all the components of the vector
5601 if (PE->getNumExprs() == 1) {
5602 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00005603 ExprResult Literal = Owned(PE->getExpr(0));
5604 Literal = ImpCastExprToType(Literal.take(), ElemTy,
5605 PrepareScalarCast(*this, Literal, ElemTy));
5606 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
Anton Yartsev28ccef72011-03-27 09:32:40 +00005607 }
5608 else if (PE->getNumExprs() < numElems) {
5609 Diag(PE->getExprLoc(),
5610 diag::err_incorrect_number_of_vector_initializers);
5611 return ExprError();
5612 }
5613 else
5614 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5615 initExprs.push_back(PE->getExpr(i));
5616 }
5617 else
5618 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5619 initExprs.push_back(PE->getExpr(i));
Nate Begeman5ec4b312009-08-10 23:49:36 +00005620
5621 // FIXME: This means that pretty-printing the final AST will produce curly
5622 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00005623 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5624 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00005625 initExprs.size(), RParenLoc);
5626 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00005627 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005628 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005629 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00005630 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00005631 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00005632 if (Result.isInvalid()) return ExprError();
5633 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005634 }
5635}
5636
John McCalldadc5752010-08-24 06:29:42 +00005637ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00005638 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005639 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00005640 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005641 unsigned nexprs = Val.size();
5642 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005643 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5644 Expr *expr;
5645 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5646 expr = new (Context) ParenExpr(L, R, exprs[0]);
5647 else
5648 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005649 return Owned(expr);
5650}
5651
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005652/// \brief Emit a specialized diagnostic when one expression is a null pointer
5653/// constant and the other is not a pointer.
5654bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5655 SourceLocation QuestionLoc) {
5656 Expr *NullExpr = LHS;
5657 Expr *NonPointerExpr = RHS;
5658 Expr::NullPointerConstantKind NullKind =
5659 NullExpr->isNullPointerConstant(Context,
5660 Expr::NPC_ValueDependentIsNotNull);
5661
5662 if (NullKind == Expr::NPCK_NotNull) {
5663 NullExpr = RHS;
5664 NonPointerExpr = LHS;
5665 NullKind =
5666 NullExpr->isNullPointerConstant(Context,
5667 Expr::NPC_ValueDependentIsNotNull);
5668 }
5669
5670 if (NullKind == Expr::NPCK_NotNull)
5671 return false;
5672
5673 if (NullKind == Expr::NPCK_ZeroInteger) {
5674 // In this case, check to make sure that we got here from a "NULL"
5675 // string in the source code.
5676 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00005677 SourceLocation loc = NullExpr->getExprLoc();
5678 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005679 return false;
5680 }
5681
5682 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5683 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5684 << NonPointerExpr->getType() << DiagType
5685 << NonPointerExpr->getSourceRange();
5686 return true;
5687}
5688
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005689/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5690/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00005691/// C99 6.5.15
John Wiegley01296292011-04-08 18:41:53 +00005692QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005693 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00005694 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00005695
John McCall3aef3d82011-04-10 19:13:55 +00005696 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00005697 if (!lhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005698 LHS = move(lhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005699
John McCall3aef3d82011-04-10 19:13:55 +00005700 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00005701 if (!rhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005702 RHS = move(rhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005703
Sebastian Redl1a99f442009-04-16 17:51:27 +00005704 // C++ is sufficiently different to merit its own checker.
5705 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00005706 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00005707
5708 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005709 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005710
John Wiegley01296292011-04-08 18:41:53 +00005711 Cond = UsualUnaryConversions(Cond.take());
5712 if (Cond.isInvalid())
5713 return QualType();
5714 LHS = UsualUnaryConversions(LHS.take());
5715 if (LHS.isInvalid())
5716 return QualType();
5717 RHS = UsualUnaryConversions(RHS.take());
5718 if (RHS.isInvalid())
5719 return QualType();
5720
5721 QualType CondTy = Cond.get()->getType();
5722 QualType LHSTy = LHS.get()->getType();
5723 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00005724
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005725 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005726 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00005727 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5728 // Throw an error if its not either.
5729 if (getLangOptions().OpenCL) {
5730 if (!CondTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005731 Diag(Cond.get()->getLocStart(),
Nate Begemanabb5a732010-09-20 22:41:17 +00005732 diag::err_typecheck_cond_expect_scalar_or_vector)
5733 << CondTy;
5734 return QualType();
5735 }
5736 }
5737 else {
John Wiegley01296292011-04-08 18:41:53 +00005738 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005739 << CondTy;
5740 return QualType();
5741 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005742 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005743
Chris Lattnere2949f42008-01-06 22:42:25 +00005744 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005745 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5746 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00005747
Nate Begemanabb5a732010-09-20 22:41:17 +00005748 // OpenCL: If the condition is a vector, and both operands are scalar,
5749 // attempt to implicity convert them to the vector type to act like the
5750 // built in select.
5751 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5752 // Both operands should be of scalar type.
5753 if (!LHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00005754 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005755 << CondTy;
5756 return QualType();
5757 }
5758 if (!RHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00005759 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005760 << CondTy;
5761 return QualType();
5762 }
5763 // Implicity convert these scalars to the type of the condition.
John Wiegley01296292011-04-08 18:41:53 +00005764 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5765 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begemanabb5a732010-09-20 22:41:17 +00005766 }
5767
Chris Lattnere2949f42008-01-06 22:42:25 +00005768 // If both operands have arithmetic type, do the usual arithmetic conversions
5769 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00005770 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5771 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005772 if (LHS.isInvalid() || RHS.isInvalid())
5773 return QualType();
5774 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00005775 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005776
Chris Lattnere2949f42008-01-06 22:42:25 +00005777 // If both operands are the same structure or union type, the result is that
5778 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005779 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5780 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00005781 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005782 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00005783 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00005784 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00005785 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005786 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005787
Chris Lattnere2949f42008-01-06 22:42:25 +00005788 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00005789 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00005790 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5791 if (!LHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00005792 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5793 << RHS.get()->getSourceRange();
Chris Lattner432cff52009-02-18 04:28:32 +00005794 if (!RHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00005795 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5796 << LHS.get()->getSourceRange();
5797 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
5798 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00005799 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00005800 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00005801 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5802 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00005803 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00005804 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005805 // promote the null to a pointer.
John Wiegley01296292011-04-08 18:41:53 +00005806 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005807 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005808 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005809 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00005810 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5811 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005812 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005813 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005814
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005815 // All objective-c pointer type analysis is done here.
5816 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5817 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005818 if (LHS.isInvalid() || RHS.isInvalid())
5819 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005820 if (!compositeType.isNull())
5821 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005822
5823
Steve Naroff05efa972009-07-01 14:36:47 +00005824 // Handle block pointer types.
5825 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5826 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5827 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5828 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00005829 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5830 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005831 return destType;
5832 }
5833 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005834 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00005835 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00005836 }
Steve Naroff05efa972009-07-01 14:36:47 +00005837 // We have 2 block pointer types.
5838 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5839 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00005840 return LHSTy;
5841 }
Steve Naroff05efa972009-07-01 14:36:47 +00005842 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005843 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5844 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005845
Steve Naroff05efa972009-07-01 14:36:47 +00005846 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5847 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00005848 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00005849 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00005850 // In this situation, we assume void* type. No especially good
5851 // reason, but this is what gcc does, and we do have to pick
5852 // to get a consistent AST.
5853 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00005854 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5855 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00005856 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005857 }
Steve Naroff05efa972009-07-01 14:36:47 +00005858 // The block pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00005859 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
5860 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00005861 return LHSTy;
5862 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005863
Steve Naroff05efa972009-07-01 14:36:47 +00005864 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5865 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5866 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005867 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5868 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00005869
5870 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5871 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5872 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00005873 QualType destPointee
5874 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005875 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005876 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005877 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005878 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005879 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005880 return destType;
5881 }
5882 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005883 QualType destPointee
5884 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00005885 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005886 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005887 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00005888 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005889 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005890 return destType;
5891 }
5892
5893 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5894 // Two identical pointer types are always compatible.
5895 return LHSTy;
5896 }
5897 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5898 rhptee.getUnqualifiedType())) {
5899 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00005900 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00005901 // In this situation, we assume void* type. No especially good
5902 // reason, but this is what gcc does, and we do have to pick
5903 // to get a consistent AST.
5904 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00005905 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5906 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005907 return incompatTy;
5908 }
5909 // The pointer types are compatible.
5910 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5911 // differently qualified versions of compatible types, the result type is
5912 // a pointer to an appropriately qualified version of the *composite*
5913 // type.
5914 // FIXME: Need to calculate the composite type.
5915 // FIXME: Need to add qualifiers
John Wiegley01296292011-04-08 18:41:53 +00005916 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
5917 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005918 return LHSTy;
5919 }
Mike Stump11289f42009-09-09 15:08:12 +00005920
John McCalle84af4e2010-11-13 01:35:44 +00005921 // GCC compatibility: soften pointer/integer mismatch. Note that
5922 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00005923 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5924 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00005925 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5926 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005927 return RHSTy;
5928 }
5929 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5930 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00005931 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5932 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00005933 return LHSTy;
5934 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00005935
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005936 // Emit a better diagnostic if one of the expressions is a null pointer
5937 // constant and the other is not a pointer type. In this case, the user most
5938 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005939 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005940 return QualType();
5941
Chris Lattnere2949f42008-01-06 22:42:25 +00005942 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00005943 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005944 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005945 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00005946}
5947
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005948/// FindCompositeObjCPointerType - Helper method to find composite type of
5949/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00005950QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005951 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005952 QualType LHSTy = LHS.get()->getType();
5953 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005954
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005955 // Handle things like Class and struct objc_class*. Here we case the result
5956 // to the pseudo-builtin, because that will be implicitly cast back to the
5957 // redefinition type if an attempt is made to access its fields.
5958 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005959 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00005960 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005961 return LHSTy;
5962 }
5963 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00005964 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00005965 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005966 return RHSTy;
5967 }
5968 // And the same for struct objc_object* / id
5969 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005970 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00005971 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005972 return LHSTy;
5973 }
5974 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00005975 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00005976 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005977 return RHSTy;
5978 }
5979 // And the same for struct objc_selector* / SEL
5980 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005981 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00005982 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005983 return LHSTy;
5984 }
5985 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00005986 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00005987 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005988 return RHSTy;
5989 }
5990 // Check constraints for Objective-C object pointers types.
5991 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005992
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005993 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5994 // Two identical object pointer types are always compatible.
5995 return LHSTy;
5996 }
5997 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5998 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5999 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006000
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006001 // If both operands are interfaces and either operand can be
6002 // assigned to the other, use that type as the composite
6003 // type. This allows
6004 // xxx ? (A*) a : (B*) b
6005 // where B is a subclass of A.
6006 //
6007 // Additionally, as for assignment, if either type is 'id'
6008 // allow silent coercion. Finally, if the types are
6009 // incompatible then make sure to use 'id' as the composite
6010 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006011
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006012 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6013 // It could return the composite type.
6014 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6015 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6016 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6017 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6018 } else if ((LHSTy->isObjCQualifiedIdType() ||
6019 RHSTy->isObjCQualifiedIdType()) &&
6020 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6021 // Need to handle "id<xx>" explicitly.
6022 // GCC allows qualified id and any Objective-C type to devolve to
6023 // id. Currently localizing to here until clear this should be
6024 // part of ObjCQualifiedIdTypesAreCompatible.
6025 compositeType = Context.getObjCIdType();
6026 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6027 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006028 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006029 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
6030 ;
6031 else {
6032 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6033 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00006034 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006035 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00006036 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6037 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006038 return incompatTy;
6039 }
6040 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00006041 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
6042 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006043 return compositeType;
6044 }
6045 // Check Objective-C object pointer types and 'void *'
6046 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6047 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6048 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6049 QualType destPointee
6050 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6051 QualType destType = Context.getPointerType(destPointee);
6052 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00006053 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006054 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00006055 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006056 return destType;
6057 }
6058 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6059 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6060 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6061 QualType destPointee
6062 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6063 QualType destType = Context.getPointerType(destPointee);
6064 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00006065 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006066 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00006067 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006068 return destType;
6069 }
6070 return QualType();
6071}
6072
Steve Naroff83895f72007-09-16 03:34:24 +00006073/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00006074/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00006075ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00006076 SourceLocation ColonLoc,
6077 Expr *CondExpr, Expr *LHSExpr,
6078 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00006079 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6080 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00006081 OpaqueValueExpr *opaqueValue = 0;
6082 Expr *commonExpr = 0;
6083 if (LHSExpr == 0) {
6084 commonExpr = CondExpr;
6085
6086 // We usually want to apply unary conversions *before* saving, except
6087 // in the special case of a C++ l-value conditional.
6088 if (!(getLangOptions().CPlusPlus
6089 && !commonExpr->isTypeDependent()
6090 && commonExpr->getValueKind() == RHSExpr->getValueKind()
6091 && commonExpr->isGLValue()
6092 && commonExpr->isOrdinaryOrBitFieldObject()
6093 && RHSExpr->isOrdinaryOrBitFieldObject()
6094 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00006095 ExprResult commonRes = UsualUnaryConversions(commonExpr);
6096 if (commonRes.isInvalid())
6097 return ExprError();
6098 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00006099 }
6100
6101 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6102 commonExpr->getType(),
6103 commonExpr->getValueKind(),
6104 commonExpr->getObjectKind());
6105 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00006106 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00006107
John McCall7decc9e2010-11-18 06:31:45 +00006108 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00006109 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00006110 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
6111 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00006112 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00006113 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6114 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00006115 return ExprError();
6116
John McCallc07a0c72011-02-17 10:25:35 +00006117 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00006118 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
6119 LHS.take(), ColonLoc,
6120 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00006121
6122 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00006123 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
6124 RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00006125}
6126
John McCallaba90822011-01-31 23:13:11 +00006127// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00006128// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00006129// routine is it effectively iqnores the qualifiers on the top level pointee.
6130// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6131// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00006132static Sema::AssignConvertType
6133checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6134 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6135 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006136
Steve Naroff1f4d7272007-05-11 04:00:31 +00006137 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00006138 const Type *lhptee, *rhptee;
6139 Qualifiers lhq, rhq;
6140 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
6141 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006142
John McCallaba90822011-01-31 23:13:11 +00006143 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006144
6145 // C99 6.5.16.1p1: This following citation is common to constraints
6146 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6147 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00006148 Qualifiers lq;
6149
6150 if (!lhq.compatiblyIncludes(rhq)) {
6151 // Treat address-space mismatches as fatal. TODO: address subspaces
6152 if (lhq.getAddressSpace() != rhq.getAddressSpace())
6153 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6154
John McCall78535952011-03-26 02:56:45 +00006155 // It's okay to add or remove GC qualifiers when converting to
6156 // and from void*.
6157 else if (lhq.withoutObjCGCAttr().compatiblyIncludes(rhq.withoutObjCGCAttr())
6158 && (lhptee->isVoidType() || rhptee->isVoidType()))
6159 ; // keep old
6160
John McCall4fff8f62011-02-01 00:10:29 +00006161 // For GCC compatibility, other qualifier mismatches are treated
6162 // as still compatible in C.
6163 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6164 }
Steve Naroff3f597292007-05-11 22:18:03 +00006165
Mike Stump4e1f26a2009-02-19 03:04:26 +00006166 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6167 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00006168 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00006169 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006170 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00006171 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006172
Chris Lattner0a788432008-01-03 22:56:36 +00006173 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006174 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00006175 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00006176 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006177
Chris Lattner0a788432008-01-03 22:56:36 +00006178 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006179 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00006180 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00006181
6182 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006183 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00006184 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00006185 }
John McCall4fff8f62011-02-01 00:10:29 +00006186
Mike Stump4e1f26a2009-02-19 03:04:26 +00006187 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00006188 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00006189 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6190 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00006191 // Check if the pointee types are compatible ignoring the sign.
6192 // We explicitly check for char so that we catch "char" vs
6193 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00006194 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00006195 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006196 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00006197 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006198
Chris Lattnerec3a1562009-10-17 20:33:28 +00006199 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00006200 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006201 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00006202 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00006203
John McCall4fff8f62011-02-01 00:10:29 +00006204 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00006205 // Types are compatible ignoring the sign. Qualifier incompatibility
6206 // takes priority over sign incompatibility because the sign
6207 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00006208 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00006209 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00006210
John McCallaba90822011-01-31 23:13:11 +00006211 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00006212 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006213
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006214 // If we are a multi-level pointer, it's possible that our issue is simply
6215 // one of qualification - e.g. char ** -> const char ** is not allowed. If
6216 // the eventual target type is the same and the pointers have the same
6217 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00006218 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006219 do {
John McCall4fff8f62011-02-01 00:10:29 +00006220 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6221 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00006222 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006223
John McCall4fff8f62011-02-01 00:10:29 +00006224 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00006225 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006226 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006227
Eli Friedman80160bd2009-03-22 23:59:44 +00006228 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00006229 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00006230 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00006231 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00006232}
6233
John McCallaba90822011-01-31 23:13:11 +00006234/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00006235/// block pointer types are compatible or whether a block and normal pointer
6236/// are compatible. It is more restrict than comparing two function pointer
6237// types.
John McCallaba90822011-01-31 23:13:11 +00006238static Sema::AssignConvertType
6239checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
6240 QualType rhsType) {
6241 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6242 assert(rhsType.isCanonical() && "RHS not canonicalized!");
6243
Steve Naroff081c7422008-09-04 15:10:53 +00006244 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006245
Steve Naroff081c7422008-09-04 15:10:53 +00006246 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00006247 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
6248 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006249
John McCallaba90822011-01-31 23:13:11 +00006250 // In C++, the types have to match exactly.
6251 if (S.getLangOptions().CPlusPlus)
6252 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006253
John McCallaba90822011-01-31 23:13:11 +00006254 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006255
Steve Naroff081c7422008-09-04 15:10:53 +00006256 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00006257 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6258 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006259
John McCallaba90822011-01-31 23:13:11 +00006260 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
6261 return Sema::IncompatibleBlockPointer;
6262
Steve Naroff081c7422008-09-04 15:10:53 +00006263 return ConvTy;
6264}
6265
John McCallaba90822011-01-31 23:13:11 +00006266/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006267/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00006268static Sema::AssignConvertType
6269checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6270 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
6271 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
6272
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006273 if (lhsType->isObjCBuiltinType()) {
6274 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00006275 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
6276 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00006277 return Sema::IncompatiblePointer;
6278 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006279 }
6280 if (rhsType->isObjCBuiltinType()) {
6281 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00006282 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
6283 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00006284 return Sema::IncompatiblePointer;
6285 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006286 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006287 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006288 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006289 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006290 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006291
John McCallaba90822011-01-31 23:13:11 +00006292 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
6293 return Sema::CompatiblePointerDiscardsQualifiers;
6294
6295 if (S.Context.typesAreCompatible(lhsType, rhsType))
6296 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006297 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00006298 return Sema::IncompatibleObjCQualifiedId;
6299 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006300}
6301
John McCall29600e12010-11-16 02:32:08 +00006302Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00006303Sema::CheckAssignmentConstraints(SourceLocation Loc,
6304 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00006305 // Fake up an opaque expression. We don't actually care about what
6306 // cast operations are required, so if CheckAssignmentConstraints
6307 // adds casts to this they'll be wasted, but fortunately that doesn't
6308 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00006309 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00006310 ExprResult rhsPtr = &rhs;
John McCall29600e12010-11-16 02:32:08 +00006311 CastKind K = CK_Invalid;
6312
6313 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
6314}
6315
Mike Stump4e1f26a2009-02-19 03:04:26 +00006316/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6317/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00006318/// pointers. Here are some objectionable examples that GCC considers warnings:
6319///
6320/// int a, *pint;
6321/// short *pshort;
6322/// struct foo *pfoo;
6323///
6324/// pint = pshort; // warning: assignment from incompatible pointer type
6325/// a = pint; // warning: assignment makes integer from pointer without a cast
6326/// pint = a; // warning: assignment makes pointer from integer without a cast
6327/// pint = pfoo; // warning: assignment from incompatible pointer type
6328///
6329/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00006330/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00006331///
John McCall8cb679e2010-11-15 09:13:47 +00006332/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00006333Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006334Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCall8cb679e2010-11-15 09:13:47 +00006335 CastKind &Kind) {
John Wiegley01296292011-04-08 18:41:53 +00006336 QualType rhsType = rhs.get()->getType();
John McCall29600e12010-11-16 02:32:08 +00006337
Chris Lattnera52c2f22008-01-04 23:18:45 +00006338 // Get canonical types. We're not formatting these types, just comparing
6339 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00006340 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
6341 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00006342
John McCalle5255932011-01-31 22:28:28 +00006343 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00006344 if (lhsType == rhsType) {
6345 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00006346 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00006347 }
6348
Douglas Gregor6b754842008-10-28 00:22:11 +00006349 // If the left-hand side is a reference type, then we are in a
6350 // (rare!) case where we've allowed the use of references in C,
6351 // e.g., as a parameter type in a built-in function. In this case,
6352 // just make sure that the type referenced is compatible with the
6353 // right-hand side type. The caller is responsible for adjusting
6354 // lhsType so that the resulting expression does not have reference
6355 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006356 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00006357 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
6358 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00006359 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006360 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00006361 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00006362 }
John McCalle5255932011-01-31 22:28:28 +00006363
Nate Begemanbd956c42009-06-28 02:36:38 +00006364 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6365 // to the same ExtVector type.
6366 if (lhsType->isExtVectorType()) {
6367 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00006368 return Incompatible;
6369 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00006370 // CK_VectorSplat does T -> vector T, so first cast to the
6371 // element type.
6372 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
6373 if (elType != rhsType) {
6374 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley01296292011-04-08 18:41:53 +00006375 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00006376 }
6377 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00006378 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006379 }
Nate Begemanbd956c42009-06-28 02:36:38 +00006380 }
Mike Stump11289f42009-09-09 15:08:12 +00006381
John McCalle5255932011-01-31 22:28:28 +00006382 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00006383 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006384 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00006385 // Allow assignments of an AltiVec vector type to an equivalent GCC
6386 // vector type and vice versa
6387 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6388 Kind = CK_BitCast;
6389 return Compatible;
6390 }
6391
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006392 // If we are allowing lax vector conversions, and LHS and RHS are both
6393 // vectors, the total size only needs to be the same. This is a bitcast;
6394 // no bits are changed but the result type is different.
6395 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00006396 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00006397 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006398 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00006399 }
Chris Lattner881a2122008-01-04 23:32:24 +00006400 }
6401 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006402 }
Eli Friedman3360d892008-05-30 18:07:22 +00006403
John McCalle5255932011-01-31 22:28:28 +00006404 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00006405 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00006406 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00006407 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00006408 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006409 }
Eli Friedman3360d892008-05-30 18:07:22 +00006410
John McCalle5255932011-01-31 22:28:28 +00006411 // Conversions to normal pointers.
6412 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
6413 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00006414 if (isa<PointerType>(rhsType)) {
6415 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006416 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00006417 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006418
John McCalle5255932011-01-31 22:28:28 +00006419 // int -> T*
6420 if (rhsType->isIntegerType()) {
6421 Kind = CK_IntegralToPointer; // FIXME: null?
6422 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006423 }
John McCalle5255932011-01-31 22:28:28 +00006424
6425 // C pointers are not compatible with ObjC object pointers,
6426 // with two exceptions:
6427 if (isa<ObjCObjectPointerType>(rhsType)) {
6428 // - conversions to void*
6429 if (lhsPointer->getPointeeType()->isVoidType()) {
6430 Kind = CK_AnyPointerToObjCPointerCast;
6431 return Compatible;
6432 }
6433
6434 // - conversions from 'Class' to the redefinition type
6435 if (rhsType->isObjCClassType() &&
6436 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006437 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006438 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006439 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006440
John McCalle5255932011-01-31 22:28:28 +00006441 Kind = CK_BitCast;
6442 return IncompatiblePointer;
6443 }
6444
6445 // U^ -> void*
6446 if (rhsType->getAs<BlockPointerType>()) {
6447 if (lhsPointer->getPointeeType()->isVoidType()) {
6448 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006449 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006450 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006451 }
John McCalle5255932011-01-31 22:28:28 +00006452
Steve Naroff081c7422008-09-04 15:10:53 +00006453 return Incompatible;
6454 }
6455
John McCalle5255932011-01-31 22:28:28 +00006456 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00006457 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006458 // U^ -> T^
6459 if (rhsType->isBlockPointerType()) {
6460 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00006461 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006462 }
6463
6464 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006465 if (rhsType->isIntegerType()) {
6466 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00006467 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006468 }
6469
John McCalle5255932011-01-31 22:28:28 +00006470 // id -> T^
6471 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6472 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006473 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006474 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006475
John McCalle5255932011-01-31 22:28:28 +00006476 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006477 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00006478 if (RHSPT->getPointeeType()->isVoidType()) {
6479 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006480 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006481 }
John McCall8cb679e2010-11-15 09:13:47 +00006482
Chris Lattnera52c2f22008-01-04 23:18:45 +00006483 return Incompatible;
6484 }
6485
John McCalle5255932011-01-31 22:28:28 +00006486 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006487 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006488 // A* -> B*
6489 if (rhsType->isObjCObjectPointerType()) {
6490 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006491 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006492 }
6493
6494 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00006495 if (rhsType->isIntegerType()) {
6496 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00006497 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006498 }
6499
John McCalle5255932011-01-31 22:28:28 +00006500 // In general, C pointers are not compatible with ObjC object pointers,
6501 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00006502 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006503 // - conversions from 'void*'
6504 if (rhsType->isVoidPointerType()) {
6505 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006506 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006507 }
6508
6509 // - conversions to 'Class' from its redefinition type
6510 if (lhsType->isObjCClassType() &&
6511 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6512 Kind = CK_BitCast;
6513 return Compatible;
6514 }
6515
6516 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006517 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006518 }
John McCalle5255932011-01-31 22:28:28 +00006519
6520 // T^ -> A*
6521 if (rhsType->isBlockPointerType()) {
6522 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006523 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006524 }
6525
Steve Naroff7cae42b2009-07-10 23:34:53 +00006526 return Incompatible;
6527 }
John McCalle5255932011-01-31 22:28:28 +00006528
6529 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00006530 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006531 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006532 if (lhsType == Context.BoolTy) {
6533 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00006534 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006535 }
Eli Friedman3360d892008-05-30 18:07:22 +00006536
John McCalle5255932011-01-31 22:28:28 +00006537 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006538 if (lhsType->isIntegerType()) {
6539 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006540 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006541 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006542
Chris Lattnera52c2f22008-01-04 23:18:45 +00006543 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00006544 }
John McCalle5255932011-01-31 22:28:28 +00006545
6546 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006547 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006548 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006549 if (lhsType == Context.BoolTy) {
6550 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006551 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006552 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006553
John McCalle5255932011-01-31 22:28:28 +00006554 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006555 if (lhsType->isIntegerType()) {
6556 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006557 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006558 }
6559
Steve Naroff7cae42b2009-07-10 23:34:53 +00006560 return Incompatible;
6561 }
Eli Friedman3360d892008-05-30 18:07:22 +00006562
John McCalle5255932011-01-31 22:28:28 +00006563 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00006564 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006565 if (Context.typesAreCompatible(lhsType, rhsType)) {
6566 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00006567 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006568 }
Bill Wendling216423b2007-05-30 06:30:29 +00006569 }
John McCalle5255932011-01-31 22:28:28 +00006570
Steve Naroff98cf3e92007-06-06 18:38:38 +00006571 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00006572}
6573
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006574/// \brief Constructs a transparent union from an expression that is
6575/// used to initialize the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00006576static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006577 QualType UnionType, FieldDecl *Field) {
6578 // Build an initializer list that designates the appropriate member
6579 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00006580 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00006581 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00006582 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006583 SourceLocation());
6584 Initializer->setType(UnionType);
6585 Initializer->setInitializedFieldInUnion(Field);
6586
6587 // Build a compound literal constructing a value of the transparent
6588 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00006589 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00006590 EResult = S.Owned(
6591 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6592 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006593}
6594
6595Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006596Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
6597 QualType FromType = rExpr.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006598
Mike Stump11289f42009-09-09 15:08:12 +00006599 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006600 // transparent_union GCC extension.
6601 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006602 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006603 return Incompatible;
6604
6605 // The field to initialize within the transparent union.
6606 RecordDecl *UD = UT->getDecl();
6607 FieldDecl *InitField = 0;
6608 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006609 for (RecordDecl::field_iterator it = UD->field_begin(),
6610 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006611 it != itend; ++it) {
6612 if (it->getType()->isPointerType()) {
6613 // If the transparent union contains a pointer type, we allow:
6614 // 1) void pointer
6615 // 2) null pointer constant
6616 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006617 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley01296292011-04-08 18:41:53 +00006618 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006619 InitField = *it;
6620 break;
6621 }
Mike Stump11289f42009-09-09 15:08:12 +00006622
John Wiegley01296292011-04-08 18:41:53 +00006623 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006624 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006625 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006626 InitField = *it;
6627 break;
6628 }
6629 }
6630
John McCall8cb679e2010-11-15 09:13:47 +00006631 CastKind Kind = CK_Invalid;
John Wiegley01296292011-04-08 18:41:53 +00006632 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006633 == Compatible) {
John Wiegley01296292011-04-08 18:41:53 +00006634 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006635 InitField = *it;
6636 break;
6637 }
6638 }
6639
6640 if (!InitField)
6641 return Incompatible;
6642
John Wiegley01296292011-04-08 18:41:53 +00006643 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006644 return Compatible;
6645}
6646
Chris Lattner9bad62c2008-01-04 18:04:52 +00006647Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006648Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00006649 if (getLangOptions().CPlusPlus) {
6650 if (!lhsType->isRecordType()) {
6651 // C++ 5.17p3: If the left operand is not of class type, the
6652 // expression is implicitly converted (C++ 4) to the
6653 // cv-unqualified type of the left operand.
John Wiegley01296292011-04-08 18:41:53 +00006654 ExprResult Res = PerformImplicitConversion(rExpr.get(),
6655 lhsType.getUnqualifiedType(),
6656 AA_Assigning);
6657 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00006658 return Incompatible;
John Wiegley01296292011-04-08 18:41:53 +00006659 rExpr = move(Res);
Chris Lattner0d5640c2009-04-12 09:02:39 +00006660 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00006661 }
6662
6663 // FIXME: Currently, we fall through and treat C++ classes like C
6664 // structures.
John McCall34376a62010-12-04 03:47:34 +00006665 }
Douglas Gregor9a657932008-10-21 23:43:52 +00006666
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006667 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6668 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00006669 if ((lhsType->isPointerType() ||
6670 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00006671 lhsType->isBlockPointerType())
John Wiegley01296292011-04-08 18:41:53 +00006672 && rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006673 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006674 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006675 return Compatible;
6676 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006677
Chris Lattnere6dcd502007-10-16 02:55:40 +00006678 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006679 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00006680 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00006681 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00006682 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00006683 // Suppress this for references: C++ 8.5.3p5.
John Wiegley01296292011-04-08 18:41:53 +00006684 if (!lhsType->isReferenceType()) {
6685 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
6686 if (rExpr.isInvalid())
6687 return Incompatible;
6688 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006689
John McCall8cb679e2010-11-15 09:13:47 +00006690 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006691 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00006692 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006693
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006694 // C99 6.5.16.1p2: The value of the right operand is converted to the
6695 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00006696 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6697 // so that we can use references in built-in functions even in C.
6698 // The getNonReferenceType() call makes sure that the resulting expression
6699 // does not have reference type.
John Wiegley01296292011-04-08 18:41:53 +00006700 if (result != Incompatible && rExpr.get()->getType() != lhsType)
6701 rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006702 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006703}
6704
John Wiegley01296292011-04-08 18:41:53 +00006705QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006706 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley01296292011-04-08 18:41:53 +00006707 << lex.get()->getType() << rex.get()->getType()
6708 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00006709 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00006710}
6711
John Wiegley01296292011-04-08 18:41:53 +00006712QualType Sema::CheckVectorOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00006713 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006714 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00006715 QualType lhsType =
John Wiegley01296292011-04-08 18:41:53 +00006716 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattner574dee62008-07-26 22:17:49 +00006717 QualType rhsType =
John Wiegley01296292011-04-08 18:41:53 +00006718 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006719
Nate Begeman191a6b12008-07-14 18:02:46 +00006720 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006721 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00006722 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00006723
Nate Begeman191a6b12008-07-14 18:02:46 +00006724 // Handle the case of a vector & extvector type of the same size and element
6725 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006726 if (getLangOptions().LaxVectorConversions) {
John McCall9dd450b2009-09-21 23:43:11 +00006727 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006728 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006729 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006730 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006731 if (lhsType->isExtVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00006732 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006733 return lhsType;
6734 }
6735
John Wiegley01296292011-04-08 18:41:53 +00006736 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006737 return rhsType;
Eric Christophera613f562010-08-26 00:42:16 +00006738 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6739 // If we are allowing lax vector conversions, and LHS and RHS are both
6740 // vectors, the total size only needs to be the same. This is a
6741 // bitcast; no bits are changed but the result type is different.
John Wiegley01296292011-04-08 18:41:53 +00006742 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Eric Christophera613f562010-08-26 00:42:16 +00006743 return lhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006744 }
Eric Christophera613f562010-08-26 00:42:16 +00006745 }
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00006746 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006747 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006748
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006749 // Handle the case of equivalent AltiVec and GCC vector types
6750 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6751 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John Wiegley01296292011-04-08 18:41:53 +00006752 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006753 return rhsType;
6754 }
6755
Nate Begemanbd956c42009-06-28 02:36:38 +00006756 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6757 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6758 bool swapped = false;
6759 if (rhsType->isExtVectorType()) {
6760 swapped = true;
6761 std::swap(rex, lex);
6762 std::swap(rhsType, lhsType);
6763 }
Mike Stump11289f42009-09-09 15:08:12 +00006764
Nate Begeman886448d2009-06-28 19:12:57 +00006765 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00006766 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00006767 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00006768 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00006769 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6770 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00006771 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00006772 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00006773 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006774 if (swapped) std::swap(rex, lex);
6775 return lhsType;
6776 }
6777 }
6778 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6779 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00006780 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6781 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00006782 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00006783 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00006784 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00006785 if (swapped) std::swap(rex, lex);
6786 return lhsType;
6787 }
Nate Begeman330aaa72007-12-30 02:59:45 +00006788 }
6789 }
Mike Stump11289f42009-09-09 15:08:12 +00006790
Nate Begeman886448d2009-06-28 19:12:57 +00006791 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00006792 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley01296292011-04-08 18:41:53 +00006793 << lex.get()->getType() << rex.get()->getType()
6794 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00006795 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00006796}
6797
Chris Lattnerfaa54172010-01-12 21:23:57 +00006798QualType Sema::CheckMultiplyDivideOperands(
John Wiegley01296292011-04-08 18:41:53 +00006799 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
6800 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00006801 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006802
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006803 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00006804 if (lex.isInvalid() || rex.isInvalid())
6805 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006806
John Wiegley01296292011-04-08 18:41:53 +00006807 if (!lex.get()->getType()->isArithmeticType() ||
6808 !rex.get()->getType()->isArithmeticType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00006809 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006810
Chris Lattnerfaa54172010-01-12 21:23:57 +00006811 // Check for division by zero.
6812 if (isDiv &&
John Wiegley01296292011-04-08 18:41:53 +00006813 rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6814 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
6815 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006816
Chris Lattnerfaa54172010-01-12 21:23:57 +00006817 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006818}
6819
Chris Lattnerfaa54172010-01-12 21:23:57 +00006820QualType Sema::CheckRemainderOperands(
John Wiegley01296292011-04-08 18:41:53 +00006821 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
6822 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
6823 if (lex.get()->getType()->hasIntegerRepresentation() &&
6824 rex.get()->getType()->hasIntegerRepresentation())
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006825 return CheckVectorOperands(Loc, lex, rex);
6826 return InvalidOperands(Loc, lex, rex);
6827 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006828
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006829 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00006830 if (lex.isInvalid() || rex.isInvalid())
6831 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006832
John Wiegley01296292011-04-08 18:41:53 +00006833 if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00006834 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006835
Chris Lattnerfaa54172010-01-12 21:23:57 +00006836 // Check for remainder by zero.
John Wiegley01296292011-04-08 18:41:53 +00006837 if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6838 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
6839 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006840
Chris Lattnerfaa54172010-01-12 21:23:57 +00006841 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006842}
6843
Chris Lattnerfaa54172010-01-12 21:23:57 +00006844QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00006845 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
6846 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006847 QualType compType = CheckVectorOperands(Loc, lex, rex);
6848 if (CompLHSTy) *CompLHSTy = compType;
6849 return compType;
6850 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006851
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006852 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00006853 if (lex.isInvalid() || rex.isInvalid())
6854 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006855
Steve Naroffe4718892007-04-27 18:30:00 +00006856 // handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00006857 if (lex.get()->getType()->isArithmeticType() &&
6858 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006859 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006860 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006861 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006862
Eli Friedman8e122982008-05-18 18:08:51 +00006863 // Put any potential pointer into PExp
John Wiegley01296292011-04-08 18:41:53 +00006864 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00006865 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006866 std::swap(PExp, IExp);
6867
Steve Naroff6b712a72009-07-14 18:25:06 +00006868 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006869
Eli Friedman8e122982008-05-18 18:08:51 +00006870 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006871 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00006872
Chris Lattner12bdebb2009-04-24 23:50:08 +00006873 // Check for arithmetic on pointers to incomplete types.
6874 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006875 if (getLangOptions().CPlusPlus) {
6876 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00006877 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00006878 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006879 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006880
6881 // GNU extension: arithmetic on pointer to void
6882 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00006883 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00006884 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006885 if (getLangOptions().CPlusPlus) {
6886 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00006887 << lex.get()->getType() << lex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006888 return QualType();
6889 }
6890
6891 // GNU extension: arithmetic on pointer to function
6892 Diag(Loc, diag::ext_gnu_ptr_func_arith)
John Wiegley01296292011-04-08 18:41:53 +00006893 << lex.get()->getType() << lex.get()->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00006894 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006895 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00006896 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00006897 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006898 PExp->getType()->isObjCObjectPointerType()) &&
6899 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00006900 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6901 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00006902 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00006903 return QualType();
6904 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00006905 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006906 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006907 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6908 << PointeeTy << PExp->getSourceRange();
6909 return QualType();
6910 }
Mike Stump11289f42009-09-09 15:08:12 +00006911
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006912 if (CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00006913 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman629ffb92009-08-20 04:21:42 +00006914 if (LHSTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +00006915 LHSTy = lex.get()->getType();
Eli Friedman629ffb92009-08-20 04:21:42 +00006916 if (LHSTy->isPromotableIntegerType())
6917 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00006918 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006919 *CompLHSTy = LHSTy;
6920 }
Eli Friedman8e122982008-05-18 18:08:51 +00006921 return PExp->getType();
6922 }
6923 }
6924
Chris Lattner326f7572008-11-18 01:30:42 +00006925 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006926}
6927
Chris Lattner2a3569b2008-04-07 05:30:13 +00006928// C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00006929QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006930 SourceLocation Loc, QualType* CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00006931 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006932 QualType compType = CheckVectorOperands(Loc, lex, rex);
6933 if (CompLHSTy) *CompLHSTy = compType;
6934 return compType;
6935 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006936
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006937 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00006938 if (lex.isInvalid() || rex.isInvalid())
6939 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006940
Chris Lattner4d62f422007-12-09 21:53:25 +00006941 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006942
Chris Lattner4d62f422007-12-09 21:53:25 +00006943 // Handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00006944 if (lex.get()->getType()->isArithmeticType() &&
6945 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006946 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006947 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006948 }
Mike Stump11289f42009-09-09 15:08:12 +00006949
Chris Lattner4d62f422007-12-09 21:53:25 +00006950 // Either ptr - int or ptr - ptr.
John Wiegley01296292011-04-08 18:41:53 +00006951 if (lex.get()->getType()->isAnyPointerType()) {
6952 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006953
Douglas Gregorac1fb652009-03-24 19:52:54 +00006954 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00006955
Douglas Gregorac1fb652009-03-24 19:52:54 +00006956 bool ComplainAboutVoid = false;
6957 Expr *ComplainAboutFunc = 0;
6958 if (lpointee->isVoidType()) {
6959 if (getLangOptions().CPlusPlus) {
6960 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00006961 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006962 return QualType();
6963 }
6964
6965 // GNU C extension: arithmetic on pointer to void
6966 ComplainAboutVoid = true;
6967 } else if (lpointee->isFunctionType()) {
6968 if (getLangOptions().CPlusPlus) {
6969 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00006970 << lex.get()->getType() << lex.get()->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00006971 return QualType();
6972 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00006973
6974 // GNU C extension: arithmetic on pointer to function
John Wiegley01296292011-04-08 18:41:53 +00006975 ComplainAboutFunc = lex.get();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006976 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00006977 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00006978 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley01296292011-04-08 18:41:53 +00006979 << lex.get()->getSourceRange()
6980 << lex.get()->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00006981 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006982
Chris Lattner12bdebb2009-04-24 23:50:08 +00006983 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00006984 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00006985 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley01296292011-04-08 18:41:53 +00006986 << lpointee << lex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00006987 return QualType();
6988 }
Mike Stump11289f42009-09-09 15:08:12 +00006989
Chris Lattner4d62f422007-12-09 21:53:25 +00006990 // The result type of a pointer-int computation is the pointer type.
John Wiegley01296292011-04-08 18:41:53 +00006991 if (rex.get()->getType()->isIntegerType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00006992 if (ComplainAboutVoid)
6993 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00006994 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006995 if (ComplainAboutFunc)
6996 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00006997 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00006998 << ComplainAboutFunc->getSourceRange();
6999
John Wiegley01296292011-04-08 18:41:53 +00007000 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
7001 return lex.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007002 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007003
Chris Lattner4d62f422007-12-09 21:53:25 +00007004 // Handle pointer-pointer subtractions.
John Wiegley01296292011-04-08 18:41:53 +00007005 if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00007006 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007007
Douglas Gregorac1fb652009-03-24 19:52:54 +00007008 // RHS must be a completely-type object type.
7009 // Handle the GNU void* extension.
7010 if (rpointee->isVoidType()) {
7011 if (getLangOptions().CPlusPlus) {
7012 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00007013 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007014 return QualType();
7015 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007016
Douglas Gregorac1fb652009-03-24 19:52:54 +00007017 ComplainAboutVoid = true;
7018 } else if (rpointee->isFunctionType()) {
7019 if (getLangOptions().CPlusPlus) {
7020 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00007021 << rex.get()->getType() << rex.get()->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00007022 return QualType();
7023 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00007024
7025 // GNU extension: arithmetic on pointer to function
7026 if (!ComplainAboutFunc)
John Wiegley01296292011-04-08 18:41:53 +00007027 ComplainAboutFunc = rex.get();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007028 } else if (!rpointee->isDependentType() &&
7029 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00007030 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley01296292011-04-08 18:41:53 +00007031 << rex.get()->getSourceRange()
7032 << rex.get()->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00007033 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007034
Eli Friedman168fe152009-05-16 13:54:38 +00007035 if (getLangOptions().CPlusPlus) {
7036 // Pointee types must be the same: C++ [expr.add]
7037 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7038 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00007039 << lex.get()->getType() << rex.get()->getType()
7040 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00007041 return QualType();
7042 }
7043 } else {
7044 // Pointee types must be compatible C99 6.5.6p3
7045 if (!Context.typesAreCompatible(
7046 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7047 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7048 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00007049 << lex.get()->getType() << rex.get()->getType()
7050 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00007051 return QualType();
7052 }
Chris Lattner4d62f422007-12-09 21:53:25 +00007053 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007054
Douglas Gregorac1fb652009-03-24 19:52:54 +00007055 if (ComplainAboutVoid)
7056 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00007057 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007058 if (ComplainAboutFunc)
7059 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00007060 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00007061 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007062
John Wiegley01296292011-04-08 18:41:53 +00007063 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00007064 return Context.getPointerDiffType();
7065 }
7066 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007067
Chris Lattner326f7572008-11-18 01:30:42 +00007068 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00007069}
7070
Douglas Gregor0bf31402010-10-08 23:50:27 +00007071static bool isScopedEnumerationType(QualType T) {
7072 if (const EnumType *ET = dyn_cast<EnumType>(T))
7073 return ET->getDecl()->isScoped();
7074 return false;
7075}
7076
John Wiegley01296292011-04-08 18:41:53 +00007077static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007078 SourceLocation Loc, unsigned Opc,
7079 QualType LHSTy) {
7080 llvm::APSInt Right;
7081 // Check right/shifter operand
John Wiegley01296292011-04-08 18:41:53 +00007082 if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007083 return;
7084
7085 if (Right.isNegative()) {
John Wiegley01296292011-04-08 18:41:53 +00007086 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00007087 S.PDiag(diag::warn_shift_negative)
John Wiegley01296292011-04-08 18:41:53 +00007088 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007089 return;
7090 }
7091 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley01296292011-04-08 18:41:53 +00007092 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007093 if (Right.uge(LeftBits)) {
John Wiegley01296292011-04-08 18:41:53 +00007094 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00007095 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley01296292011-04-08 18:41:53 +00007096 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007097 return;
7098 }
7099 if (Opc != BO_Shl)
7100 return;
7101
7102 // When left shifting an ICE which is signed, we can check for overflow which
7103 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7104 // integers have defined behavior modulo one more than the maximum value
7105 // representable in the result type, so never warn for those.
7106 llvm::APSInt Left;
John Wiegley01296292011-04-08 18:41:53 +00007107 if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007108 LHSTy->hasUnsignedIntegerRepresentation())
7109 return;
7110 llvm::APInt ResultBits =
7111 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7112 if (LeftBits.uge(ResultBits))
7113 return;
7114 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7115 Result = Result.shl(Right);
7116
7117 // If we are only missing a sign bit, this is less likely to result in actual
7118 // bugs -- if the result is cast back to an unsigned type, it will have the
7119 // expected value. Thus we place this behind a different warning that can be
7120 // turned off separately if needed.
7121 if (LeftBits == ResultBits - 1) {
7122 S.Diag(Loc, diag::warn_shift_result_overrides_sign_bit)
7123 << Result.toString(10) << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00007124 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007125 return;
7126 }
7127
7128 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7129 << Result.toString(10) << Result.getMinSignedBits() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00007130 << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007131}
7132
Chris Lattner2a3569b2008-04-07 05:30:13 +00007133// C99 6.5.7
John Wiegley01296292011-04-08 18:41:53 +00007134QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007135 unsigned Opc, bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00007136 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley01296292011-04-08 18:41:53 +00007137 if (!lex.get()->getType()->hasIntegerRepresentation() ||
7138 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00007139 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007140
Douglas Gregor0bf31402010-10-08 23:50:27 +00007141 // C++0x: Don't allow scoped enums. FIXME: Use something better than
7142 // hasIntegerRepresentation() above instead of this.
John Wiegley01296292011-04-08 18:41:53 +00007143 if (isScopedEnumerationType(lex.get()->getType()) ||
7144 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00007145 return InvalidOperands(Loc, lex, rex);
7146 }
7147
Nate Begemane46ee9a2009-10-25 02:26:48 +00007148 // Vector shifts promote their scalar inputs to vector type.
John Wiegley01296292011-04-08 18:41:53 +00007149 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Nate Begemane46ee9a2009-10-25 02:26:48 +00007150 return CheckVectorOperands(Loc, lex, rex);
7151
Chris Lattner5c11c412007-12-12 05:47:28 +00007152 // Shifts don't perform usual arithmetic conversions, they just do integer
7153 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007154
John McCall57cdd882010-12-16 19:28:59 +00007155 // For the LHS, do usual unary conversions, but then reset them away
7156 // if this is a compound assignment.
John Wiegley01296292011-04-08 18:41:53 +00007157 ExprResult old_lex = lex;
7158 lex = UsualUnaryConversions(lex.take());
7159 if (lex.isInvalid())
7160 return QualType();
7161 QualType LHSTy = lex.get()->getType();
John McCall57cdd882010-12-16 19:28:59 +00007162 if (isCompAssign) lex = old_lex;
7163
7164 // The RHS is simpler.
John Wiegley01296292011-04-08 18:41:53 +00007165 rex = UsualUnaryConversions(rex.take());
7166 if (rex.isInvalid())
7167 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007168
Ryan Flynnf53fab82009-08-07 16:20:20 +00007169 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007170 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00007171
Chris Lattner5c11c412007-12-12 05:47:28 +00007172 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007173 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00007174}
7175
Chandler Carruth17773fc2010-07-10 12:30:03 +00007176static bool IsWithinTemplateSpecialization(Decl *D) {
7177 if (DeclContext *DC = D->getDeclContext()) {
7178 if (isa<ClassTemplateSpecializationDecl>(DC))
7179 return true;
7180 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7181 return FD->isFunctionTemplateSpecialization();
7182 }
7183 return false;
7184}
7185
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007186// C99 6.5.8, C++ [expr.rel]
John Wiegley01296292011-04-08 18:41:53 +00007187QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007188 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00007189 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007190
Chris Lattner9a152e22009-12-05 05:40:13 +00007191 // Handle vector comparisons separately.
John Wiegley01296292011-04-08 18:41:53 +00007192 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00007193 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007194
John Wiegley01296292011-04-08 18:41:53 +00007195 QualType lType = lex.get()->getType();
7196 QualType rType = rex.get()->getType();
Douglas Gregor1beec452011-03-12 01:48:56 +00007197
John Wiegley01296292011-04-08 18:41:53 +00007198 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
7199 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00007200 QualType LHSStrippedType = LHSStripped->getType();
7201 QualType RHSStrippedType = RHSStripped->getType();
7202
Douglas Gregor1beec452011-03-12 01:48:56 +00007203
7204
Chandler Carruth712563b2011-02-17 08:37:06 +00007205 // Two different enums will raise a warning when compared.
7206 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
7207 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
7208 if (LHSEnumType->getDecl()->getIdentifier() &&
7209 RHSEnumType->getDecl()->getIdentifier() &&
7210 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
7211 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7212 << LHSStrippedType << RHSStrippedType
John Wiegley01296292011-04-08 18:41:53 +00007213 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth712563b2011-02-17 08:37:06 +00007214 }
7215 }
7216 }
7217
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007218 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00007219 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley01296292011-04-08 18:41:53 +00007220 !lex.get()->getLocStart().isMacroID() &&
7221 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00007222 // For non-floating point types, check for self-comparisons of the form
7223 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7224 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00007225 //
7226 // NOTE: Don't warn about comparison expressions resulting from macro
7227 // expansion. Also don't warn about comparisons which are only self
7228 // comparisons within a template specialization. The warnings should catch
7229 // obvious cases in the definition of the template anyways. The idea is to
7230 // warn when the typed comparison operator will always evaluate to the same
7231 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00007232 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00007233 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00007234 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00007235 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00007236 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00007237 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00007238 << (Opc == BO_EQ
7239 || Opc == BO_LE
7240 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00007241 } else if (lType->isArrayType() && rType->isArrayType() &&
7242 !DRL->getDecl()->getType()->isReferenceType() &&
7243 !DRR->getDecl()->getType()->isReferenceType()) {
7244 // what is it always going to eval to?
7245 char always_evals_to;
7246 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00007247 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00007248 always_evals_to = 0; // false
7249 break;
John McCalle3027922010-08-25 11:45:40 +00007250 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00007251 always_evals_to = 1; // true
7252 break;
7253 default:
7254 // best we can say is 'a constant'
7255 always_evals_to = 2; // e.g. array1 <= array2
7256 break;
7257 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00007258 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00007259 << 1 // array
7260 << always_evals_to);
7261 }
7262 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00007263 }
Mike Stump11289f42009-09-09 15:08:12 +00007264
Chris Lattner222b8bd2009-03-08 19:39:53 +00007265 if (isa<CastExpr>(LHSStripped))
7266 LHSStripped = LHSStripped->IgnoreParenCasts();
7267 if (isa<CastExpr>(RHSStripped))
7268 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00007269
Chris Lattner222b8bd2009-03-08 19:39:53 +00007270 // Warn about comparisons against a string constant (unless the other
7271 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007272 Expr *literalString = 0;
7273 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00007274 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007275 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007276 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00007277 literalString = lex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007278 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00007279 } else if ((isa<StringLiteral>(RHSStripped) ||
7280 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007281 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007282 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00007283 literalString = rex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007284 literalStringStripped = RHSStripped;
7285 }
7286
7287 if (literalString) {
7288 std::string resultComparison;
7289 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007290 case BO_LT: resultComparison = ") < 0"; break;
7291 case BO_GT: resultComparison = ") > 0"; break;
7292 case BO_LE: resultComparison = ") <= 0"; break;
7293 case BO_GE: resultComparison = ") >= 0"; break;
7294 case BO_EQ: resultComparison = ") == 0"; break;
7295 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007296 default: assert(false && "Invalid comparison operator");
7297 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007298
Ted Kremenek3427fac2011-02-23 01:52:04 +00007299 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00007300 PDiag(diag::warn_stringcompare)
7301 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00007302 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007303 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00007304 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007305
Douglas Gregorec170db2010-06-08 19:50:34 +00007306 // C99 6.5.8p3 / C99 6.5.9p4
John Wiegley01296292011-04-08 18:41:53 +00007307 if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
Douglas Gregorec170db2010-06-08 19:50:34 +00007308 UsualArithmeticConversions(lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00007309 if (lex.isInvalid() || rex.isInvalid())
7310 return QualType();
7311 }
Douglas Gregorec170db2010-06-08 19:50:34 +00007312 else {
John Wiegley01296292011-04-08 18:41:53 +00007313 lex = UsualUnaryConversions(lex.take());
7314 if (lex.isInvalid())
7315 return QualType();
7316
7317 rex = UsualUnaryConversions(rex.take());
7318 if (rex.isInvalid())
7319 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007320 }
7321
John Wiegley01296292011-04-08 18:41:53 +00007322 lType = lex.get()->getType();
7323 rType = rex.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007324
Douglas Gregorca63811b2008-11-19 03:25:36 +00007325 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007326 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00007327
Chris Lattnerb620c342007-08-26 01:18:55 +00007328 if (isRelational) {
7329 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007330 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007331 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00007332 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007333 if (lType->hasFloatingRepresentation())
John Wiegley01296292011-04-08 18:41:53 +00007334 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007335
Chris Lattnerb620c342007-08-26 01:18:55 +00007336 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007337 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007338 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007339
John Wiegley01296292011-04-08 18:41:53 +00007340 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007341 Expr::NPC_ValueDependentIsNull);
John Wiegley01296292011-04-08 18:41:53 +00007342 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007343 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007344
Douglas Gregorf267edd2010-06-15 21:38:40 +00007345 // All of the following pointer-related warnings are GCC extensions, except
7346 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00007347 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00007348 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007349 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00007350 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007351 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007352
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007353 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00007354 if (LCanPointeeTy == RCanPointeeTy)
7355 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007356 if (!isRelational &&
7357 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7358 // Valid unless comparison between non-null pointer and function pointer
7359 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00007360 // In a SFINAE context, we treat this as a hard error to maintain
7361 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007362 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7363 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00007364 Diag(Loc,
7365 isSFINAEContext()?
7366 diag::err_typecheck_comparison_of_fptr_to_void
7367 : diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00007368 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007369
7370 if (isSFINAEContext())
7371 return QualType();
7372
John Wiegley01296292011-04-08 18:41:53 +00007373 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007374 return ResultTy;
7375 }
7376 }
Anders Carlssona95069c2010-11-04 03:17:43 +00007377
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007378 // C++ [expr.rel]p2:
7379 // [...] Pointer conversions (4.10) and qualification
7380 // conversions (4.4) are performed on pointer operands (or on
7381 // a pointer operand and a null pointer constant) to bring
7382 // them to their composite pointer type. [...]
7383 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007384 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007385 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007386 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007387 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007388 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007389 if (T.isNull()) {
7390 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007391 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007392 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007393 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007394 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007395 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007396 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00007397 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007398 }
7399
John Wiegley01296292011-04-08 18:41:53 +00007400 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7401 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007402 return ResultTy;
7403 }
Eli Friedman16c209612009-08-23 00:27:47 +00007404 // C99 6.5.9p2 and C99 6.5.8p2
7405 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7406 RCanPointeeTy.getUnqualifiedType())) {
7407 // Valid unless a relational comparison of function pointers
7408 if (isRelational && LCanPointeeTy->isFunctionType()) {
7409 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007410 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007411 }
7412 } else if (!isRelational &&
7413 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7414 // Valid unless comparison between non-null pointer and function pointer
7415 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7416 && !LHSIsNull && !RHSIsNull) {
7417 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00007418 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007419 }
7420 } else {
7421 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00007422 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007423 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00007424 }
John McCall7684dde2011-03-11 04:25:25 +00007425 if (LCanPointeeTy != RCanPointeeTy) {
7426 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007427 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007428 else
John Wiegley01296292011-04-08 18:41:53 +00007429 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007430 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00007431 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00007432 }
Mike Stump11289f42009-09-09 15:08:12 +00007433
Sebastian Redl576fd422009-05-10 18:38:11 +00007434 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00007435 // Comparison of nullptr_t with itself.
7436 if (lType->isNullPtrType() && rType->isNullPtrType())
7437 return ResultTy;
7438
Mike Stump11289f42009-09-09 15:08:12 +00007439 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007440 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00007441 if (RHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00007442 ((lType->isPointerType() || lType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007443 (!isRelational && lType->isMemberPointerType()))) {
John Wiegley01296292011-04-08 18:41:53 +00007444 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00007445 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007446 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007447 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007448 return ResultTy;
7449 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007450 if (LHSIsNull &&
Anders Carlssona95069c2010-11-04 03:17:43 +00007451 ((rType->isPointerType() || rType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007452 (!isRelational && rType->isMemberPointerType()))) {
John Wiegley01296292011-04-08 18:41:53 +00007453 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00007454 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007455 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007456 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007457 return ResultTy;
7458 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007459
7460 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00007461 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007462 lType->isMemberPointerType() && rType->isMemberPointerType()) {
7463 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00007464 // In addition, pointers to members can be compared, or a pointer to
7465 // member and a null pointer constant. Pointer to member conversions
7466 // (4.11) and qualification conversions (4.4) are performed to bring
7467 // them to a common type. If one operand is a null pointer constant,
7468 // the common type is the type of the other operand. Otherwise, the
7469 // common type is a pointer to member type similar (4.4) to the type
7470 // of one of the operands, with a cv-qualification signature (4.4)
7471 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007472 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007473 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007474 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007475 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007476 if (T.isNull()) {
7477 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007478 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007479 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007480 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007481 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007482 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007483 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00007484 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007485 }
Mike Stump11289f42009-09-09 15:08:12 +00007486
John Wiegley01296292011-04-08 18:41:53 +00007487 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7488 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007489 return ResultTy;
7490 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007491
7492 // Handle scoped enumeration types specifically, since they don't promote
7493 // to integers.
John Wiegley01296292011-04-08 18:41:53 +00007494 if (lex.get()->getType()->isEnumeralType() &&
7495 Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007496 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00007497 }
Mike Stump11289f42009-09-09 15:08:12 +00007498
Steve Naroff081c7422008-09-04 15:10:53 +00007499 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00007500 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007501 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7502 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007503
Steve Naroff081c7422008-09-04 15:10:53 +00007504 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007505 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007506 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00007507 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007508 }
John Wiegley01296292011-04-08 18:41:53 +00007509 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007510 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007511 }
John Wiegley01296292011-04-08 18:41:53 +00007512
Steve Naroffe18f94c2008-09-28 01:11:11 +00007513 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00007514 if (!isRelational
7515 && ((lType->isBlockPointerType() && rType->isPointerType())
7516 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007517 if (!LHSIsNull && !RHSIsNull) {
John McCall7684dde2011-03-11 04:25:25 +00007518 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007519 ->getPointeeType()->isVoidType())
John McCall7684dde2011-03-11 04:25:25 +00007520 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007521 ->getPointeeType()->isVoidType())))
7522 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00007523 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007524 }
John McCall7684dde2011-03-11 04:25:25 +00007525 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007526 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007527 else
John Wiegley01296292011-04-08 18:41:53 +00007528 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007529 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007530 }
Steve Naroff081c7422008-09-04 15:10:53 +00007531
John McCall7684dde2011-03-11 04:25:25 +00007532 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
7533 const PointerType *LPT = lType->getAs<PointerType>();
7534 const PointerType *RPT = rType->getAs<PointerType>();
7535 if (LPT || RPT) {
7536 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7537 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007538
Steve Naroff753567f2008-11-17 19:49:16 +00007539 if (!LPtrToVoid && !RPtrToVoid &&
7540 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007541 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007542 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007543 }
John McCall7684dde2011-03-11 04:25:25 +00007544 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007545 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007546 else
John Wiegley01296292011-04-08 18:41:53 +00007547 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007548 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007549 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007550 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007551 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007552 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007553 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
John McCall7684dde2011-03-11 04:25:25 +00007554 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007555 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007556 else
John Wiegley01296292011-04-08 18:41:53 +00007557 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007558 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007559 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007560 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007561 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7562 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007563 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007564 bool isError = false;
7565 if ((LHSIsNull && lType->isIntegerType()) ||
7566 (RHSIsNull && rType->isIntegerType())) {
7567 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007568 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007569 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007570 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007571 else if (getLangOptions().CPlusPlus) {
7572 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7573 isError = true;
7574 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007575 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007576
Chris Lattnerd99bd522009-08-23 00:03:44 +00007577 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007578 Diag(Loc, DiagID)
John Wiegley01296292011-04-08 18:41:53 +00007579 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007580 if (isError)
7581 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007582 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007583
7584 if (lType->isIntegerType())
John Wiegley01296292011-04-08 18:41:53 +00007585 lex = ImpCastExprToType(lex.take(), rType,
John McCalle84af4e2010-11-13 01:35:44 +00007586 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007587 else
John Wiegley01296292011-04-08 18:41:53 +00007588 rex = ImpCastExprToType(rex.take(), lType,
John McCalle84af4e2010-11-13 01:35:44 +00007589 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007590 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007591 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007592
Steve Naroff4b191572008-09-04 16:56:14 +00007593 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00007594 if (!isRelational && RHSIsNull
7595 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley01296292011-04-08 18:41:53 +00007596 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007597 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007598 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00007599 if (!isRelational && LHSIsNull
7600 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley01296292011-04-08 18:41:53 +00007601 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007602 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007603 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007604
Chris Lattner326f7572008-11-18 01:30:42 +00007605 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007606}
7607
Nate Begeman191a6b12008-07-14 18:02:46 +00007608/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007609/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007610/// like a scalar comparison, a vector comparison produces a vector of integer
7611/// types.
John Wiegley01296292011-04-08 18:41:53 +00007612QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner326f7572008-11-18 01:30:42 +00007613 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00007614 bool isRelational) {
7615 // Check to make sure we're operating on vectors of the same type and width,
7616 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00007617 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00007618 if (vType.isNull())
7619 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007620
John Wiegley01296292011-04-08 18:41:53 +00007621 QualType lType = lex.get()->getType();
7622 QualType rType = rex.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007623
Anton Yartsev530deb92011-03-27 15:36:07 +00007624 // If AltiVec, the comparison results in a numeric type, i.e.
7625 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00007626 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00007627 return Context.getLogicalOperationType();
7628
Nate Begeman191a6b12008-07-14 18:02:46 +00007629 // For non-floating point types, check for self-comparisons of the form
7630 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7631 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007632 if (!lType->hasFloatingRepresentation()) {
John Wiegley01296292011-04-08 18:41:53 +00007633 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
7634 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00007635 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007636 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007637 PDiag(diag::warn_comparison_always)
7638 << 0 // self-
7639 << 2 // "a constant"
7640 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007641 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007642
Nate Begeman191a6b12008-07-14 18:02:46 +00007643 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007644 if (!isRelational && lType->hasFloatingRepresentation()) {
7645 assert (rType->hasFloatingRepresentation());
John Wiegley01296292011-04-08 18:41:53 +00007646 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00007647 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007648
Nate Begeman191a6b12008-07-14 18:02:46 +00007649 // Return the type for the comparison, which is the same as vector type for
7650 // integer vectors, or an integer type of identical size and number of
7651 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007652 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00007653 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007654
John McCall9dd450b2009-09-21 23:43:11 +00007655 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00007656 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007657 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00007658 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00007659 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007660 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7661
Mike Stump4e1f26a2009-02-19 03:04:26 +00007662 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007663 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00007664 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7665}
7666
Steve Naroff218bc2b2007-05-04 21:54:46 +00007667inline QualType Sema::CheckBitwiseOperands(
John Wiegley01296292011-04-08 18:41:53 +00007668 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
7669 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
7670 if (lex.get()->getType()->hasIntegerRepresentation() &&
7671 rex.get()->getType()->hasIntegerRepresentation())
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007672 return CheckVectorOperands(Loc, lex, rex);
7673
7674 return InvalidOperands(Loc, lex, rex);
7675 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007676
John Wiegley01296292011-04-08 18:41:53 +00007677 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
7678 QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
7679 if (lexResult.isInvalid() || rexResult.isInvalid())
7680 return QualType();
7681 lex = lexResult.take();
7682 rex = rexResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007683
John Wiegley01296292011-04-08 18:41:53 +00007684 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
7685 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007686 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00007687 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007688}
7689
Steve Naroff218bc2b2007-05-04 21:54:46 +00007690inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley01296292011-04-08 18:41:53 +00007691 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00007692
7693 // Diagnose cases where the user write a logical and/or but probably meant a
7694 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7695 // is a constant.
John Wiegley01296292011-04-08 18:41:53 +00007696 if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
7697 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00007698 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00007699 !Loc.isMacroID()) {
7700 // If the RHS can be constant folded, and if it constant folds to something
7701 // that isn't 0 or 1 (which indicate a potential logical operation that
7702 // happened to fold to true/false) then warn.
7703 Expr::EvalResult Result;
John Wiegley01296292011-04-08 18:41:53 +00007704 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects &&
Chris Lattner938533d2010-07-24 01:10:11 +00007705 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7706 Diag(Loc, diag::warn_logical_instead_of_bitwise)
John Wiegley01296292011-04-08 18:41:53 +00007707 << rex.get()->getSourceRange()
John McCalle3027922010-08-25 11:45:40 +00007708 << (Opc == BO_LAnd ? "&&" : "||")
7709 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00007710 }
7711 }
Chris Lattner8406c512010-07-13 19:41:32 +00007712
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007713 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007714 lex = UsualUnaryConversions(lex.take());
7715 if (lex.isInvalid())
7716 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007717
John Wiegley01296292011-04-08 18:41:53 +00007718 rex = UsualUnaryConversions(rex.take());
7719 if (rex.isInvalid())
7720 return QualType();
7721
7722 if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007723 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007724
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007725 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007726 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007727
John McCall4a2429a2010-06-04 00:29:51 +00007728 // The following is safe because we only use this method for
7729 // non-overloadable operands.
7730
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007731 // C++ [expr.log.and]p1
7732 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007733 // The operands are both contextually converted to type bool.
John Wiegley01296292011-04-08 18:41:53 +00007734 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
7735 if (lexRes.isInvalid())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007736 return InvalidOperands(Loc, lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00007737 lex = move(lexRes);
7738
7739 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
7740 if (rexRes.isInvalid())
7741 return InvalidOperands(Loc, lex, rex);
7742 rex = move(rexRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007743
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007744 // C++ [expr.log.and]p2
7745 // C++ [expr.log.or]p2
7746 // The result is a bool.
7747 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007748}
7749
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007750/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7751/// is a read-only property; return true if so. A readonly property expression
7752/// depends on various declarations and thus must be treated specially.
7753///
Mike Stump11289f42009-09-09 15:08:12 +00007754static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007755 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7756 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00007757 if (PropExpr->isImplicitProperty()) return false;
7758
7759 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7760 QualType BaseType = PropExpr->isSuperReceiver() ?
7761 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007762 PropExpr->getBase()->getType();
7763
John McCallb7bd14f2010-12-02 01:19:52 +00007764 if (const ObjCObjectPointerType *OPT =
7765 BaseType->getAsObjCInterfacePointerType())
7766 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7767 if (S.isPropertyReadonly(PDecl, IFace))
7768 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007769 }
7770 return false;
7771}
7772
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007773static bool IsConstProperty(Expr *E, Sema &S) {
7774 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7775 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
7776 if (PropExpr->isImplicitProperty()) return false;
7777
7778 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7779 QualType T = PDecl->getType();
7780 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00007781 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007782 CanQualType CT = S.Context.getCanonicalType(T);
7783 return CT.isConstQualified();
7784 }
7785 return false;
7786}
7787
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007788static bool IsReadonlyMessage(Expr *E, Sema &S) {
7789 if (E->getStmtClass() != Expr::MemberExprClass)
7790 return false;
7791 const MemberExpr *ME = cast<MemberExpr>(E);
7792 NamedDecl *Member = ME->getMemberDecl();
7793 if (isa<FieldDecl>(Member)) {
7794 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
7795 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
7796 return false;
7797 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
7798 }
7799 return false;
7800}
7801
Chris Lattner30bd3272008-11-18 01:22:49 +00007802/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7803/// emit an error and return true. If so, return false.
7804static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007805 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007806 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007807 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007808 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7809 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007810 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7811 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007812 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7813 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007814 if (IsLV == Expr::MLV_Valid)
7815 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007816
Chris Lattner30bd3272008-11-18 01:22:49 +00007817 unsigned Diag = 0;
7818 bool NeedType = false;
7819 switch (IsLV) { // C99 6.5.16p2
Chris Lattner30bd3272008-11-18 01:22:49 +00007820 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007821 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007822 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7823 NeedType = true;
7824 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007825 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007826 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7827 NeedType = true;
7828 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007829 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007830 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7831 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007832 case Expr::MLV_Valid:
7833 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007834 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007835 case Expr::MLV_MemberFunction:
7836 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007837 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7838 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007839 case Expr::MLV_IncompleteType:
7840 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007841 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007842 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00007843 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00007844 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007845 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7846 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00007847 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00007848 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7849 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007850 case Expr::MLV_ReadonlyProperty:
7851 Diag = diag::error_readonly_property_assignment;
7852 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007853 case Expr::MLV_NoSetterProperty:
7854 Diag = diag::error_nosetter_property_assignment;
7855 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007856 case Expr::MLV_InvalidMessageExpression:
7857 Diag = diag::error_readonly_message_assignment;
7858 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007859 case Expr::MLV_SubObjCPropertySetting:
7860 Diag = diag::error_no_subobject_property_setting;
7861 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007862 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007863
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007864 SourceRange Assign;
7865 if (Loc != OrigLoc)
7866 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007867 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007868 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007869 else
Mike Stump11289f42009-09-09 15:08:12 +00007870 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007871 return true;
7872}
7873
7874
7875
7876// C99 6.5.16.1
John Wiegley01296292011-04-08 18:41:53 +00007877QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007878 SourceLocation Loc,
7879 QualType CompoundType) {
7880 // Verify that LHS is a modifiable lvalue, and emit error if not.
7881 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007882 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007883
7884 QualType LHSType = LHS->getType();
John Wiegley01296292011-04-08 18:41:53 +00007885 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007886 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007887 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007888 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007889 // Simple assignment "x = y".
John Wiegley01296292011-04-08 18:41:53 +00007890 if (LHS->getObjectKind() == OK_ObjCProperty) {
7891 ExprResult LHSResult = Owned(LHS);
7892 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7893 if (LHSResult.isInvalid())
7894 return QualType();
7895 LHS = LHSResult.take();
7896 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007897 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007898 if (RHS.isInvalid())
7899 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007900 // Special case of NSObject attributes on c-style pointer types.
7901 if (ConvTy == IncompatiblePointer &&
7902 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007903 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007904 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007905 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007906 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007907
John McCall7decc9e2010-11-18 06:31:45 +00007908 if (ConvTy == Compatible &&
7909 getLangOptions().ObjCNonFragileABI &&
7910 LHSType->isObjCObjectType())
7911 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7912 << LHSType;
7913
Chris Lattnerea714382008-08-21 18:04:13 +00007914 // If the RHS is a unary plus or minus, check to see if they = and + are
7915 // right next to each other. If so, the user may have typo'd "x =+ 4"
7916 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00007917 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00007918 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7919 RHSCheck = ICE->getSubExpr();
7920 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007921 if ((UO->getOpcode() == UO_Plus ||
7922 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007923 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007924 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00007925 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7926 // And there is a space or other character before the subexpr of the
7927 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00007928 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7929 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007930 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007931 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007932 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007933 }
Chris Lattnerea714382008-08-21 18:04:13 +00007934 }
7935 } else {
7936 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007937 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007938 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007939
Chris Lattner326f7572008-11-18 01:30:42 +00007940 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007941 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007942 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007943
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +00007944 CheckForNullPointerDereference(*this, LHS);
Ted Kremenek64699be2011-02-16 01:57:07 +00007945 // Check for trivial buffer overflows.
Ted Kremenekdf26df72011-03-01 18:41:00 +00007946 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremenek64699be2011-02-16 01:57:07 +00007947
Steve Naroff98cf3e92007-06-06 18:38:38 +00007948 // C99 6.5.16p3: The type of an assignment expression is the type of the
7949 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007950 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007951 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7952 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007953 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007954 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007955 return (getLangOptions().CPlusPlus
7956 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007957}
7958
Chris Lattner326f7572008-11-18 01:30:42 +00007959// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007960static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007961 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00007962 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007963
John McCall3aef3d82011-04-10 19:13:55 +00007964 LHS = S.CheckPlaceholderExpr(LHS.take());
7965 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007966 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007967 return QualType();
7968
John McCall73d36182010-10-12 07:14:40 +00007969 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7970 // operands, but not unary promotions.
7971 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007972
John McCall34376a62010-12-04 03:47:34 +00007973 // So we treat the LHS as a ignored value, and in C++ we allow the
7974 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007975 LHS = S.IgnoredValueConversions(LHS.take());
7976 if (LHS.isInvalid())
7977 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007978
7979 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007980 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7981 if (RHS.isInvalid())
7982 return QualType();
7983 if (!RHS.get()->getType()->isVoidType())
7984 S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007985 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007986
John Wiegley01296292011-04-08 18:41:53 +00007987 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007988}
7989
Steve Naroff7a5af782007-07-13 16:58:59 +00007990/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7991/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007992static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7993 ExprValueKind &VK,
7994 SourceLocation OpLoc,
7995 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007996 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007997 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007998
Chris Lattner6b0cf142008-11-21 07:05:48 +00007999 QualType ResType = Op->getType();
8000 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00008001
John McCall4bc41ae2010-11-18 19:01:18 +00008002 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00008003 // Decrement of bool is not allowed.
8004 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00008005 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00008006 return QualType();
8007 }
8008 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00008009 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00008010 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00008011 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00008012 } else if (ResType->isAnyPointerType()) {
8013 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00008014
Chris Lattner6b0cf142008-11-21 07:05:48 +00008015 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00008016 if (PointeeTy->isVoidType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008017 if (S.getLangOptions().CPlusPlus) {
8018 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00008019 << Op->getSourceRange();
8020 return QualType();
8021 }
8022
8023 // Pointer to void is a GNU extension in C.
John McCall4bc41ae2010-11-18 19:01:18 +00008024 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00008025 } else if (PointeeTy->isFunctionType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008026 if (S.getLangOptions().CPlusPlus) {
8027 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00008028 << Op->getType() << Op->getSourceRange();
8029 return QualType();
8030 }
8031
John McCall4bc41ae2010-11-18 19:01:18 +00008032 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008033 << ResType << Op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00008034 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
8035 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00008036 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00008037 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00008038 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00008039 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00008040 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
8041 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00008042 << PointeeTy << Op->getSourceRange();
8043 return QualType();
8044 }
Eli Friedman090addd2010-01-03 00:20:48 +00008045 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00008046 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00008047 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008048 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008049 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008050 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00008051 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008052 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8053 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00008054 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
8055 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00008056 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00008057 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00008058 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00008059 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00008060 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008061 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00008062 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00008063 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00008064 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00008065 // In C++, a prefix increment is the same type as the operand. Otherwise
8066 // (in C or with postfix), the increment is the unqualified type of the
8067 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00008068 if (isPrefix && S.getLangOptions().CPlusPlus) {
8069 VK = VK_LValue;
8070 return ResType;
8071 } else {
8072 VK = VK_RValue;
8073 return ResType.getUnqualifiedType();
8074 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00008075}
8076
John Wiegley01296292011-04-08 18:41:53 +00008077ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00008078 assert(E->getValueKind() == VK_LValue &&
8079 E->getObjectKind() == OK_ObjCProperty);
8080 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
8081
8082 ExprValueKind VK = VK_RValue;
8083 if (PRE->isImplicitProperty()) {
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00008084 if (const ObjCMethodDecl *GetterMethod =
8085 PRE->getImplicitPropertyGetter()) {
8086 QualType Result = GetterMethod->getResultType();
8087 VK = Expr::getValueKindForType(Result);
8088 }
8089 else {
8090 Diag(PRE->getLocation(), diag::err_getter_not_found)
8091 << PRE->getBase()->getType();
8092 }
John McCall34376a62010-12-04 03:47:34 +00008093 }
8094
8095 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
8096 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00008097
8098 ExprResult Result = MaybeBindToTemporary(E);
8099 if (!Result.isInvalid())
8100 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00008101
8102 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00008103}
8104
John Wiegley01296292011-04-08 18:41:53 +00008105void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
8106 assert(LHS.get()->getValueKind() == VK_LValue &&
8107 LHS.get()->getObjectKind() == OK_ObjCProperty);
8108 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00008109
John Wiegley01296292011-04-08 18:41:53 +00008110 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00008111 // If using property-dot syntax notation for assignment, and there is a
8112 // setter, RHS expression is being passed to the setter argument. So,
8113 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00008114 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00008115 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
8116 LHSTy = (*P)->getType();
8117
8118 // Otherwise, if the getter returns an l-value, just call that.
8119 } else {
John Wiegley01296292011-04-08 18:41:53 +00008120 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00008121 ExprValueKind VK = Expr::getValueKindForType(Result);
8122 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00008123 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
8124 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00008125 return;
John McCallb7bd14f2010-12-02 01:19:52 +00008126 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008127 }
John McCall34376a62010-12-04 03:47:34 +00008128 }
8129
8130 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008131 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008132 InitializedEntity::InitializeParameter(Context, LHSTy);
John Wiegley01296292011-04-08 18:41:53 +00008133 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008134 if (!ArgE.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00008135 RHS = ArgE;
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008136 }
8137}
8138
8139
Anders Carlsson806700f2008-02-01 07:15:58 +00008140/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00008141/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008142/// where the declaration is needed for type checking. We only need to
8143/// handle cases when the expression references a function designator
8144/// or is an lvalue. Here are some examples:
8145/// - &(x) => x
8146/// - &*****f => f for f a function designator.
8147/// - &s.xx => s
8148/// - &s.zz[1].yy -> s, if zz is an array
8149/// - *(x + 1) -> x, if x is an array
8150/// - &"123"[2] -> 0
8151/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00008152static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008153 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00008154 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008155 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00008156 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00008157 // If this is an arrow operator, the address is an offset from
8158 // the base's value, so the object the base refers to is
8159 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008160 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00008161 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00008162 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008163 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00008164 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00008165 // FIXME: This code shouldn't be necessary! We should catch the implicit
8166 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00008167 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8168 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8169 if (ICE->getSubExpr()->getType()->isArrayType())
8170 return getPrimaryDecl(ICE->getSubExpr());
8171 }
8172 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00008173 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008174 case Stmt::UnaryOperatorClass: {
8175 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008176
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008177 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008178 case UO_Real:
8179 case UO_Imag:
8180 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008181 return getPrimaryDecl(UO->getSubExpr());
8182 default:
8183 return 0;
8184 }
8185 }
Steve Naroff47500512007-04-19 23:00:49 +00008186 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008187 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00008188 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00008189 // If the result of an implicit cast is an l-value, we care about
8190 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008191 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00008192 default:
8193 return 0;
8194 }
8195}
8196
8197/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00008198/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00008199/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008200/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00008201/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008202/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00008203/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00008204static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
8205 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00008206 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008207 return S.Context.DependentTy;
8208 if (OrigOp->getType() == S.Context.OverloadTy)
8209 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00008210 if (OrigOp->getType() == S.Context.UnknownAnyTy)
8211 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00008212 if (OrigOp->getType() == S.Context.BoundMemberTy) {
8213 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8214 << OrigOp->getSourceRange();
8215 return QualType();
8216 }
John McCall8d08b9b2010-08-27 09:08:28 +00008217
John McCall2979fe02011-04-12 00:42:48 +00008218 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00008219
John McCall8d08b9b2010-08-27 09:08:28 +00008220 // Make sure to ignore parentheses in subsequent checks
8221 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00008222
John McCall4bc41ae2010-11-18 19:01:18 +00008223 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00008224 // Implement C99-only parts of addressof rules.
8225 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00008226 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00008227 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8228 // (assuming the deref expression is valid).
8229 return uOp->getSubExpr()->getType();
8230 }
8231 // Technically, there should be a check for array subscript
8232 // expressions here, but the result of one is always an lvalue anyway.
8233 }
John McCallf3a88602011-02-03 08:15:49 +00008234 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00008235 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00008236
Fariborz Jahanian071caef2011-03-26 19:48:30 +00008237 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00008238 bool sfinae = S.isSFINAEContext();
8239 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8240 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008241 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00008242 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008243 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00008244 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008245 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00008246 } else if (lval == Expr::LV_MemberFunction) {
8247 // If it's an instance method, make a member pointer.
8248 // The expression must have exactly the form &A::foo.
8249
8250 // If the underlying expression isn't a decl ref, give up.
8251 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008252 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008253 << OrigOp->getSourceRange();
8254 return QualType();
8255 }
8256 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8257 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8258
8259 // The id-expression was parenthesized.
8260 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00008261 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008262 << OrigOp->getSourceRange();
8263
8264 // The method was named without a qualifier.
8265 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008266 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008267 << op->getSourceRange();
8268 }
8269
John McCall4bc41ae2010-11-18 19:01:18 +00008270 return S.Context.getMemberPointerType(op->getType(),
8271 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00008272 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00008273 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008274 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00008275 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00008276 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00008277 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00008278 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00008279 return QualType();
8280 }
John McCall086a4642010-11-24 05:12:34 +00008281 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008282 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00008283 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00008284 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00008285 return QualType();
John McCall086a4642010-11-24 05:12:34 +00008286 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00008287 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00008288 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00008289 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008290 return QualType();
John McCall086a4642010-11-24 05:12:34 +00008291 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00008292 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00008293 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00008294 << "property expression" << op->getSourceRange();
8295 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008296 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00008297 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00008298 // with the register storage-class specifier.
8299 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00008300 // in C++ it is not error to take address of a register
8301 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00008302 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00008303 !S.getLangOptions().CPlusPlus) {
8304 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00008305 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00008306 return QualType();
8307 }
John McCalld14a8642009-11-21 08:51:07 +00008308 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008309 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00008310 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00008311 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008312 // Could be a pointer to member, though, if there is an explicit
8313 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00008314 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008315 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008316 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00008317 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008318 S.Diag(OpLoc,
8319 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00008320 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008321 return QualType();
8322 }
Mike Stump11289f42009-09-09 15:08:12 +00008323
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00008324 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8325 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00008326 return S.Context.getMemberPointerType(op->getType(),
8327 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00008328 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008329 }
Anders Carlsson5b535762009-05-16 21:43:42 +00008330 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00008331 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00008332 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008333
Eli Friedmance7f9002009-05-16 23:27:50 +00008334 if (lval == Expr::LV_IncompleteVoidType) {
8335 // Taking the address of a void variable is technically illegal, but we
8336 // allow it in cases which are otherwise valid.
8337 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00008338 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00008339 }
8340
Steve Naroff47500512007-04-19 23:00:49 +00008341 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00008342 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00008343 return S.Context.getObjCObjectPointerType(op->getType());
8344 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00008345}
8346
Chris Lattner9156f1b2010-07-05 19:17:26 +00008347/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00008348static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8349 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008350 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008351 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008352
John Wiegley01296292011-04-08 18:41:53 +00008353 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8354 if (ConvResult.isInvalid())
8355 return QualType();
8356 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00008357 QualType OpTy = Op->getType();
8358 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00008359
8360 if (isa<CXXReinterpretCastExpr>(Op)) {
8361 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8362 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8363 Op->getSourceRange());
8364 }
8365
Chris Lattner9156f1b2010-07-05 19:17:26 +00008366 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8367 // is an incomplete type or void. It would be possible to warn about
8368 // dereferencing a void pointer, but it's completely well-defined, and such a
8369 // warning is unlikely to catch any mistakes.
8370 if (const PointerType *PT = OpTy->getAs<PointerType>())
8371 Result = PT->getPointeeType();
8372 else if (const ObjCObjectPointerType *OPT =
8373 OpTy->getAs<ObjCObjectPointerType>())
8374 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00008375 else {
John McCall3aef3d82011-04-10 19:13:55 +00008376 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00008377 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008378 if (PR.take() != Op)
8379 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00008380 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008381
Chris Lattner9156f1b2010-07-05 19:17:26 +00008382 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008383 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00008384 << OpTy << Op->getSourceRange();
8385 return QualType();
8386 }
John McCall4bc41ae2010-11-18 19:01:18 +00008387
8388 // Dereferences are usually l-values...
8389 VK = VK_LValue;
8390
8391 // ...except that certain expressions are never l-values in C.
8392 if (!S.getLangOptions().CPlusPlus &&
8393 IsCForbiddenLValueType(S.Context, Result))
8394 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00008395
8396 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00008397}
Steve Naroff218bc2b2007-05-04 21:54:46 +00008398
John McCalle3027922010-08-25 11:45:40 +00008399static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00008400 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008401 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008402 switch (Kind) {
8403 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00008404 case tok::periodstar: Opc = BO_PtrMemD; break;
8405 case tok::arrowstar: Opc = BO_PtrMemI; break;
8406 case tok::star: Opc = BO_Mul; break;
8407 case tok::slash: Opc = BO_Div; break;
8408 case tok::percent: Opc = BO_Rem; break;
8409 case tok::plus: Opc = BO_Add; break;
8410 case tok::minus: Opc = BO_Sub; break;
8411 case tok::lessless: Opc = BO_Shl; break;
8412 case tok::greatergreater: Opc = BO_Shr; break;
8413 case tok::lessequal: Opc = BO_LE; break;
8414 case tok::less: Opc = BO_LT; break;
8415 case tok::greaterequal: Opc = BO_GE; break;
8416 case tok::greater: Opc = BO_GT; break;
8417 case tok::exclaimequal: Opc = BO_NE; break;
8418 case tok::equalequal: Opc = BO_EQ; break;
8419 case tok::amp: Opc = BO_And; break;
8420 case tok::caret: Opc = BO_Xor; break;
8421 case tok::pipe: Opc = BO_Or; break;
8422 case tok::ampamp: Opc = BO_LAnd; break;
8423 case tok::pipepipe: Opc = BO_LOr; break;
8424 case tok::equal: Opc = BO_Assign; break;
8425 case tok::starequal: Opc = BO_MulAssign; break;
8426 case tok::slashequal: Opc = BO_DivAssign; break;
8427 case tok::percentequal: Opc = BO_RemAssign; break;
8428 case tok::plusequal: Opc = BO_AddAssign; break;
8429 case tok::minusequal: Opc = BO_SubAssign; break;
8430 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8431 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8432 case tok::ampequal: Opc = BO_AndAssign; break;
8433 case tok::caretequal: Opc = BO_XorAssign; break;
8434 case tok::pipeequal: Opc = BO_OrAssign; break;
8435 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008436 }
8437 return Opc;
8438}
8439
John McCalle3027922010-08-25 11:45:40 +00008440static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00008441 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008442 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00008443 switch (Kind) {
8444 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00008445 case tok::plusplus: Opc = UO_PreInc; break;
8446 case tok::minusminus: Opc = UO_PreDec; break;
8447 case tok::amp: Opc = UO_AddrOf; break;
8448 case tok::star: Opc = UO_Deref; break;
8449 case tok::plus: Opc = UO_Plus; break;
8450 case tok::minus: Opc = UO_Minus; break;
8451 case tok::tilde: Opc = UO_Not; break;
8452 case tok::exclaim: Opc = UO_LNot; break;
8453 case tok::kw___real: Opc = UO_Real; break;
8454 case tok::kw___imag: Opc = UO_Imag; break;
8455 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00008456 }
8457 return Opc;
8458}
8459
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008460/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8461/// This warning is only emitted for builtin assignment operations. It is also
8462/// suppressed in the event of macro expansions.
8463static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
8464 SourceLocation OpLoc) {
8465 if (!S.ActiveTemplateInstantiations.empty())
8466 return;
8467 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8468 return;
8469 lhs = lhs->IgnoreParenImpCasts();
8470 rhs = rhs->IgnoreParenImpCasts();
8471 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
8472 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
8473 if (!LeftDeclRef || !RightDeclRef ||
8474 LeftDeclRef->getLocation().isMacroID() ||
8475 RightDeclRef->getLocation().isMacroID())
8476 return;
8477 const ValueDecl *LeftDecl =
8478 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
8479 const ValueDecl *RightDecl =
8480 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
8481 if (LeftDecl != RightDecl)
8482 return;
8483 if (LeftDecl->getType().isVolatileQualified())
8484 return;
8485 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
8486 if (RefTy->getPointeeType().isVolatileQualified())
8487 return;
8488
8489 S.Diag(OpLoc, diag::warn_self_assignment)
8490 << LeftDeclRef->getType()
8491 << lhs->getSourceRange() << rhs->getSourceRange();
8492}
8493
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008494/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8495/// operator @p Opc at location @c TokLoc. This routine only supports
8496/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00008497ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008498 BinaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008499 Expr *lhsExpr, Expr *rhsExpr) {
8500 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008501 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008502 // The following two variables are used for compound assignment operators
8503 QualType CompLHSTy; // Type of LHS after promotions for computation
8504 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00008505 ExprValueKind VK = VK_RValue;
8506 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008507
Douglas Gregor1beec452011-03-12 01:48:56 +00008508 // Check if a 'foo<int>' involved in a binary op, identifies a single
8509 // function unambiguously (i.e. an lvalue ala 13.4)
8510 // But since an assignment can trigger target based overload, exclude it in
8511 // our blind search. i.e:
8512 // template<class T> void f(); template<class T, class U> void f(U);
8513 // f<int> == 0; // resolve f<int> blindly
8514 // void (*p)(int); p = f<int>; // resolve f<int> using target
8515 if (Opc != BO_Assign) {
John McCall3aef3d82011-04-10 19:13:55 +00008516 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall31996342011-04-07 08:22:57 +00008517 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008518 lhs = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00008519
John McCall3aef3d82011-04-10 19:13:55 +00008520 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall31996342011-04-07 08:22:57 +00008521 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008522 rhs = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00008523 }
8524
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008525 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008526 case BO_Assign:
John Wiegley01296292011-04-08 18:41:53 +00008527 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00008528 if (getLangOptions().CPlusPlus &&
John Wiegley01296292011-04-08 18:41:53 +00008529 lhs.get()->getObjectKind() != OK_ObjCProperty) {
8530 VK = lhs.get()->getValueKind();
8531 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008532 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008533 if (!ResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00008534 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008535 break;
John McCalle3027922010-08-25 11:45:40 +00008536 case BO_PtrMemD:
8537 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00008538 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008539 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00008540 break;
John McCalle3027922010-08-25 11:45:40 +00008541 case BO_Mul:
8542 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008543 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00008544 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008545 break;
John McCalle3027922010-08-25 11:45:40 +00008546 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008547 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
8548 break;
John McCalle3027922010-08-25 11:45:40 +00008549 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008550 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
8551 break;
John McCalle3027922010-08-25 11:45:40 +00008552 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008553 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
8554 break;
John McCalle3027922010-08-25 11:45:40 +00008555 case BO_Shl:
8556 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008557 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008558 break;
John McCalle3027922010-08-25 11:45:40 +00008559 case BO_LE:
8560 case BO_LT:
8561 case BO_GE:
8562 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008563 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008564 break;
John McCalle3027922010-08-25 11:45:40 +00008565 case BO_EQ:
8566 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008567 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008568 break;
John McCalle3027922010-08-25 11:45:40 +00008569 case BO_And:
8570 case BO_Xor:
8571 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008572 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
8573 break;
John McCalle3027922010-08-25 11:45:40 +00008574 case BO_LAnd:
8575 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00008576 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008577 break;
John McCalle3027922010-08-25 11:45:40 +00008578 case BO_MulAssign:
8579 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008580 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00008581 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008582 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008583 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8584 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008585 break;
John McCalle3027922010-08-25 11:45:40 +00008586 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008587 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
8588 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008589 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8590 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008591 break;
John McCalle3027922010-08-25 11:45:40 +00008592 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008593 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00008594 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8595 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008596 break;
John McCalle3027922010-08-25 11:45:40 +00008597 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008598 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00008599 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8600 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008601 break;
John McCalle3027922010-08-25 11:45:40 +00008602 case BO_ShlAssign:
8603 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008604 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008605 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008606 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8607 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008608 break;
John McCalle3027922010-08-25 11:45:40 +00008609 case BO_AndAssign:
8610 case BO_XorAssign:
8611 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008612 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
8613 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008614 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8615 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008616 break;
John McCalle3027922010-08-25 11:45:40 +00008617 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00008618 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00008619 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
8620 VK = rhs.get()->getValueKind();
8621 OK = rhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008622 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008623 break;
8624 }
John Wiegley01296292011-04-08 18:41:53 +00008625 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008626 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008627 if (CompResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00008628 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
8629 ResultTy, VK, OK, OpLoc));
8630 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008631 VK = VK_LValue;
John Wiegley01296292011-04-08 18:41:53 +00008632 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008633 }
John Wiegley01296292011-04-08 18:41:53 +00008634 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
8635 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00008636 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008637}
8638
Sebastian Redl44615072009-10-27 12:10:02 +00008639/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
8640/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008641static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8642 const PartialDiagnostic &PD,
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008643 const PartialDiagnostic &FirstNote,
8644 SourceRange FirstParenRange,
8645 const PartialDiagnostic &SecondNote,
Douglas Gregor89336232010-03-29 23:34:08 +00008646 SourceRange SecondParenRange) {
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008647 Self.Diag(Loc, PD);
8648
8649 if (!FirstNote.getDiagID())
8650 return;
8651
8652 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
8653 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8654 // We can't display the parentheses, so just return.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008655 return;
8656 }
8657
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008658 Self.Diag(Loc, FirstNote)
8659 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
Douglas Gregora771f462010-03-31 17:46:05 +00008660 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008661
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008662 if (!SecondNote.getDiagID())
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008663 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008664
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008665 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
8666 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8667 // We can't display the parentheses, so just dig the
8668 // warning/error and return.
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008669 Self.Diag(Loc, SecondNote);
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008670 return;
8671 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008672
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008673 Self.Diag(Loc, SecondNote)
Douglas Gregora771f462010-03-31 17:46:05 +00008674 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
8675 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008676}
8677
Sebastian Redl44615072009-10-27 12:10:02 +00008678/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8679/// operators are mixed in a way that suggests that the programmer forgot that
8680/// comparison operators have higher precedence. The most typical example of
8681/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008682static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008683 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00008684 typedef BinaryOperator BinOp;
8685 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
8686 rhsopc = static_cast<BinOp::Opcode>(-1);
8687 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008688 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00008689 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008690 rhsopc = BO->getOpcode();
8691
8692 // Subs are not binary operators.
8693 if (lhsopc == -1 && rhsopc == -1)
8694 return;
8695
8696 // Bitwise operations are sometimes used as eager logical ops.
8697 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00008698 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
8699 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008700 return;
8701
Sebastian Redl44615072009-10-27 12:10:02 +00008702 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008703 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008704 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008705 << SourceRange(lhs->getLocStart(), OpLoc)
8706 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008707 Self.PDiag(diag::note_precedence_bitwise_silence)
8708 << BinOp::getOpcodeStr(lhsopc),
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00008709 lhs->getSourceRange(),
8710 Self.PDiag(diag::note_precedence_bitwise_first)
8711 << BinOp::getOpcodeStr(Opc),
8712 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
Sebastian Redl44615072009-10-27 12:10:02 +00008713 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008714 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008715 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008716 << SourceRange(OpLoc, rhs->getLocEnd())
8717 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00008718 Self.PDiag(diag::note_precedence_bitwise_silence)
8719 << BinOp::getOpcodeStr(rhsopc),
8720 rhs->getSourceRange(),
Douglas Gregor89336232010-03-29 23:34:08 +00008721 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008722 << BinOp::getOpcodeStr(Opc),
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00008723 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl43028242009-10-26 15:24:15 +00008724}
8725
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008726/// \brief It accepts a '&&' expr that is inside a '||' one.
8727/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8728/// in parentheses.
8729static void
8730EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008731 BinaryOperator *Bop) {
8732 assert(Bop->getOpcode() == BO_LAnd);
8733 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008734 Self.PDiag(diag::warn_logical_and_in_logical_or)
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008735 << Bop->getSourceRange() << OpLoc,
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008736 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008737 Bop->getSourceRange(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008738 Self.PDiag(0), SourceRange());
8739}
8740
8741/// \brief Returns true if the given expression can be evaluated as a constant
8742/// 'true'.
8743static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8744 bool Res;
8745 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8746}
8747
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008748/// \brief Returns true if the given expression can be evaluated as a constant
8749/// 'false'.
8750static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8751 bool Res;
8752 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8753}
8754
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008755/// \brief Look for '&&' in the left hand of a '||' expr.
8756static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008757 Expr *OrLHS, Expr *OrRHS) {
8758 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008759 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008760 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8761 if (EvaluatesAsFalse(S, OrRHS))
8762 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008763 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8764 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8765 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8766 } else if (Bop->getOpcode() == BO_LOr) {
8767 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8768 // If it's "a || b && 1 || c" we didn't warn earlier for
8769 // "a || b && 1", but warn now.
8770 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8771 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8772 }
8773 }
8774 }
8775}
8776
8777/// \brief Look for '&&' in the right hand of a '||' expr.
8778static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008779 Expr *OrLHS, Expr *OrRHS) {
8780 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008781 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008782 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8783 if (EvaluatesAsFalse(S, OrLHS))
8784 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008785 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8786 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8787 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008788 }
8789 }
8790}
8791
Sebastian Redl43028242009-10-26 15:24:15 +00008792/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008793/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008794static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008795 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008796 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008797 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008798 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8799
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008800 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8801 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008802 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008803 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8804 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008805 }
Sebastian Redl43028242009-10-26 15:24:15 +00008806}
8807
Steve Naroff218bc2b2007-05-04 21:54:46 +00008808// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008809ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008810 tok::TokenKind Kind,
8811 Expr *lhs, Expr *rhs) {
8812 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00008813 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8814 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008815
Sebastian Redl43028242009-10-26 15:24:15 +00008816 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8817 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8818
Douglas Gregor5287f092009-11-05 00:51:44 +00008819 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8820}
8821
John McCalldadc5752010-08-24 06:29:42 +00008822ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008823 BinaryOperatorKind Opc,
8824 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00008825 if (getLangOptions().CPlusPlus) {
8826 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008827
John McCall622114c2010-12-06 05:26:58 +00008828 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8829 UseBuiltinOperator = false;
8830 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8831 UseBuiltinOperator = true;
8832 } else {
8833 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8834 !rhs->getType()->isOverloadableType();
8835 }
8836
8837 if (!UseBuiltinOperator) {
8838 // Find all of the overloaded operators visible from this
8839 // point. We perform both an operator-name lookup from the local
8840 // scope and an argument-dependent lookup based on the types of
8841 // the arguments.
8842 UnresolvedSet<16> Functions;
8843 OverloadedOperatorKind OverOp
8844 = BinaryOperator::getOverloadedOperator(Opc);
8845 if (S && OverOp != OO_None)
8846 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8847 Functions);
8848
8849 // Build the (potentially-overloaded, potentially-dependent)
8850 // binary operation.
8851 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8852 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00008853 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008854
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008855 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00008856 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008857}
8858
John McCalldadc5752010-08-24 06:29:42 +00008859ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008860 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008861 Expr *InputExpr) {
8862 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008863 ExprValueKind VK = VK_RValue;
8864 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008865 QualType resultType;
8866 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008867 case UO_PreInc:
8868 case UO_PreDec:
8869 case UO_PostInc:
8870 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008871 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008872 Opc == UO_PreInc ||
8873 Opc == UO_PostInc,
8874 Opc == UO_PreInc ||
8875 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008876 break;
John McCalle3027922010-08-25 11:45:40 +00008877 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00008878 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008879 break;
John McCall31996342011-04-07 08:22:57 +00008880 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00008881 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00008882 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008883 Input = move(resolved);
8884 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8885 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008886 break;
John McCall31996342011-04-07 08:22:57 +00008887 }
John McCalle3027922010-08-25 11:45:40 +00008888 case UO_Plus:
8889 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008890 Input = UsualUnaryConversions(Input.take());
8891 if (Input.isInvalid()) return ExprError();
8892 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008893 if (resultType->isDependentType())
8894 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008895 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8896 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008897 break;
8898 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8899 resultType->isEnumeralType())
8900 break;
8901 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008902 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008903 resultType->isPointerType())
8904 break;
John McCall36226622010-10-12 02:09:17 +00008905 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008906 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008907 if (Input.isInvalid()) return ExprError();
8908 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008909 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008910
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008911 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008912 << resultType << Input.get()->getSourceRange());
8913
John McCalle3027922010-08-25 11:45:40 +00008914 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008915 Input = UsualUnaryConversions(Input.take());
8916 if (Input.isInvalid()) return ExprError();
8917 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008918 if (resultType->isDependentType())
8919 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008920 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8921 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8922 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008923 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008924 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008925 else if (resultType->hasIntegerRepresentation())
8926 break;
8927 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008928 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008929 if (Input.isInvalid()) return ExprError();
8930 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008931 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008932 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008933 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008934 }
Steve Naroff35d85152007-05-07 00:24:15 +00008935 break;
John Wiegley01296292011-04-08 18:41:53 +00008936
John McCalle3027922010-08-25 11:45:40 +00008937 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008938 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008939 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8940 if (Input.isInvalid()) return ExprError();
8941 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008942 if (resultType->isDependentType())
8943 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008944 if (resultType->isScalarType()) {
8945 // C99 6.5.3.3p1: ok, fallthrough;
8946 if (Context.getLangOptions().CPlusPlus) {
8947 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8948 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008949 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8950 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008951 }
John McCall36226622010-10-12 02:09:17 +00008952 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008953 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00008954 if (Input.isInvalid()) return ExprError();
8955 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00008956 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008957 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008958 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008959 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008960
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008961 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008962 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008963 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008964 break;
John McCalle3027922010-08-25 11:45:40 +00008965 case UO_Real:
8966 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008967 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00008968 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00008969 if (Input.isInvalid()) return ExprError();
8970 if (Input.get()->getValueKind() != VK_RValue &&
8971 Input.get()->getObjectKind() == OK_Ordinary)
8972 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00008973 break;
John McCalle3027922010-08-25 11:45:40 +00008974 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008975 resultType = Input.get()->getType();
8976 VK = Input.get()->getValueKind();
8977 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008978 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008979 }
John Wiegley01296292011-04-08 18:41:53 +00008980 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008981 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008982
John Wiegley01296292011-04-08 18:41:53 +00008983 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008984 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008985}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008986
John McCalldadc5752010-08-24 06:29:42 +00008987ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008988 UnaryOperatorKind Opc,
8989 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00008990 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00008991 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008992 // Find all of the overloaded operators visible from this
8993 // point. We perform both an operator-name lookup from the local
8994 // scope and an argument-dependent lookup based on the types of
8995 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008996 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008997 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008998 if (S && OverOp != OO_None)
8999 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9000 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009001
John McCallb268a282010-08-23 23:25:46 +00009002 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009003 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009004
John McCallb268a282010-08-23 23:25:46 +00009005 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009006}
9007
Douglas Gregor5287f092009-11-05 00:51:44 +00009008// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00009009ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00009010 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00009011 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00009012}
9013
Steve Naroff66356bd2007-09-16 14:56:35 +00009014/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00009015ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00009016 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00009017 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00009018 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00009019 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009020 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00009021}
9022
John McCalldadc5752010-08-24 06:29:42 +00009023ExprResult
John McCallb268a282010-08-23 23:25:46 +00009024Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009025 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00009026 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9027 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9028
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00009029 bool isFileScope
9030 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00009031 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009032 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00009033
Chris Lattner366727f2007-07-24 16:58:17 +00009034 // FIXME: there are a variety of strange constraints to enforce here, for
9035 // example, it is not possible to goto into a stmt expression apparently.
9036 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00009037
Chris Lattner366727f2007-07-24 16:58:17 +00009038 // If there are sub stmts in the compound stmt, take the type of the last one
9039 // as the type of the stmtexpr.
9040 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009041 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00009042 if (!Compound->body_empty()) {
9043 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009044 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00009045 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009046 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9047 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00009048 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009049 }
John Wiegley01296292011-04-08 18:41:53 +00009050 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00009051 // Do function/array conversion on the last expression, but not
9052 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00009053 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9054 if (LastExpr.isInvalid())
9055 return ExprError();
9056 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00009057
John Wiegley01296292011-04-08 18:41:53 +00009058 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9059 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009060 InitializedEntity::InitializeResult(LPLoc,
9061 Ty,
9062 false),
9063 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00009064 LastExpr);
9065 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009066 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009067 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009068 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00009069 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009070 else
John Wiegley01296292011-04-08 18:41:53 +00009071 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009072 StmtExprMayBindToTemp = true;
9073 }
9074 }
9075 }
Chris Lattner944d3062008-07-26 19:51:01 +00009076 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009077
Eli Friedmanba961a92009-03-23 00:24:07 +00009078 // FIXME: Check that expression type is complete/non-abstract; statement
9079 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009080 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9081 if (StmtExprMayBindToTemp)
9082 return MaybeBindToTemporary(ResStmtExpr);
9083 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00009084}
Steve Naroff78864672007-08-01 22:05:33 +00009085
John McCalldadc5752010-08-24 06:29:42 +00009086ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009087 TypeSourceInfo *TInfo,
9088 OffsetOfComponent *CompPtr,
9089 unsigned NumComponents,
9090 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00009091 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009092 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00009093 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00009094
Chris Lattnerf17bd422007-08-30 17:45:32 +00009095 // We must have at least one component that refers to the type, and the first
9096 // one is known to be a field designator. Verify that the ArgTy represents
9097 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009098 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00009099 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9100 << ArgTy << TypeRange);
9101
9102 // Type must be complete per C99 7.17p3 because a declaring a variable
9103 // with an incomplete type would be ill-formed.
9104 if (!Dependent
9105 && RequireCompleteType(BuiltinLoc, ArgTy,
9106 PDiag(diag::err_offsetof_incomplete_type)
9107 << TypeRange))
9108 return ExprError();
9109
Chris Lattner78502cf2007-08-31 21:49:13 +00009110 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9111 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00009112 // FIXME: This diagnostic isn't actually visible because the location is in
9113 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00009114 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00009115 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9116 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00009117
9118 bool DidWarnAboutNonPOD = false;
9119 QualType CurrentType = ArgTy;
9120 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9121 llvm::SmallVector<OffsetOfNode, 4> Comps;
9122 llvm::SmallVector<Expr*, 4> Exprs;
9123 for (unsigned i = 0; i != NumComponents; ++i) {
9124 const OffsetOfComponent &OC = CompPtr[i];
9125 if (OC.isBrackets) {
9126 // Offset of an array sub-field. TODO: Should we allow vector elements?
9127 if (!CurrentType->isDependentType()) {
9128 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9129 if(!AT)
9130 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9131 << CurrentType);
9132 CurrentType = AT->getElementType();
9133 } else
9134 CurrentType = Context.DependentTy;
9135
9136 // The expression must be an integral expression.
9137 // FIXME: An integral constant expression?
9138 Expr *Idx = static_cast<Expr*>(OC.U.E);
9139 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9140 !Idx->getType()->isIntegerType())
9141 return ExprError(Diag(Idx->getLocStart(),
9142 diag::err_typecheck_subscript_not_integer)
9143 << Idx->getSourceRange());
9144
9145 // Record this array index.
9146 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9147 Exprs.push_back(Idx);
9148 continue;
9149 }
9150
9151 // Offset of a field.
9152 if (CurrentType->isDependentType()) {
9153 // We have the offset of a field, but we can't look into the dependent
9154 // type. Just record the identifier of the field.
9155 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9156 CurrentType = Context.DependentTy;
9157 continue;
9158 }
9159
9160 // We need to have a complete type to look into.
9161 if (RequireCompleteType(OC.LocStart, CurrentType,
9162 diag::err_offsetof_incomplete_type))
9163 return ExprError();
9164
9165 // Look for the designated field.
9166 const RecordType *RC = CurrentType->getAs<RecordType>();
9167 if (!RC)
9168 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9169 << CurrentType);
9170 RecordDecl *RD = RC->getDecl();
9171
9172 // C++ [lib.support.types]p5:
9173 // The macro offsetof accepts a restricted set of type arguments in this
9174 // International Standard. type shall be a POD structure or a POD union
9175 // (clause 9).
9176 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9177 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00009178 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00009179 PDiag(diag::warn_offsetof_non_pod_type)
9180 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9181 << CurrentType))
9182 DidWarnAboutNonPOD = true;
9183 }
9184
9185 // Look for the field.
9186 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9187 LookupQualifiedName(R, RD);
9188 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009189 IndirectFieldDecl *IndirectMemberDecl = 0;
9190 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00009191 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00009192 MemberDecl = IndirectMemberDecl->getAnonField();
9193 }
9194
Douglas Gregor882211c2010-04-28 22:16:22 +00009195 if (!MemberDecl)
9196 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9197 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9198 OC.LocEnd));
9199
Douglas Gregor10982ea2010-04-28 22:36:06 +00009200 // C99 7.17p3:
9201 // (If the specified member is a bit-field, the behavior is undefined.)
9202 //
9203 // We diagnose this as an error.
9204 if (MemberDecl->getBitWidth()) {
9205 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9206 << MemberDecl->getDeclName()
9207 << SourceRange(BuiltinLoc, RParenLoc);
9208 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9209 return ExprError();
9210 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009211
9212 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009213 if (IndirectMemberDecl)
9214 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009215
Douglas Gregord1702062010-04-29 00:18:15 +00009216 // If the member was found in a base class, introduce OffsetOfNodes for
9217 // the base class indirections.
9218 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9219 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009220 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00009221 CXXBasePath &Path = Paths.front();
9222 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9223 B != BEnd; ++B)
9224 Comps.push_back(OffsetOfNode(B->Base));
9225 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009226
Francois Pichet783dd6e2010-11-21 06:08:52 +00009227 if (IndirectMemberDecl) {
9228 for (IndirectFieldDecl::chain_iterator FI =
9229 IndirectMemberDecl->chain_begin(),
9230 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9231 assert(isa<FieldDecl>(*FI));
9232 Comps.push_back(OffsetOfNode(OC.LocStart,
9233 cast<FieldDecl>(*FI), OC.LocEnd));
9234 }
9235 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00009236 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00009237
Douglas Gregor882211c2010-04-28 22:16:22 +00009238 CurrentType = MemberDecl->getType().getNonReferenceType();
9239 }
9240
9241 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9242 TInfo, Comps.data(), Comps.size(),
9243 Exprs.data(), Exprs.size(), RParenLoc));
9244}
Mike Stump4e1f26a2009-02-19 03:04:26 +00009245
John McCalldadc5752010-08-24 06:29:42 +00009246ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00009247 SourceLocation BuiltinLoc,
9248 SourceLocation TypeLoc,
9249 ParsedType argty,
9250 OffsetOfComponent *CompPtr,
9251 unsigned NumComponents,
9252 SourceLocation RPLoc) {
9253
Douglas Gregor882211c2010-04-28 22:16:22 +00009254 TypeSourceInfo *ArgTInfo;
9255 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
9256 if (ArgTy.isNull())
9257 return ExprError();
9258
Eli Friedman06dcfd92010-08-05 10:15:45 +00009259 if (!ArgTInfo)
9260 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9261
9262 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9263 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00009264}
9265
9266
John McCalldadc5752010-08-24 06:29:42 +00009267ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009268 Expr *CondExpr,
9269 Expr *LHSExpr, Expr *RHSExpr,
9270 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00009271 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9272
John McCall7decc9e2010-11-18 06:31:45 +00009273 ExprValueKind VK = VK_RValue;
9274 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009275 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00009276 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00009277 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009278 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00009279 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009280 } else {
9281 // The conditional expression is required to be a constant expression.
9282 llvm::APSInt condEval(32);
9283 SourceLocation ExpLoc;
9284 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009285 return ExprError(Diag(ExpLoc,
9286 diag::err_typecheck_choose_expr_requires_constant)
9287 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00009288
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009289 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00009290 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9291
9292 resType = ActiveExpr->getType();
9293 ValueDependent = ActiveExpr->isValueDependent();
9294 VK = ActiveExpr->getValueKind();
9295 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009296 }
9297
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009298 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00009299 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00009300 resType->isDependentType(),
9301 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00009302}
9303
Steve Naroffc540d662008-09-03 18:15:37 +00009304//===----------------------------------------------------------------------===//
9305// Clang Extensions.
9306//===----------------------------------------------------------------------===//
9307
9308/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009309void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009310 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9311 PushBlockScope(BlockScope, Block);
9312 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009313 if (BlockScope)
9314 PushDeclContext(BlockScope, Block);
9315 else
9316 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009317}
9318
Mike Stump82f071f2009-02-04 22:31:32 +00009319void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00009320 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00009321 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009322 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009323
John McCall8cb7bdf2010-06-04 23:28:52 +00009324 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00009325 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00009326
John McCall3882ace2011-01-05 12:14:39 +00009327 // GetTypeForDeclarator always produces a function type for a block
9328 // literal signature. Furthermore, it is always a FunctionProtoType
9329 // unless the function was written with a typedef.
9330 assert(T->isFunctionType() &&
9331 "GetTypeForDeclarator made a non-function block signature");
9332
9333 // Look for an explicit signature in that function type.
9334 FunctionProtoTypeLoc ExplicitSignature;
9335
9336 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9337 if (isa<FunctionProtoTypeLoc>(tmp)) {
9338 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9339
9340 // Check whether that explicit signature was synthesized by
9341 // GetTypeForDeclarator. If so, don't save that as part of the
9342 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00009343 if (ExplicitSignature.getLocalRangeBegin() ==
9344 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00009345 // This would be much cheaper if we stored TypeLocs instead of
9346 // TypeSourceInfos.
9347 TypeLoc Result = ExplicitSignature.getResultLoc();
9348 unsigned Size = Result.getFullDataSize();
9349 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9350 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9351
9352 ExplicitSignature = FunctionProtoTypeLoc();
9353 }
John McCalla3ccba02010-06-04 11:21:44 +00009354 }
Mike Stump11289f42009-09-09 15:08:12 +00009355
John McCall3882ace2011-01-05 12:14:39 +00009356 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9357 CurBlock->FunctionType = T;
9358
9359 const FunctionType *Fn = T->getAs<FunctionType>();
9360 QualType RetTy = Fn->getResultType();
9361 bool isVariadic =
9362 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9363
John McCall8e346702010-06-04 19:02:56 +00009364 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00009365
John McCalla3ccba02010-06-04 11:21:44 +00009366 // Don't allow returning a objc interface by value.
9367 if (RetTy->isObjCObjectType()) {
9368 Diag(ParamInfo.getSourceRange().getBegin(),
9369 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9370 return;
9371 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009372
John McCalla3ccba02010-06-04 11:21:44 +00009373 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00009374 // return type. TODO: what should we do with declarators like:
9375 // ^ * { ... }
9376 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00009377 if (RetTy != Context.DependentTy)
9378 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009379
John McCalla3ccba02010-06-04 11:21:44 +00009380 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00009381 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00009382 if (ExplicitSignature) {
9383 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9384 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009385 if (Param->getIdentifier() == 0 &&
9386 !Param->isImplicit() &&
9387 !Param->isInvalidDecl() &&
9388 !getLangOptions().CPlusPlus)
9389 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00009390 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009391 }
John McCalla3ccba02010-06-04 11:21:44 +00009392
9393 // Fake up parameter variables if we have a typedef, like
9394 // ^ fntype { ... }
9395 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9396 for (FunctionProtoType::arg_type_iterator
9397 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9398 ParmVarDecl *Param =
9399 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9400 ParamInfo.getSourceRange().getBegin(),
9401 *I);
John McCall8e346702010-06-04 19:02:56 +00009402 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00009403 }
Steve Naroffc540d662008-09-03 18:15:37 +00009404 }
John McCalla3ccba02010-06-04 11:21:44 +00009405
John McCall8e346702010-06-04 19:02:56 +00009406 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00009407 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00009408 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00009409 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9410 CurBlock->TheDecl->param_end(),
9411 /*CheckParameterNames=*/false);
9412 }
9413
John McCalla3ccba02010-06-04 11:21:44 +00009414 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00009415 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00009416
John McCall8e346702010-06-04 19:02:56 +00009417 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00009418 Diag(ParamInfo.getAttributes()->getLoc(),
9419 diag::warn_attribute_sentinel_not_variadic) << 1;
9420 // FIXME: remove the attribute.
9421 }
9422
9423 // Put the parameter variables in scope. We can bail out immediately
9424 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00009425 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00009426 return;
9427
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009428 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00009429 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9430 (*AI)->setOwningFunction(CurBlock->TheDecl);
9431
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009432 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009433 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009434 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00009435
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009436 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009437 }
John McCallf7b2fb52010-01-22 00:28:27 +00009438 }
Steve Naroffc540d662008-09-03 18:15:37 +00009439}
9440
9441/// ActOnBlockError - If there is an error parsing a block, this callback
9442/// is invoked to pop the information about the block from the action impl.
9443void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00009444 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00009445 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00009446 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00009447}
9448
9449/// ActOnBlockStmtExpr - This is called when the body of a block statement
9450/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00009451ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00009452 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00009453 // If blocks are disabled, emit an error.
9454 if (!LangOpts.Blocks)
9455 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00009456
Douglas Gregor9a28e842010-03-01 23:15:13 +00009457 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009458
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009459 PopDeclContext();
9460
Steve Naroffc540d662008-09-03 18:15:37 +00009461 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00009462 if (!BSI->ReturnType.isNull())
9463 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009464
Mike Stump3bf1ab42009-07-28 22:04:01 +00009465 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00009466 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00009467
John McCallc63de662011-02-02 13:00:07 +00009468 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00009469 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
9470 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00009471
John McCall8e346702010-06-04 19:02:56 +00009472 // If the user wrote a function type in some form, try to use that.
9473 if (!BSI->FunctionType.isNull()) {
9474 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9475
9476 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9477 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9478
9479 // Turn protoless block types into nullary block types.
9480 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009481 FunctionProtoType::ExtProtoInfo EPI;
9482 EPI.ExtInfo = Ext;
9483 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009484
9485 // Otherwise, if we don't need to change anything about the function type,
9486 // preserve its sugar structure.
9487 } else if (FTy->getResultType() == RetTy &&
9488 (!NoReturn || FTy->getNoReturnAttr())) {
9489 BlockTy = BSI->FunctionType;
9490
9491 // Otherwise, make the minimal modifications to the function type.
9492 } else {
9493 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009494 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9495 EPI.TypeQuals = 0; // FIXME: silently?
9496 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009497 BlockTy = Context.getFunctionType(RetTy,
9498 FPT->arg_type_begin(),
9499 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009500 EPI);
John McCall8e346702010-06-04 19:02:56 +00009501 }
9502
9503 // If we don't have a function type, just build one from nothing.
9504 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009505 FunctionProtoType::ExtProtoInfo EPI;
Eli Friedmanc5b20b52011-04-09 08:18:08 +00009506 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, false, 0, CC_Default);
John McCalldb40c7f2010-12-14 08:05:40 +00009507 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009508 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009509
John McCall8e346702010-06-04 19:02:56 +00009510 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9511 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009512 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009513
Chris Lattner45542ea2009-04-19 05:28:12 +00009514 // If needed, diagnose invalid gotos and switches in the block.
John McCallaab3e412010-08-25 08:40:02 +00009515 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00009516 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009517
Chris Lattner60f84492011-02-17 23:58:47 +00009518 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009519
John McCallc63de662011-02-02 13:00:07 +00009520 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCall1d570a72010-08-25 05:56:39 +00009521
Ted Kremenek1767a272011-02-23 01:51:48 +00009522 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9523 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009524 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009525}
9526
John McCalldadc5752010-08-24 06:29:42 +00009527ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00009528 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009529 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009530 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009531 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00009532 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009533}
9534
John McCalldadc5752010-08-24 06:29:42 +00009535ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009536 Expr *E, TypeSourceInfo *TInfo,
9537 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009538 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009539
Eli Friedman121ba0c2008-08-09 23:32:40 +00009540 // Get the va_list type
9541 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009542 if (VaListType->isArrayType()) {
9543 // Deal with implicit array decay; for example, on x86-64,
9544 // va_list is an array, but it's supposed to decay to
9545 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009546 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009547 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00009548 ExprResult Result = UsualUnaryConversions(E);
9549 if (Result.isInvalid())
9550 return ExprError();
9551 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00009552 } else {
9553 // Otherwise, the va_list argument must be an l-value because
9554 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009555 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009556 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009557 return ExprError();
9558 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009559
Douglas Gregorad3150c2009-05-19 23:10:31 +00009560 if (!E->isTypeDependent() &&
9561 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009562 return ExprError(Diag(E->getLocStart(),
9563 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009564 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009565 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009566
Eli Friedmanba961a92009-03-23 00:24:07 +00009567 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009568 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00009569
Abramo Bagnara27db2392010-08-10 10:06:15 +00009570 QualType T = TInfo->getType().getNonLValueExprType(Context);
9571 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009572}
9573
John McCalldadc5752010-08-24 06:29:42 +00009574ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009575 // The type of __null will be int or long, depending on the size of
9576 // pointers on the target.
9577 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009578 unsigned pw = Context.Target.getPointerWidth(0);
9579 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009580 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009581 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009582 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009583 else if (pw == Context.Target.getLongLongWidth())
9584 Ty = Context.LongLongTy;
9585 else {
9586 assert(!"I don't know size of pointer!");
9587 Ty = Context.IntTy;
9588 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009589
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009590 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009591}
9592
Alexis Huntc46382e2010-04-28 23:02:27 +00009593static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009594 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00009595 if (!SemaRef.getLangOptions().ObjC1)
9596 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009597
Anders Carlssonace5d072009-11-10 04:46:30 +00009598 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9599 if (!PT)
9600 return;
9601
9602 // Check if the destination is of type 'id'.
9603 if (!PT->isObjCIdType()) {
9604 // Check if the destination is the 'NSString' interface.
9605 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9606 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9607 return;
9608 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009609
Anders Carlssonace5d072009-11-10 04:46:30 +00009610 // Strip off any parens and casts.
9611 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
9612 if (!SL || SL->isWide())
9613 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009614
Douglas Gregora771f462010-03-31 17:46:05 +00009615 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009616}
9617
Chris Lattner9bad62c2008-01-04 18:04:52 +00009618bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9619 SourceLocation Loc,
9620 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009621 Expr *SrcExpr, AssignmentAction Action,
9622 bool *Complained) {
9623 if (Complained)
9624 *Complained = false;
9625
Chris Lattner9bad62c2008-01-04 18:04:52 +00009626 // Decode the result (notice that AST's are still created for extensions).
9627 bool isInvalid = false;
9628 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00009629 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009630
Chris Lattner9bad62c2008-01-04 18:04:52 +00009631 switch (ConvTy) {
9632 default: assert(0 && "Unknown conversion type");
9633 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009634 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009635 DiagKind = diag::ext_typecheck_convert_pointer_int;
9636 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009637 case IntToPointer:
9638 DiagKind = diag::ext_typecheck_convert_int_pointer;
9639 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009640 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009641 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009642 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9643 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009644 case IncompatiblePointerSign:
9645 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9646 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009647 case FunctionVoidPointer:
9648 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9649 break;
John McCall4fff8f62011-02-01 00:10:29 +00009650 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009651 // Perform array-to-pointer decay if necessary.
9652 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9653
John McCall4fff8f62011-02-01 00:10:29 +00009654 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9655 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9656 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9657 DiagKind = diag::err_typecheck_incompatible_address_space;
9658 break;
9659 }
9660
9661 llvm_unreachable("unknown error case for discarding qualifiers!");
9662 // fallthrough
9663 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009664 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009665 // If the qualifiers lost were because we were applying the
9666 // (deprecated) C++ conversion from a string literal to a char*
9667 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9668 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009669 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009670 // bit of refactoring (so that the second argument is an
9671 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009672 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009673 // C++ semantics.
9674 if (getLangOptions().CPlusPlus &&
9675 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9676 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009677 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9678 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009679 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009680 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009681 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009682 case IntToBlockPointer:
9683 DiagKind = diag::err_int_to_block_pointer;
9684 break;
9685 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009686 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009687 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009688 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009689 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009690 // it can give a more specific diagnostic.
9691 DiagKind = diag::warn_incompatible_qualified_id;
9692 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009693 case IncompatibleVectors:
9694 DiagKind = diag::warn_incompatible_vectors;
9695 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009696 case Incompatible:
9697 DiagKind = diag::err_typecheck_convert_incompatible;
9698 isInvalid = true;
9699 break;
9700 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009701
Douglas Gregorc68e1402010-04-09 00:35:39 +00009702 QualType FirstType, SecondType;
9703 switch (Action) {
9704 case AA_Assigning:
9705 case AA_Initializing:
9706 // The destination type comes first.
9707 FirstType = DstType;
9708 SecondType = SrcType;
9709 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009710
Douglas Gregorc68e1402010-04-09 00:35:39 +00009711 case AA_Returning:
9712 case AA_Passing:
9713 case AA_Converting:
9714 case AA_Sending:
9715 case AA_Casting:
9716 // The source type comes first.
9717 FirstType = SrcType;
9718 SecondType = DstType;
9719 break;
9720 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009721
Douglas Gregorc68e1402010-04-09 00:35:39 +00009722 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00009723 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009724 if (Complained)
9725 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009726 return isInvalid;
9727}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009728
Chris Lattnerc71d08b2009-04-25 21:59:05 +00009729bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009730 llvm::APSInt ICEResult;
9731 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9732 if (Result)
9733 *Result = ICEResult;
9734 return false;
9735 }
9736
Anders Carlssone54e8a12008-11-30 19:50:32 +00009737 Expr::EvalResult EvalResult;
9738
Mike Stump4e1f26a2009-02-19 03:04:26 +00009739 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00009740 EvalResult.HasSideEffects) {
9741 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9742
9743 if (EvalResult.Diag) {
9744 // We only show the note if it's not the usual "invalid subexpression"
9745 // or if it's actually in a subexpression.
9746 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9747 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9748 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9749 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009750
Anders Carlssone54e8a12008-11-30 19:50:32 +00009751 return true;
9752 }
9753
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009754 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9755 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009756
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009757 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009758 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9759 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009760 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009761
Anders Carlssone54e8a12008-11-30 19:50:32 +00009762 if (Result)
9763 *Result = EvalResult.Val.getInt();
9764 return false;
9765}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009766
Douglas Gregorff790f12009-11-26 00:44:06 +00009767void
Mike Stump11289f42009-09-09 15:08:12 +00009768Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009769 ExprEvalContexts.push_back(
9770 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009771}
9772
Mike Stump11289f42009-09-09 15:08:12 +00009773void
Douglas Gregorff790f12009-11-26 00:44:06 +00009774Sema::PopExpressionEvaluationContext() {
9775 // Pop the current expression evaluation context off the stack.
9776 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9777 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009778
Douglas Gregorfab31f42009-12-12 07:57:52 +00009779 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9780 if (Rec.PotentiallyReferenced) {
9781 // Mark any remaining declarations in the current position of the stack
9782 // as "referenced". If they were not meant to be referenced, semantic
9783 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009784 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +00009785 I = Rec.PotentiallyReferenced->begin(),
9786 IEnd = Rec.PotentiallyReferenced->end();
9787 I != IEnd; ++I)
9788 MarkDeclarationReferenced(I->first, I->second);
9789 }
9790
9791 if (Rec.PotentiallyDiagnosed) {
9792 // Emit any pending diagnostics.
9793 for (PotentiallyEmittedDiagnostics::iterator
9794 I = Rec.PotentiallyDiagnosed->begin(),
9795 IEnd = Rec.PotentiallyDiagnosed->end();
9796 I != IEnd; ++I)
9797 Diag(I->first, I->second);
9798 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009799 }
Douglas Gregorff790f12009-11-26 00:44:06 +00009800
9801 // When are coming out of an unevaluated context, clear out any
9802 // temporaries that we may have created as part of the evaluation of
9803 // the expression in that context: they aren't relevant because they
9804 // will never be constructed.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009805 if (Rec.Context == Unevaluated &&
Douglas Gregorff790f12009-11-26 00:44:06 +00009806 ExprTemporaries.size() > Rec.NumTemporaries)
9807 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9808 ExprTemporaries.end());
9809
9810 // Destroy the popped expression evaluation record.
9811 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009812}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009813
9814/// \brief Note that the given declaration was referenced in the source code.
9815///
9816/// This routine should be invoke whenever a given declaration is referenced
9817/// in the source code, and where that reference occurred. If this declaration
9818/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9819/// C99 6.9p3), then the declaration will be marked as used.
9820///
9821/// \param Loc the location where the declaration was referenced.
9822///
9823/// \param D the declaration that has been referenced by the source code.
9824void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9825 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00009826
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +00009827 D->setReferenced();
9828
Douglas Gregorebada0772010-06-17 23:14:26 +00009829 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +00009830 return;
Mike Stump11289f42009-09-09 15:08:12 +00009831
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00009832 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9833 // template or not. The reason for this is that unevaluated expressions
9834 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9835 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009836 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009837 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +00009838 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009839 return;
9840 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009841
Douglas Gregorfd27fed2010-04-07 20:29:57 +00009842 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9843 return;
Alexis Huntc46382e2010-04-28 23:02:27 +00009844
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009845 // Do not mark anything as "used" within a dependent context; wait for
9846 // an instantiation.
9847 if (CurContext->isDependentContext())
9848 return;
Mike Stump11289f42009-09-09 15:08:12 +00009849
Douglas Gregorff790f12009-11-26 00:44:06 +00009850 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009851 case Unevaluated:
9852 // We are in an expression that is not potentially evaluated; do nothing.
9853 return;
Mike Stump11289f42009-09-09 15:08:12 +00009854
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009855 case PotentiallyEvaluated:
9856 // We are in a potentially-evaluated expression, so this declaration is
9857 // "used"; handle this below.
9858 break;
Mike Stump11289f42009-09-09 15:08:12 +00009859
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009860 case PotentiallyPotentiallyEvaluated:
9861 // We are in an expression that may be potentially evaluated; queue this
9862 // declaration reference until we know whether the expression is
9863 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00009864 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009865 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009866
9867 case PotentiallyEvaluatedIfUsed:
9868 // Referenced declarations will only be used if the construct in the
9869 // containing expression is used.
9870 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009871 }
Mike Stump11289f42009-09-09 15:08:12 +00009872
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009873 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00009874 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Alexis Huntf92197c2011-05-12 03:51:51 +00009875 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor()) {
9876 if (Constructor->isTrivial())
Chandler Carruthc9262402010-08-23 07:55:51 +00009877 return;
9878 if (!Constructor->isUsed(false))
9879 DefineImplicitDefaultConstructor(Loc, Constructor);
Alexis Hunt22b5b132011-05-14 18:20:50 +00009880 } else if (Constructor->isDefaulted() &&
Alexis Hunt913820d2011-05-13 06:10:58 +00009881 Constructor->isCopyConstructor()) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009882 if (!Constructor->isUsed(false))
Alexis Hunt913820d2011-05-13 06:10:58 +00009883 DefineImplicitCopyConstructor(Loc, Constructor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009884 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009885
Douglas Gregor88d292c2010-05-13 16:44:06 +00009886 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009887 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Alexis Huntf91729462011-05-12 22:46:25 +00009888 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009889 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009890 if (Destructor->isVirtual())
9891 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009892 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Alexis Huntc9a55732011-05-14 05:23:28 +00009893 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009894 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +00009895 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +00009896 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009897 } else if (MethodDecl->isVirtual())
9898 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009899 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00009900 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +00009901 // Recursive functions should be marked when used from another function.
9902 if (CurContext == Function) return;
9903
Mike Stump11289f42009-09-09 15:08:12 +00009904 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00009905 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +00009906 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00009907 bool AlreadyInstantiated = false;
9908 if (FunctionTemplateSpecializationInfo *SpecInfo
9909 = Function->getTemplateSpecializationInfo()) {
9910 if (SpecInfo->getPointOfInstantiation().isInvalid())
9911 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009912 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009913 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009914 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009915 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +00009916 = Function->getMemberSpecializationInfo()) {
9917 if (MSInfo->getPointOfInstantiation().isInvalid())
9918 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009919 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +00009920 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00009921 AlreadyInstantiated = true;
9922 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009923
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009924 if (!AlreadyInstantiated) {
9925 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9926 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9927 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9928 Loc));
9929 else
Chandler Carruth54080172010-08-25 08:44:16 +00009930 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +00009931 }
John McCall83779672011-02-19 02:53:41 +00009932 } else {
9933 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009934 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9935 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +00009936 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +00009937 MarkDeclarationReferenced(Loc, *i);
9938 }
John McCall83779672011-02-19 02:53:41 +00009939 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009940
John McCall83779672011-02-19 02:53:41 +00009941 // Keep track of used but undefined functions.
9942 if (!Function->isPure() && !Function->hasBody() &&
9943 Function->getLinkage() != ExternalLinkage) {
9944 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9945 if (old.isInvalid()) old = Loc;
9946 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +00009947
John McCall83779672011-02-19 02:53:41 +00009948 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009949 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00009950 }
Mike Stump11289f42009-09-09 15:08:12 +00009951
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009952 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009953 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00009954 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00009955 Var->getInstantiatedFromStaticDataMember()) {
9956 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9957 assert(MSInfo && "Missing member specialization information?");
9958 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9959 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9960 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redl2ac2c722011-04-29 08:19:30 +00009961 // This is a modification of an existing AST node. Notify listeners.
9962 if (ASTMutationListener *L = getASTMutationListener())
9963 L->StaticDataMemberInstantiated(Var);
Chandler Carruth54080172010-08-25 08:44:16 +00009964 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +00009965 }
9966 }
Mike Stump11289f42009-09-09 15:08:12 +00009967
John McCall15dd4042011-02-21 19:25:48 +00009968 // Keep track of used but undefined variables. We make a hole in
9969 // the warning for static const data members with in-line
9970 // initializers.
John McCall83779672011-02-19 02:53:41 +00009971 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +00009972 && Var->getLinkage() != ExternalLinkage
9973 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +00009974 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9975 if (old.isInvalid()) old = Loc;
9976 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009977
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009978 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00009979 return;
Sam Weinigbae69142009-09-11 03:29:30 +00009980 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009981}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00009982
Douglas Gregor5597ab42010-05-07 23:12:07 +00009983namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +00009984 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +00009985 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +00009986 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +00009987 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9988 Sema &S;
9989 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009990
Douglas Gregor5597ab42010-05-07 23:12:07 +00009991 public:
9992 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +00009993
Douglas Gregor5597ab42010-05-07 23:12:07 +00009994 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +00009995
9996 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9997 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +00009998 };
9999}
10000
Chandler Carruthaf80f662010-06-09 08:17:30 +000010001bool MarkReferencedDecls::TraverseTemplateArgument(
10002 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010003 if (Arg.getKind() == TemplateArgument::Declaration) {
10004 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
10005 }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010006
10007 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010008}
10009
Chandler Carruthaf80f662010-06-09 08:17:30 +000010010bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010011 if (ClassTemplateSpecializationDecl *Spec
10012 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10013 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +000010014 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +000010015 }
10016
Chandler Carruthc65667c2010-06-10 10:31:57 +000010017 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +000010018}
10019
10020void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10021 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000010022 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000010023}
10024
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010025namespace {
10026 /// \brief Helper class that marks all of the declarations referenced by
10027 /// potentially-evaluated subexpressions as "referenced".
10028 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10029 Sema &S;
10030
10031 public:
10032 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10033
10034 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
10035
10036 void VisitDeclRefExpr(DeclRefExpr *E) {
10037 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10038 }
10039
10040 void VisitMemberExpr(MemberExpr *E) {
10041 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010042 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010043 }
10044
10045 void VisitCXXNewExpr(CXXNewExpr *E) {
10046 if (E->getConstructor())
10047 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
10048 if (E->getOperatorNew())
10049 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
10050 if (E->getOperatorDelete())
10051 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010052 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010053 }
10054
10055 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10056 if (E->getOperatorDelete())
10057 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000010058 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10059 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10060 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10061 S.MarkDeclarationReferenced(E->getLocStart(),
10062 S.LookupDestructor(Record));
10063 }
10064
Douglas Gregor32b3de52010-09-11 23:32:50 +000010065 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010066 }
10067
10068 void VisitCXXConstructExpr(CXXConstructExpr *E) {
10069 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010070 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010071 }
10072
10073 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
10074 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10075 }
Douglas Gregorf0873f42010-10-19 17:17:35 +000010076
10077 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10078 Visit(E->getExpr());
10079 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010080 };
10081}
10082
10083/// \brief Mark any declarations that appear within this expression or any
10084/// potentially-evaluated subexpressions as "referenced".
10085void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
10086 EvaluatedExprMarker(*this).Visit(E);
10087}
10088
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010089/// \brief Emit a diagnostic that describes an effect on the run-time behavior
10090/// of the program being compiled.
10091///
10092/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010093/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010094/// possibility that the code will actually be executable. Code in sizeof()
10095/// expressions, code used only during overload resolution, etc., are not
10096/// potentially evaluated. This routine will suppress such diagnostics or,
10097/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010098/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010099/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010100///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010101/// This routine should be used for all diagnostics that describe the run-time
10102/// behavior of a program, such as passing a non-POD value through an ellipsis.
10103/// Failure to do so will likely result in spurious diagnostics or failures
10104/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +000010105bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010106 const PartialDiagnostic &PD) {
10107 switch (ExprEvalContexts.back().Context ) {
10108 case Unevaluated:
10109 // The argument will never be evaluated, so don't complain.
10110 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010111
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010112 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010113 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +000010114 if (stmt && getCurFunctionOrMethodDecl()) {
10115 FunctionScopes.back()->PossiblyUnreachableDiags.
10116 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
10117 }
10118 else
10119 Diag(Loc, PD);
10120
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010121 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010122
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010123 case PotentiallyPotentiallyEvaluated:
10124 ExprEvalContexts.back().addDiagnostic(Loc, PD);
10125 break;
10126 }
10127
10128 return false;
10129}
10130
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010131bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
10132 CallExpr *CE, FunctionDecl *FD) {
10133 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
10134 return false;
10135
10136 PartialDiagnostic Note =
10137 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
10138 << FD->getDeclName() : PDiag();
10139 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010140
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010141 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010142 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010143 PDiag(diag::err_call_function_incomplete_return)
10144 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010145 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010146 << CE->getSourceRange(),
10147 std::make_pair(NoteLoc, Note)))
10148 return true;
10149
10150 return false;
10151}
10152
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010153// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000010154// will prevent this condition from triggering, which is what we want.
10155void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
10156 SourceLocation Loc;
10157
John McCall0506e4a2009-11-11 02:41:58 +000010158 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010159 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000010160
John McCalld5707ab2009-10-12 21:59:07 +000010161 if (isa<BinaryOperator>(E)) {
10162 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010163 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000010164 return;
10165
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010166 IsOrAssign = Op->getOpcode() == BO_OrAssign;
10167
John McCallb0e419e2009-11-12 00:06:05 +000010168 // Greylist some idioms by putting them into a warning subcategory.
10169 if (ObjCMessageExpr *ME
10170 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
10171 Selector Sel = ME->getSelector();
10172
John McCallb0e419e2009-11-12 00:06:05 +000010173 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000010174 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +000010175 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10176
10177 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000010178 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000010179 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10180 }
John McCall0506e4a2009-11-11 02:41:58 +000010181
John McCalld5707ab2009-10-12 21:59:07 +000010182 Loc = Op->getOperatorLoc();
10183 } else if (isa<CXXOperatorCallExpr>(E)) {
10184 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010185 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000010186 return;
10187
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010188 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000010189 Loc = Op->getOperatorLoc();
10190 } else {
10191 // Not an assignment.
10192 return;
10193 }
10194
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000010195 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010196
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000010197 SourceLocation Open = E->getSourceRange().getBegin();
10198 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
10199 Diag(Loc, diag::note_condition_assign_silence)
10200 << FixItHint::CreateInsertion(Open, "(")
10201 << FixItHint::CreateInsertion(Close, ")");
10202
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010203 if (IsOrAssign)
10204 Diag(Loc, diag::note_condition_or_assign_to_comparison)
10205 << FixItHint::CreateReplacement(Loc, "!=");
10206 else
10207 Diag(Loc, diag::note_condition_assign_to_comparison)
10208 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +000010209}
10210
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010211/// \brief Redundant parentheses over an equality comparison can indicate
10212/// that the user intended an assignment used as condition.
10213void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010214 // Don't warn if the parens came from a macro.
10215 SourceLocation parenLoc = parenE->getLocStart();
10216 if (parenLoc.isInvalid() || parenLoc.isMacroID())
10217 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000010218 // Don't warn for dependent expressions.
10219 if (parenE->isTypeDependent())
10220 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010221
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010222 Expr *E = parenE->IgnoreParens();
10223
10224 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000010225 if (opE->getOpcode() == BO_EQ &&
10226 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
10227 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010228 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000010229
Ted Kremenekae022092011-02-02 02:20:30 +000010230 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +000010231 Diag(Loc, diag::note_equality_comparison_silence)
10232 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
10233 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000010234 Diag(Loc, diag::note_equality_comparison_to_assign)
10235 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010236 }
10237}
10238
John Wiegley01296292011-04-08 18:41:53 +000010239ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000010240 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010241 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
10242 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000010243
John McCall0009fcc2011-04-26 20:42:42 +000010244 ExprResult result = CheckPlaceholderExpr(E);
10245 if (result.isInvalid()) return ExprError();
10246 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000010247
John McCall0009fcc2011-04-26 20:42:42 +000010248 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +000010249 if (getLangOptions().CPlusPlus)
10250 return CheckCXXBooleanCondition(E); // C++ 6.4p4
10251
John Wiegley01296292011-04-08 18:41:53 +000010252 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
10253 if (ERes.isInvalid())
10254 return ExprError();
10255 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +000010256
10257 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000010258 if (!T->isScalarType()) { // C99 6.8.4.1p1
10259 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
10260 << T << E->getSourceRange();
10261 return ExprError();
10262 }
John McCalld5707ab2009-10-12 21:59:07 +000010263 }
10264
John Wiegley01296292011-04-08 18:41:53 +000010265 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +000010266}
Douglas Gregore60e41a2010-05-06 17:25:47 +000010267
John McCalldadc5752010-08-24 06:29:42 +000010268ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
10269 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +000010270 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +000010271 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010272
10273 return CheckBooleanCondition(Sub, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000010274}
John McCall36e7fe32010-10-12 00:20:44 +000010275
John McCall31996342011-04-07 08:22:57 +000010276namespace {
John McCall2979fe02011-04-12 00:42:48 +000010277 /// A visitor for rebuilding a call to an __unknown_any expression
10278 /// to have an appropriate type.
10279 struct RebuildUnknownAnyFunction
10280 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
10281
10282 Sema &S;
10283
10284 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
10285
10286 ExprResult VisitStmt(Stmt *S) {
10287 llvm_unreachable("unexpected statement!");
10288 return ExprError();
10289 }
10290
10291 ExprResult VisitExpr(Expr *expr) {
10292 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
10293 << expr->getSourceRange();
10294 return ExprError();
10295 }
10296
10297 /// Rebuild an expression which simply semantically wraps another
10298 /// expression which it shares the type and value kind of.
10299 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10300 ExprResult subResult = Visit(expr->getSubExpr());
10301 if (subResult.isInvalid()) return ExprError();
10302
10303 Expr *subExpr = subResult.take();
10304 expr->setSubExpr(subExpr);
10305 expr->setType(subExpr->getType());
10306 expr->setValueKind(subExpr->getValueKind());
10307 assert(expr->getObjectKind() == OK_Ordinary);
10308 return expr;
10309 }
10310
10311 ExprResult VisitParenExpr(ParenExpr *paren) {
10312 return rebuildSugarExpr(paren);
10313 }
10314
10315 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10316 return rebuildSugarExpr(op);
10317 }
10318
10319 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10320 ExprResult subResult = Visit(op->getSubExpr());
10321 if (subResult.isInvalid()) return ExprError();
10322
10323 Expr *subExpr = subResult.take();
10324 op->setSubExpr(subExpr);
10325 op->setType(S.Context.getPointerType(subExpr->getType()));
10326 assert(op->getValueKind() == VK_RValue);
10327 assert(op->getObjectKind() == OK_Ordinary);
10328 return op;
10329 }
10330
10331 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
10332 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
10333
10334 expr->setType(decl->getType());
10335
10336 assert(expr->getValueKind() == VK_RValue);
10337 if (S.getLangOptions().CPlusPlus &&
10338 !(isa<CXXMethodDecl>(decl) &&
10339 cast<CXXMethodDecl>(decl)->isInstance()))
10340 expr->setValueKind(VK_LValue);
10341
10342 return expr;
10343 }
10344
10345 ExprResult VisitMemberExpr(MemberExpr *mem) {
10346 return resolveDecl(mem, mem->getMemberDecl());
10347 }
10348
10349 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
10350 return resolveDecl(ref, ref->getDecl());
10351 }
10352 };
10353}
10354
10355/// Given a function expression of unknown-any type, try to rebuild it
10356/// to have a function type.
10357static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
10358 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
10359 if (result.isInvalid()) return ExprError();
10360 return S.DefaultFunctionArrayConversion(result.take());
10361}
10362
10363namespace {
John McCall2d2e8702011-04-11 07:02:50 +000010364 /// A visitor for rebuilding an expression of type __unknown_anytype
10365 /// into one which resolves the type directly on the referring
10366 /// expression. Strict preservation of the original source
10367 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000010368 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000010369 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000010370
10371 Sema &S;
10372
10373 /// The current destination type.
10374 QualType DestType;
10375
10376 RebuildUnknownAnyExpr(Sema &S, QualType castType)
10377 : S(S), DestType(castType) {}
10378
John McCall39439732011-04-09 22:50:59 +000010379 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000010380 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +000010381 return ExprError();
John McCall31996342011-04-07 08:22:57 +000010382 }
10383
John McCall2d2e8702011-04-11 07:02:50 +000010384 ExprResult VisitExpr(Expr *expr) {
10385 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10386 << expr->getSourceRange();
10387 return ExprError();
John McCall31996342011-04-07 08:22:57 +000010388 }
10389
John McCall2d2e8702011-04-11 07:02:50 +000010390 ExprResult VisitCallExpr(CallExpr *call);
10391 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
10392
John McCall39439732011-04-09 22:50:59 +000010393 /// Rebuild an expression which simply semantically wraps another
10394 /// expression which it shares the type and value kind of.
10395 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10396 ExprResult subResult = Visit(expr->getSubExpr());
John McCall2979fe02011-04-12 00:42:48 +000010397 if (subResult.isInvalid()) return ExprError();
John McCall39439732011-04-09 22:50:59 +000010398 Expr *subExpr = subResult.take();
10399 expr->setSubExpr(subExpr);
10400 expr->setType(subExpr->getType());
10401 expr->setValueKind(subExpr->getValueKind());
10402 assert(expr->getObjectKind() == OK_Ordinary);
10403 return expr;
10404 }
John McCall31996342011-04-07 08:22:57 +000010405
John McCall39439732011-04-09 22:50:59 +000010406 ExprResult VisitParenExpr(ParenExpr *paren) {
10407 return rebuildSugarExpr(paren);
10408 }
10409
10410 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10411 return rebuildSugarExpr(op);
10412 }
10413
John McCall2979fe02011-04-12 00:42:48 +000010414 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10415 const PointerType *ptr = DestType->getAs<PointerType>();
10416 if (!ptr) {
10417 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
10418 << op->getSourceRange();
10419 return ExprError();
10420 }
10421 assert(op->getValueKind() == VK_RValue);
10422 assert(op->getObjectKind() == OK_Ordinary);
10423 op->setType(DestType);
10424
10425 // Build the sub-expression as if it were an object of the pointee type.
10426 DestType = ptr->getPointeeType();
10427 ExprResult subResult = Visit(op->getSubExpr());
10428 if (subResult.isInvalid()) return ExprError();
10429 op->setSubExpr(subResult.take());
10430 return op;
10431 }
10432
John McCall2d2e8702011-04-11 07:02:50 +000010433 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCall39439732011-04-09 22:50:59 +000010434
John McCall2979fe02011-04-12 00:42:48 +000010435 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCall39439732011-04-09 22:50:59 +000010436
John McCall2979fe02011-04-12 00:42:48 +000010437 ExprResult VisitMemberExpr(MemberExpr *mem) {
10438 return resolveDecl(mem, mem->getMemberDecl());
10439 }
John McCall39439732011-04-09 22:50:59 +000010440
10441 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall2d2e8702011-04-11 07:02:50 +000010442 return resolveDecl(ref, ref->getDecl());
John McCall31996342011-04-07 08:22:57 +000010443 }
10444 };
10445}
10446
John McCall2d2e8702011-04-11 07:02:50 +000010447/// Rebuilds a call expression which yielded __unknown_anytype.
10448ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
10449 Expr *callee = call->getCallee();
10450
10451 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +000010452 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +000010453 FK_FunctionPointer,
10454 FK_BlockPointer
10455 };
10456
10457 FnKind kind;
10458 QualType type = callee->getType();
John McCall4adb38c2011-04-27 00:36:17 +000010459 if (type == S.Context.BoundMemberTy) {
10460 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
10461 kind = FK_MemberFunction;
10462 type = Expr::findBoundMemberType(callee);
John McCall2d2e8702011-04-11 07:02:50 +000010463 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
10464 type = ptr->getPointeeType();
10465 kind = FK_FunctionPointer;
10466 } else {
10467 type = type->castAs<BlockPointerType>()->getPointeeType();
10468 kind = FK_BlockPointer;
10469 }
10470 const FunctionType *fnType = type->castAs<FunctionType>();
10471
10472 // Verify that this is a legal result type of a function.
10473 if (DestType->isArrayType() || DestType->isFunctionType()) {
10474 unsigned diagID = diag::err_func_returning_array_function;
10475 if (kind == FK_BlockPointer)
10476 diagID = diag::err_block_returning_array_function;
10477
10478 S.Diag(call->getExprLoc(), diagID)
10479 << DestType->isFunctionType() << DestType;
10480 return ExprError();
10481 }
10482
10483 // Otherwise, go ahead and set DestType as the call's result.
10484 call->setType(DestType.getNonLValueExprType(S.Context));
10485 call->setValueKind(Expr::getValueKindForType(DestType));
10486 assert(call->getObjectKind() == OK_Ordinary);
10487
10488 // Rebuild the function type, replacing the result type with DestType.
10489 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
10490 DestType = S.Context.getFunctionType(DestType,
10491 proto->arg_type_begin(),
10492 proto->getNumArgs(),
10493 proto->getExtProtoInfo());
10494 else
10495 DestType = S.Context.getFunctionNoProtoType(DestType,
10496 fnType->getExtInfo());
10497
10498 // Rebuild the appropriate pointer-to-function type.
10499 switch (kind) {
John McCall4adb38c2011-04-27 00:36:17 +000010500 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +000010501 // Nothing to do.
10502 break;
10503
10504 case FK_FunctionPointer:
10505 DestType = S.Context.getPointerType(DestType);
10506 break;
10507
10508 case FK_BlockPointer:
10509 DestType = S.Context.getBlockPointerType(DestType);
10510 break;
10511 }
10512
10513 // Finally, we can recurse.
10514 ExprResult calleeResult = Visit(callee);
10515 if (!calleeResult.isUsable()) return ExprError();
10516 call->setCallee(calleeResult.take());
10517
10518 // Bind a temporary if necessary.
10519 return S.MaybeBindToTemporary(call);
10520}
10521
10522ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall2979fe02011-04-12 00:42:48 +000010523 ObjCMethodDecl *method = msg->getMethodDecl();
10524 assert(method && "__unknown_anytype message without result type?");
John McCall2d2e8702011-04-11 07:02:50 +000010525
John McCall2979fe02011-04-12 00:42:48 +000010526 // Verify that this is a legal result type of a call.
10527 if (DestType->isArrayType() || DestType->isFunctionType()) {
10528 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
10529 << DestType->isFunctionType() << DestType;
10530 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010531 }
10532
John McCall2979fe02011-04-12 00:42:48 +000010533 assert(method->getResultType() == S.Context.UnknownAnyTy);
10534 method->setResultType(DestType);
10535
John McCall2d2e8702011-04-11 07:02:50 +000010536 // Change the type of the message.
John McCall2979fe02011-04-12 00:42:48 +000010537 msg->setType(DestType.getNonReferenceType());
10538 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000010539
John McCall2979fe02011-04-12 00:42:48 +000010540 return S.MaybeBindToTemporary(msg);
John McCall2d2e8702011-04-11 07:02:50 +000010541}
10542
10543ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall2979fe02011-04-12 00:42:48 +000010544 // The only case we should ever see here is a function-to-pointer decay.
John McCall2d2e8702011-04-11 07:02:50 +000010545 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall2d2e8702011-04-11 07:02:50 +000010546 assert(ice->getValueKind() == VK_RValue);
10547 assert(ice->getObjectKind() == OK_Ordinary);
10548
John McCall2979fe02011-04-12 00:42:48 +000010549 ice->setType(DestType);
10550
John McCall2d2e8702011-04-11 07:02:50 +000010551 // Rebuild the sub-expression as the pointee (function) type.
10552 DestType = DestType->castAs<PointerType>()->getPointeeType();
10553
10554 ExprResult result = Visit(ice->getSubExpr());
10555 if (!result.isUsable()) return ExprError();
10556
10557 ice->setSubExpr(result.take());
10558 return S.Owned(ice);
10559}
10560
John McCall2979fe02011-04-12 00:42:48 +000010561ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall2d2e8702011-04-11 07:02:50 +000010562 ExprValueKind valueKind = VK_LValue;
John McCall2d2e8702011-04-11 07:02:50 +000010563 QualType type = DestType;
10564
10565 // We know how to make this work for certain kinds of decls:
10566
10567 // - functions
John McCall2979fe02011-04-12 00:42:48 +000010568 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCall2d2e8702011-04-11 07:02:50 +000010569 // This is true because FunctionDecls must always have function
10570 // type, so we can't be resolving the entire thing at once.
10571 assert(type->isFunctionType());
10572
John McCall4adb38c2011-04-27 00:36:17 +000010573 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
10574 if (method->isInstance()) {
10575 valueKind = VK_RValue;
10576 type = S.Context.BoundMemberTy;
10577 }
10578
John McCall2d2e8702011-04-11 07:02:50 +000010579 // Function references aren't l-values in C.
10580 if (!S.getLangOptions().CPlusPlus)
10581 valueKind = VK_RValue;
10582
10583 // - variables
10584 } else if (isa<VarDecl>(decl)) {
John McCall2979fe02011-04-12 00:42:48 +000010585 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
10586 type = refTy->getPointeeType();
John McCall2d2e8702011-04-11 07:02:50 +000010587 } else if (type->isFunctionType()) {
John McCall2979fe02011-04-12 00:42:48 +000010588 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
10589 << decl << expr->getSourceRange();
10590 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010591 }
10592
10593 // - nothing else
10594 } else {
10595 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10596 << decl << expr->getSourceRange();
10597 return ExprError();
10598 }
10599
John McCall2979fe02011-04-12 00:42:48 +000010600 decl->setType(DestType);
10601 expr->setType(type);
10602 expr->setValueKind(valueKind);
10603 return S.Owned(expr);
John McCall2d2e8702011-04-11 07:02:50 +000010604}
10605
John McCall31996342011-04-07 08:22:57 +000010606/// Check a cast of an unknown-any type. We intentionally only
10607/// trigger this for C-style casts.
John Wiegley01296292011-04-08 18:41:53 +000010608ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
10609 Expr *castExpr, CastKind &castKind,
10610 ExprValueKind &VK, CXXCastPath &path) {
John McCall31996342011-04-07 08:22:57 +000010611 // Rewrite the casted expression from scratch.
John McCall39439732011-04-09 22:50:59 +000010612 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
10613 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000010614
John McCall39439732011-04-09 22:50:59 +000010615 castExpr = result.take();
10616 VK = castExpr->getValueKind();
10617 castKind = CK_NoOp;
10618
10619 return castExpr;
John McCall31996342011-04-07 08:22:57 +000010620}
10621
10622static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
10623 Expr *orig = e;
John McCall2d2e8702011-04-11 07:02:50 +000010624 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000010625 while (true) {
10626 e = e->IgnoreParenImpCasts();
John McCall2d2e8702011-04-11 07:02:50 +000010627 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall31996342011-04-07 08:22:57 +000010628 e = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000010629 diagID = diag::err_uncasted_call_of_unknown_any;
10630 } else {
John McCall31996342011-04-07 08:22:57 +000010631 break;
John McCall2d2e8702011-04-11 07:02:50 +000010632 }
John McCall31996342011-04-07 08:22:57 +000010633 }
10634
John McCall2d2e8702011-04-11 07:02:50 +000010635 SourceLocation loc;
10636 NamedDecl *d;
10637 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10638 loc = ref->getLocation();
10639 d = ref->getDecl();
10640 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
10641 loc = mem->getMemberLoc();
10642 d = mem->getMemberDecl();
10643 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
10644 diagID = diag::err_uncasted_call_of_unknown_any;
10645 loc = msg->getSelectorLoc();
10646 d = msg->getMethodDecl();
10647 assert(d && "unknown method returning __unknown_any?");
10648 } else {
10649 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10650 << e->getSourceRange();
10651 return ExprError();
10652 }
10653
10654 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000010655
10656 // Never recoverable.
10657 return ExprError();
10658}
10659
John McCall36e7fe32010-10-12 00:20:44 +000010660/// Check for operands with placeholder types and complain if found.
10661/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000010662ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +000010663 // Placeholder types are always *exactly* the appropriate builtin type.
10664 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +000010665
John McCall31996342011-04-07 08:22:57 +000010666 // Overloaded expressions.
10667 if (type == Context.OverloadTy)
10668 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010669 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +000010670 QualType(),
10671 diag::err_ovl_unresolvable);
10672
John McCall0009fcc2011-04-26 20:42:42 +000010673 // Bound member functions.
10674 if (type == Context.BoundMemberTy) {
10675 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
10676 << E->getSourceRange();
10677 return ExprError();
10678 }
10679
John McCall31996342011-04-07 08:22:57 +000010680 // Expressions of unknown type.
10681 if (type == Context.UnknownAnyTy)
10682 return diagnoseUnknownAnyExpr(*this, E);
10683
10684 assert(!type->isPlaceholderType());
10685 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +000010686}
Richard Trieu2c850c02011-04-21 21:44:26 +000010687
10688bool Sema::CheckCaseExpression(Expr *expr) {
10689 if (expr->isTypeDependent())
10690 return true;
10691 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
10692 return expr->getType()->isIntegralOrEnumerationType();
10693 return false;
10694}