blob: a44b4475ce8b74337d1adf83ef1562d79ea0ac3a [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
Douglas Gregor347e0f22011-05-21 19:26:31 +0000452 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000453 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000454 DiagRuntimeBehavior(E->getLocStart(), 0,
455 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
456 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000457 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000458
Douglas Gregor253cadf2011-05-21 16:27:21 +0000459 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()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000480 << CT)) {
481 // Turn this into a trap.
482 CXXScopeSpec SS;
483 UnqualifiedId Name;
484 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
485 E->getLocStart());
486 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
487 if (TrapFn.isInvalid())
488 return ExprError();
489
490 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
491 MultiExprArg(), E->getLocEnd());
492 if (Call.isInvalid())
493 return ExprError();
494
495 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
496 Call.get(), E);
497 if (Comma.isInvalid())
498 return ExprError();
499
500 E = Comma.get();
501 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000502 }
503
John Wiegley01296292011-04-08 18:41:53 +0000504 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000505}
506
Chris Lattner513165e2008-07-25 21:10:04 +0000507/// UsualArithmeticConversions - Performs various conversions that are common to
508/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000509/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000510/// responsible for emitting appropriate error diagnostics.
511/// FIXME: verify the conversion rules for "complex int" are consistent with
512/// GCC.
John Wiegley01296292011-04-08 18:41:53 +0000513QualType Sema::UsualArithmeticConversions(ExprResult &lhsExpr, ExprResult &rhsExpr,
Chris Lattner513165e2008-07-25 21:10:04 +0000514 bool isCompAssign) {
John Wiegley01296292011-04-08 18:41:53 +0000515 if (!isCompAssign) {
516 lhsExpr = UsualUnaryConversions(lhsExpr.take());
517 if (lhsExpr.isInvalid())
518 return QualType();
519 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000520
John Wiegley01296292011-04-08 18:41:53 +0000521 rhsExpr = UsualUnaryConversions(rhsExpr.take());
522 if (rhsExpr.isInvalid())
523 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000524
Mike Stump11289f42009-09-09 15:08:12 +0000525 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000526 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000527 QualType lhs =
John Wiegley01296292011-04-08 18:41:53 +0000528 Context.getCanonicalType(lhsExpr.get()->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000529 QualType rhs =
John Wiegley01296292011-04-08 18:41:53 +0000530 Context.getCanonicalType(rhsExpr.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000531
532 // If both types are identical, no conversion is needed.
533 if (lhs == rhs)
534 return lhs;
535
536 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
537 // The caller can deal with this (e.g. pointer + int).
538 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
539 return lhs;
540
John McCalld005ac92010-11-13 08:17:45 +0000541 // Apply unary and bitfield promotions to the LHS's type.
542 QualType lhs_unpromoted = lhs;
543 if (lhs->isPromotableIntegerType())
544 lhs = Context.getPromotedIntegerType(lhs);
John Wiegley01296292011-04-08 18:41:53 +0000545 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000546 if (!LHSBitfieldPromoteTy.isNull())
547 lhs = LHSBitfieldPromoteTy;
John McCalld005ac92010-11-13 08:17:45 +0000548 if (lhs != lhs_unpromoted && !isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000549 lhsExpr = ImpCastExprToType(lhsExpr.take(), lhs, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000550
John McCalld005ac92010-11-13 08:17:45 +0000551 // If both types are identical, no conversion is needed.
552 if (lhs == rhs)
553 return lhs;
554
555 // At this point, we have two different arithmetic types.
556
557 // Handle complex types first (C99 6.3.1.8p1).
558 bool LHSComplexFloat = lhs->isComplexType();
559 bool RHSComplexFloat = rhs->isComplexType();
560 if (LHSComplexFloat || RHSComplexFloat) {
561 // if we have an integer operand, the result is the complex type.
562
John McCallc5e62b42010-11-13 09:02:35 +0000563 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
564 if (rhs->isIntegerType()) {
565 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000566 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_IntegralToFloating);
567 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000568 } else {
569 assert(rhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000570 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000571 }
John McCalld005ac92010-11-13 08:17:45 +0000572 return lhs;
573 }
574
John McCallc5e62b42010-11-13 09:02:35 +0000575 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
576 if (!isCompAssign) {
577 // int -> float -> _Complex float
578 if (lhs->isIntegerType()) {
579 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000580 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_IntegralToFloating);
581 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000582 } else {
583 assert(lhs->isComplexIntegerType());
John Wiegley01296292011-04-08 18:41:53 +0000584 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexToFloatingComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000585 }
586 }
John McCalld005ac92010-11-13 08:17:45 +0000587 return rhs;
588 }
589
590 // This handles complex/complex, complex/float, or float/complex.
591 // When both operands are complex, the shorter operand is converted to the
592 // type of the longer, and that is the type of the result. This corresponds
593 // to what is done when combining two real floating-point operands.
594 // The fun begins when size promotion occur across type domains.
595 // From H&S 6.3.4: When one operand is complex and the other is a real
596 // floating-point type, the less precise type is converted, within it's
597 // real or complex domain, to the precision of the other type. For example,
598 // when combining a "long double" with a "double _Complex", the
599 // "double _Complex" is promoted to "long double _Complex".
600 int order = Context.getFloatingTypeOrder(lhs, rhs);
601
602 // If both are complex, just cast to the more precise type.
603 if (LHSComplexFloat && RHSComplexFloat) {
604 if (order > 0) {
605 // _Complex float -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000606 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000607 return lhs;
608
609 } else if (order < 0) {
610 // _Complex float -> _Complex double
611 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000612 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000613 return rhs;
614 }
615 return lhs;
616 }
617
618 // If just the LHS is complex, the RHS needs to be converted,
619 // and the LHS might need to be promoted.
620 if (LHSComplexFloat) {
621 if (order > 0) { // LHS is wider
622 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000623 QualType fp = cast<ComplexType>(lhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000624 rhsExpr = ImpCastExprToType(rhsExpr.take(), fp, CK_FloatingCast);
625 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000626 return lhs;
627 }
628
629 // RHS is at least as wide. Find its corresponding complex type.
630 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
631
632 // double -> _Complex double
John Wiegley01296292011-04-08 18:41:53 +0000633 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000634
635 // _Complex float -> _Complex double
636 if (!isCompAssign && order < 0)
John Wiegley01296292011-04-08 18:41:53 +0000637 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000638
639 return result;
640 }
641
642 // Just the RHS is complex, so the LHS needs to be converted
643 // and the RHS might need to be promoted.
644 assert(RHSComplexFloat);
645
646 if (order < 0) { // RHS is wider
647 // float -> _Complex double
John McCallc5e62b42010-11-13 09:02:35 +0000648 if (!isCompAssign) {
Argyrios Kyrtzidise84389b2011-01-18 18:49:33 +0000649 QualType fp = cast<ComplexType>(rhs)->getElementType();
John Wiegley01296292011-04-08 18:41:53 +0000650 lhsExpr = ImpCastExprToType(lhsExpr.take(), fp, CK_FloatingCast);
651 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingRealToComplex);
John McCallc5e62b42010-11-13 09:02:35 +0000652 }
John McCalld005ac92010-11-13 08:17:45 +0000653 return rhs;
654 }
655
656 // LHS is at least as wide. Find its corresponding complex type.
657 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
658
659 // double -> _Complex double
660 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000661 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000662
663 // _Complex float -> _Complex double
664 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +0000665 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000666
667 return result;
668 }
669
670 // Now handle "real" floating types (i.e. float, double, long double).
671 bool LHSFloat = lhs->isRealFloatingType();
672 bool RHSFloat = rhs->isRealFloatingType();
673 if (LHSFloat || RHSFloat) {
674 // If we have two real floating types, convert the smaller operand
675 // to the bigger result.
676 if (LHSFloat && RHSFloat) {
677 int order = Context.getFloatingTypeOrder(lhs, rhs);
678 if (order > 0) {
John Wiegley01296292011-04-08 18:41:53 +0000679 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000680 return lhs;
681 }
682
683 assert(order < 0 && "illegal float comparison");
684 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000685 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_FloatingCast);
John McCalld005ac92010-11-13 08:17:45 +0000686 return rhs;
687 }
688
689 // If we have an integer operand, the result is the real floating type.
690 if (LHSFloat) {
691 if (rhs->isIntegerType()) {
692 // Convert rhs to the lhs floating point type.
John Wiegley01296292011-04-08 18:41:53 +0000693 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000694 return lhs;
695 }
696
697 // Convert both sides to the appropriate complex float.
698 assert(rhs->isComplexIntegerType());
699 QualType result = Context.getComplexType(lhs);
700
701 // _Complex int -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000702 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000703
704 // float -> _Complex float
705 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000706 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000707
708 return result;
709 }
710
711 assert(RHSFloat);
712 if (lhs->isIntegerType()) {
713 // Convert lhs to the rhs floating point type.
714 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000715 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralToFloating);
John McCalld005ac92010-11-13 08:17:45 +0000716 return rhs;
717 }
718
719 // Convert both sides to the appropriate complex float.
720 assert(lhs->isComplexIntegerType());
721 QualType result = Context.getComplexType(rhs);
722
723 // _Complex int -> _Complex float
724 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000725 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralComplexToFloatingComplex);
John McCalld005ac92010-11-13 08:17:45 +0000726
727 // float -> _Complex float
John Wiegley01296292011-04-08 18:41:53 +0000728 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_FloatingRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000729
730 return result;
731 }
732
733 // Handle GCC complex int extension.
734 // FIXME: if the operands are (int, _Complex long), we currently
735 // don't promote the complex. Also, signedness?
736 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
737 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
738 if (lhsComplexInt && rhsComplexInt) {
739 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
740 rhsComplexInt->getElementType());
741 assert(order && "inequal types with equal element ordering");
742 if (order > 0) {
743 // _Complex int -> _Complex long
John Wiegley01296292011-04-08 18:41:53 +0000744 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000745 return lhs;
746 }
747
748 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000749 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralComplexCast);
John McCalld005ac92010-11-13 08:17:45 +0000750 return rhs;
751 } else if (lhsComplexInt) {
752 // int -> _Complex int
John Wiegley01296292011-04-08 18:41:53 +0000753 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000754 return lhs;
755 } else if (rhsComplexInt) {
756 // int -> _Complex int
757 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000758 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralRealToComplex);
John McCalld005ac92010-11-13 08:17:45 +0000759 return rhs;
760 }
761
762 // Finally, we have two differing integer types.
763 // The rules for this case are in C99 6.3.1.8
764 int compare = Context.getIntegerTypeOrder(lhs, rhs);
765 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
766 rhsSigned = rhs->hasSignedIntegerRepresentation();
767 if (lhsSigned == rhsSigned) {
768 // Same signedness; use the higher-ranked type
769 if (compare >= 0) {
John Wiegley01296292011-04-08 18:41:53 +0000770 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000771 return lhs;
772 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000773 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000774 return rhs;
775 } else if (compare != (lhsSigned ? 1 : -1)) {
776 // The unsigned type has greater than or equal rank to the
777 // signed type, so use the unsigned type
778 if (rhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000779 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000780 return lhs;
781 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000782 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000783 return rhs;
784 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
785 // The two types are different widths; if we are here, that
786 // means the signed type is larger than the unsigned type, so
787 // use the signed type.
788 if (lhsSigned) {
John Wiegley01296292011-04-08 18:41:53 +0000789 rhsExpr = ImpCastExprToType(rhsExpr.take(), lhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000790 return lhs;
791 } else if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000792 lhsExpr = ImpCastExprToType(lhsExpr.take(), rhs, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000793 return rhs;
794 } else {
795 // The signed type is higher-ranked than the unsigned type,
796 // but isn't actually any bigger (like unsigned int and long
797 // on most 32-bit systems). Use the unsigned type corresponding
798 // to the signed type.
799 QualType result =
800 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
John Wiegley01296292011-04-08 18:41:53 +0000801 rhsExpr = ImpCastExprToType(rhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000802 if (!isCompAssign)
John Wiegley01296292011-04-08 18:41:53 +0000803 lhsExpr = ImpCastExprToType(lhsExpr.take(), result, CK_IntegralCast);
John McCalld005ac92010-11-13 08:17:45 +0000804 return result;
805 }
Douglas Gregora11693b2008-11-12 17:17:38 +0000806}
807
Chris Lattner513165e2008-07-25 21:10:04 +0000808//===----------------------------------------------------------------------===//
809// Semantic Analysis for various Expression Types
810//===----------------------------------------------------------------------===//
811
812
Peter Collingbourne91147592011-04-15 00:35:48 +0000813ExprResult
814Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
815 SourceLocation DefaultLoc,
816 SourceLocation RParenLoc,
817 Expr *ControllingExpr,
818 MultiTypeArg types,
819 MultiExprArg exprs) {
820 unsigned NumAssocs = types.size();
821 assert(NumAssocs == exprs.size());
822
823 ParsedType *ParsedTypes = types.release();
824 Expr **Exprs = exprs.release();
825
826 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
827 for (unsigned i = 0; i < NumAssocs; ++i) {
828 if (ParsedTypes[i])
829 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
830 else
831 Types[i] = 0;
832 }
833
834 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
835 ControllingExpr, Types, Exprs,
836 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000837 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000838 return ER;
839}
840
841ExprResult
842Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
843 SourceLocation DefaultLoc,
844 SourceLocation RParenLoc,
845 Expr *ControllingExpr,
846 TypeSourceInfo **Types,
847 Expr **Exprs,
848 unsigned NumAssocs) {
849 bool TypeErrorFound = false,
850 IsResultDependent = ControllingExpr->isTypeDependent(),
851 ContainsUnexpandedParameterPack
852 = ControllingExpr->containsUnexpandedParameterPack();
853
854 for (unsigned i = 0; i < NumAssocs; ++i) {
855 if (Exprs[i]->containsUnexpandedParameterPack())
856 ContainsUnexpandedParameterPack = true;
857
858 if (Types[i]) {
859 if (Types[i]->getType()->containsUnexpandedParameterPack())
860 ContainsUnexpandedParameterPack = true;
861
862 if (Types[i]->getType()->isDependentType()) {
863 IsResultDependent = true;
864 } else {
865 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
866 // complete object type other than a variably modified type."
867 unsigned D = 0;
868 if (Types[i]->getType()->isIncompleteType())
869 D = diag::err_assoc_type_incomplete;
870 else if (!Types[i]->getType()->isObjectType())
871 D = diag::err_assoc_type_nonobject;
872 else if (Types[i]->getType()->isVariablyModifiedType())
873 D = diag::err_assoc_type_variably_modified;
874
875 if (D != 0) {
876 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
877 << Types[i]->getTypeLoc().getSourceRange()
878 << Types[i]->getType();
879 TypeErrorFound = true;
880 }
881
882 // C1X 6.5.1.1p2 "No two generic associations in the same generic
883 // selection shall specify compatible types."
884 for (unsigned j = i+1; j < NumAssocs; ++j)
885 if (Types[j] && !Types[j]->getType()->isDependentType() &&
886 Context.typesAreCompatible(Types[i]->getType(),
887 Types[j]->getType())) {
888 Diag(Types[j]->getTypeLoc().getBeginLoc(),
889 diag::err_assoc_compatible_types)
890 << Types[j]->getTypeLoc().getSourceRange()
891 << Types[j]->getType()
892 << Types[i]->getType();
893 Diag(Types[i]->getTypeLoc().getBeginLoc(),
894 diag::note_compat_assoc)
895 << Types[i]->getTypeLoc().getSourceRange()
896 << Types[i]->getType();
897 TypeErrorFound = true;
898 }
899 }
900 }
901 }
902 if (TypeErrorFound)
903 return ExprError();
904
905 // If we determined that the generic selection is result-dependent, don't
906 // try to compute the result expression.
907 if (IsResultDependent)
908 return Owned(new (Context) GenericSelectionExpr(
909 Context, KeyLoc, ControllingExpr,
910 Types, Exprs, NumAssocs, DefaultLoc,
911 RParenLoc, ContainsUnexpandedParameterPack));
912
913 llvm::SmallVector<unsigned, 1> CompatIndices;
914 unsigned DefaultIndex = -1U;
915 for (unsigned i = 0; i < NumAssocs; ++i) {
916 if (!Types[i])
917 DefaultIndex = i;
918 else if (Context.typesAreCompatible(ControllingExpr->getType(),
919 Types[i]->getType()))
920 CompatIndices.push_back(i);
921 }
922
923 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
924 // type compatible with at most one of the types named in its generic
925 // association list."
926 if (CompatIndices.size() > 1) {
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_multi_match)
931 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
932 << (unsigned) CompatIndices.size();
933 for (llvm::SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
934 E = CompatIndices.end(); I != E; ++I) {
935 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
936 diag::note_compat_assoc)
937 << Types[*I]->getTypeLoc().getSourceRange()
938 << Types[*I]->getType();
939 }
940 return ExprError();
941 }
942
943 // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
944 // its controlling expression shall have type compatible with exactly one of
945 // the types named in its generic association list."
946 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
947 // We strip parens here because the controlling expression is typically
948 // parenthesized in macro definitions.
949 ControllingExpr = ControllingExpr->IgnoreParens();
950 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
951 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
952 return ExprError();
953 }
954
955 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
956 // type name that is compatible with the type of the controlling expression,
957 // then the result expression of the generic selection is the expression
958 // in that generic association. Otherwise, the result expression of the
959 // generic selection is the expression in the default generic association."
960 unsigned ResultIndex =
961 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
962
963 return Owned(new (Context) GenericSelectionExpr(
964 Context, KeyLoc, ControllingExpr,
965 Types, Exprs, NumAssocs, DefaultLoc,
966 RParenLoc, ContainsUnexpandedParameterPack,
967 ResultIndex));
968}
969
Steve Naroff83895f72007-09-16 03:34:24 +0000970/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000971/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
972/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
973/// multiple tokens. However, the common case is that StringToks points to one
974/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000975///
John McCalldadc5752010-08-24 06:29:42 +0000976ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +0000977Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000978 assert(NumStringToks && "Must have at least one string!");
979
Chris Lattner8a24e582009-01-16 18:51:42 +0000980 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000981 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000982 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000983
Chris Lattner23b7eb62007-06-15 23:05:46 +0000984 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000985 for (unsigned i = 0; i != NumStringToks; ++i)
986 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000987
Chris Lattner36fc8792008-02-11 00:02:17 +0000988 QualType StrTy = Context.CharTy;
Anders Carlsson6b06e182011-04-06 18:42:48 +0000989 if (Literal.AnyWide)
990 StrTy = Context.getWCharType();
991 else if (Literal.Pascal)
992 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000993
994 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +0000995 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000996 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000997
Chris Lattner36fc8792008-02-11 00:02:17 +0000998 // Get an array type for the string, according to C99 6.4.5. This includes
999 // the nul terminator character as well as the string length for pascal
1000 // strings.
1001 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001002 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001003 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001004
Chris Lattner5b183d82006-11-10 05:03:26 +00001005 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Alexis Hunt3b791862010-08-30 17:47:05 +00001006 return Owned(StringLiteral::Create(Context, Literal.GetString(),
1007 Literal.GetStringLength(),
Anders Carlsson75245402011-04-14 00:40:03 +00001008 Literal.AnyWide, Literal.Pascal, StrTy,
Alexis Hunt3b791862010-08-30 17:47:05 +00001009 &StringTokLocs[0],
1010 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +00001011}
1012
John McCallc63de662011-02-02 13:00:07 +00001013enum CaptureResult {
1014 /// No capture is required.
1015 CR_NoCapture,
1016
1017 /// A capture is required.
1018 CR_Capture,
1019
John McCall351762c2011-02-07 10:33:21 +00001020 /// A by-ref capture is required.
1021 CR_CaptureByRef,
1022
John McCallc63de662011-02-02 13:00:07 +00001023 /// An error occurred when trying to capture the given variable.
1024 CR_Error
1025};
1026
1027/// Diagnose an uncapturable value reference.
Chris Lattner2a9d9892008-10-20 05:16:36 +00001028///
John McCallc63de662011-02-02 13:00:07 +00001029/// \param var - the variable referenced
1030/// \param DC - the context which we couldn't capture through
1031static CaptureResult
John McCall351762c2011-02-07 10:33:21 +00001032diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001033 VarDecl *var, DeclContext *DC) {
1034 switch (S.ExprEvalContexts.back().Context) {
1035 case Sema::Unevaluated:
1036 // The argument will never be evaluated, so don't complain.
1037 return CR_NoCapture;
Mike Stump11289f42009-09-09 15:08:12 +00001038
John McCallc63de662011-02-02 13:00:07 +00001039 case Sema::PotentiallyEvaluated:
1040 case Sema::PotentiallyEvaluatedIfUsed:
1041 break;
Chris Lattner2a9d9892008-10-20 05:16:36 +00001042
John McCallc63de662011-02-02 13:00:07 +00001043 case Sema::PotentiallyPotentiallyEvaluated:
1044 // FIXME: delay these!
1045 break;
Chris Lattner497d7b02009-04-21 22:26:47 +00001046 }
Mike Stump11289f42009-09-09 15:08:12 +00001047
John McCallc63de662011-02-02 13:00:07 +00001048 // Don't diagnose about capture if we're not actually in code right
1049 // now; in general, there are more appropriate places that will
1050 // diagnose this.
1051 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1052
John McCall92d627e2011-03-22 23:15:50 +00001053 // Certain madnesses can happen with parameter declarations, which
1054 // we want to ignore.
1055 if (isa<ParmVarDecl>(var)) {
1056 // - If the parameter still belongs to the translation unit, then
1057 // we're actually just using one parameter in the declaration of
1058 // the next. This is useful in e.g. VLAs.
1059 if (isa<TranslationUnitDecl>(var->getDeclContext()))
1060 return CR_NoCapture;
1061
1062 // - This particular madness can happen in ill-formed default
1063 // arguments; claim it's okay and let downstream code handle it.
1064 if (S.CurContext == var->getDeclContext()->getParent())
1065 return CR_NoCapture;
1066 }
John McCallc63de662011-02-02 13:00:07 +00001067
1068 DeclarationName functionName;
1069 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1070 functionName = fn->getDeclName();
1071 // FIXME: variable from enclosing block that we couldn't capture from!
1072
1073 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1074 << var->getIdentifier() << functionName;
1075 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1076 << var->getIdentifier();
1077
1078 return CR_Error;
Mike Stump11289f42009-09-09 15:08:12 +00001079}
1080
John McCall351762c2011-02-07 10:33:21 +00001081/// There is a well-formed capture at a particular scope level;
1082/// propagate it through all the nested blocks.
1083static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
1084 const BlockDecl::Capture &capture) {
1085 VarDecl *var = capture.getVariable();
1086
1087 // Update all the inner blocks with the capture information.
1088 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
1089 i != e; ++i) {
1090 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1091 innerBlock->Captures.push_back(
1092 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
1093 /*nested*/ true, capture.getCopyExpr()));
1094 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1095 }
1096
1097 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1098}
1099
1100/// shouldCaptureValueReference - Determine if a reference to the
John McCallc63de662011-02-02 13:00:07 +00001101/// given value in the current context requires a variable capture.
1102///
1103/// This also keeps the captures set in the BlockScopeInfo records
1104/// up-to-date.
John McCall351762c2011-02-07 10:33:21 +00001105static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
John McCallc63de662011-02-02 13:00:07 +00001106 ValueDecl *value) {
1107 // Only variables ever require capture.
1108 VarDecl *var = dyn_cast<VarDecl>(value);
John McCallf4cd4f92011-02-09 01:13:10 +00001109 if (!var) return CR_NoCapture;
John McCallc63de662011-02-02 13:00:07 +00001110
1111 // Fast path: variables from the current context never require capture.
1112 DeclContext *DC = S.CurContext;
1113 if (var->getDeclContext() == DC) return CR_NoCapture;
1114
1115 // Only variables with local storage require capture.
1116 // FIXME: What about 'const' variables in C++?
1117 if (!var->hasLocalStorage()) return CR_NoCapture;
1118
1119 // Otherwise, we need to capture.
1120
1121 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
John McCallc63de662011-02-02 13:00:07 +00001122 do {
1123 // Only blocks (and eventually C++0x closures) can capture; other
1124 // scopes don't work.
1125 if (!isa<BlockDecl>(DC))
John McCall351762c2011-02-07 10:33:21 +00001126 return diagnoseUncapturableValueReference(S, loc, var, DC);
John McCallc63de662011-02-02 13:00:07 +00001127
1128 BlockScopeInfo *blockScope =
1129 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1130 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1131
John McCall351762c2011-02-07 10:33:21 +00001132 // Check whether we've already captured it in this block. If so,
1133 // we're done.
1134 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1135 return propagateCapture(S, functionScopesIndex,
1136 blockScope->Captures[indexPlus1 - 1]);
John McCallc63de662011-02-02 13:00:07 +00001137
1138 functionScopesIndex--;
1139 DC = cast<BlockDecl>(DC)->getDeclContext();
1140 } while (var->getDeclContext() != DC);
1141
John McCall351762c2011-02-07 10:33:21 +00001142 // Okay, we descended all the way to the block that defines the variable.
1143 // Actually try to capture it.
1144 QualType type = var->getType();
1145
1146 // Prohibit variably-modified types.
1147 if (type->isVariablyModifiedType()) {
1148 S.Diag(loc, diag::err_ref_vm_type);
1149 S.Diag(var->getLocation(), diag::note_declared_at);
1150 return CR_Error;
1151 }
1152
1153 // Prohibit arrays, even in __block variables, but not references to
1154 // them.
1155 if (type->isArrayType()) {
1156 S.Diag(loc, diag::err_ref_array_type);
1157 S.Diag(var->getLocation(), diag::note_declared_at);
1158 return CR_Error;
1159 }
1160
1161 S.MarkDeclarationReferenced(loc, var);
1162
1163 // The BlocksAttr indicates the variable is bound by-reference.
1164 bool byRef = var->hasAttr<BlocksAttr>();
1165
1166 // Build a copy expression.
1167 Expr *copyExpr = 0;
John McCalla85af562011-04-28 02:15:35 +00001168 const RecordType *rtype;
1169 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1170 (rtype = type->getAs<RecordType>())) {
1171
1172 // The capture logic needs the destructor, so make sure we mark it.
1173 // Usually this is unnecessary because most local variables have
1174 // their destructors marked at declaration time, but parameters are
1175 // an exception because it's technically only the call site that
1176 // actually requires the destructor.
1177 if (isa<ParmVarDecl>(var))
1178 S.FinalizeVarWithDestructor(var, rtype);
1179
John McCall351762c2011-02-07 10:33:21 +00001180 // According to the blocks spec, the capture of a variable from
1181 // the stack requires a const copy constructor. This is not true
1182 // of the copy/move done to move a __block variable to the heap.
1183 type.addConst();
1184
1185 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1186 ExprResult result =
1187 S.PerformCopyInitialization(
1188 InitializedEntity::InitializeBlock(var->getLocation(),
1189 type, false),
1190 loc, S.Owned(declRef));
1191
1192 // Build a full-expression copy expression if initialization
1193 // succeeded and used a non-trivial constructor. Recover from
1194 // errors by pretending that the copy isn't necessary.
1195 if (!result.isInvalid() &&
1196 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1197 result = S.MaybeCreateExprWithCleanups(result);
1198 copyExpr = result.take();
1199 }
1200 }
1201
1202 // We're currently at the declarer; go back to the closure.
1203 functionScopesIndex++;
1204 BlockScopeInfo *blockScope =
1205 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1206
1207 // Build a valid capture in this scope.
1208 blockScope->Captures.push_back(
1209 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1210 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1211
1212 // Propagate that to inner captures if necessary.
1213 return propagateCapture(S, functionScopesIndex,
1214 blockScope->Captures.back());
1215}
1216
1217static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
1218 const DeclarationNameInfo &NameInfo,
1219 bool byRef) {
1220 assert(isa<VarDecl>(vd) && "capturing non-variable");
1221
1222 VarDecl *var = cast<VarDecl>(vd);
1223 assert(var->hasLocalStorage() && "capturing non-local");
1224 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1225
1226 QualType exprType = var->getType().getNonReferenceType();
1227
1228 BlockDeclRefExpr *BDRE;
1229 if (!byRef) {
1230 // The variable will be bound by copy; make it const within the
1231 // closure, but record that this was done in the expression.
1232 bool constAdded = !exprType.isConstQualified();
1233 exprType.addConst();
1234
1235 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1236 NameInfo.getLoc(), false,
1237 constAdded);
1238 } else {
1239 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1240 NameInfo.getLoc(), true);
1241 }
1242
1243 return S.Owned(BDRE);
John McCallc63de662011-02-02 13:00:07 +00001244}
Chris Lattner2a9d9892008-10-20 05:16:36 +00001245
John McCalldadc5752010-08-24 06:29:42 +00001246ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001247Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001248 SourceLocation Loc,
1249 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001250 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001251 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001252}
1253
John McCallf4cd4f92011-02-09 01:13:10 +00001254/// BuildDeclRefExpr - Build an expression that references a
1255/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001256ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001257Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001258 const DeclarationNameInfo &NameInfo,
1259 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001260 MarkDeclarationReferenced(NameInfo.getLoc(), D);
Mike Stump11289f42009-09-09 15:08:12 +00001261
John McCall086a4642010-11-24 05:12:34 +00001262 Expr *E = DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00001263 SS? SS->getWithLocInContext(Context)
1264 : NestedNameSpecifierLoc(),
John McCall086a4642010-11-24 05:12:34 +00001265 D, NameInfo, Ty, VK);
1266
1267 // Just in case we're building an illegal pointer-to-member.
1268 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
1269 E->setObjectKind(OK_BitField);
1270
1271 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001272}
1273
John McCallfeb624a2010-11-23 20:48:44 +00001274static ExprResult
1275BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1276 const CXXScopeSpec &SS, FieldDecl *Field,
1277 DeclAccessPair FoundDecl,
1278 const DeclarationNameInfo &MemberNameInfo);
1279
John McCalldadc5752010-08-24 06:29:42 +00001280ExprResult
John McCallf3a88602011-02-03 08:15:49 +00001281Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
1282 SourceLocation loc,
1283 IndirectFieldDecl *indirectField,
1284 Expr *baseObjectExpr,
1285 SourceLocation opLoc) {
1286 // First, build the expression that refers to the base object.
1287
1288 bool baseObjectIsPointer = false;
1289 Qualifiers baseQuals;
1290
1291 // Case 1: the base of the indirect field is not a field.
1292 VarDecl *baseVariable = indirectField->getVarDecl();
Douglas Gregore10f36d2011-02-18 02:44:58 +00001293 CXXScopeSpec EmptySS;
John McCallf3a88602011-02-03 08:15:49 +00001294 if (baseVariable) {
1295 assert(baseVariable->getType()->isRecordType());
1296
1297 // In principle we could have a member access expression that
1298 // accesses an anonymous struct/union that's a static member of
1299 // the base object's class. However, under the current standard,
1300 // static data members cannot be anonymous structs or unions.
1301 // Supporting this is as easy as building a MemberExpr here.
1302 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1303
1304 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1305
1306 ExprResult result =
Douglas Gregore10f36d2011-02-18 02:44:58 +00001307 BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
John McCallf3a88602011-02-03 08:15:49 +00001308 if (result.isInvalid()) return ExprError();
1309
1310 baseObjectExpr = result.take();
1311 baseObjectIsPointer = false;
1312 baseQuals = baseObjectExpr->getType().getQualifiers();
1313
1314 // Case 2: the base of the indirect field is a field and the user
1315 // wrote a member expression.
1316 } else if (baseObjectExpr) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001317 // The caller provided the base object expression. Determine
1318 // whether its a pointer and whether it adds any qualifiers to the
1319 // anonymous struct/union fields we're looking into.
John McCallf3a88602011-02-03 08:15:49 +00001320 QualType objectType = baseObjectExpr->getType();
1321
1322 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1323 baseObjectIsPointer = true;
1324 objectType = ptr->getPointeeType();
1325 } else {
1326 baseObjectIsPointer = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001327 }
John McCallf3a88602011-02-03 08:15:49 +00001328 baseQuals = objectType.getQualifiers();
1329
1330 // Case 3: the base of the indirect field is a field and we should
1331 // build an implicit member access.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001332 } else {
1333 // We've found a member of an anonymous struct/union that is
1334 // inside a non-anonymous struct/union, so in a well-formed
1335 // program our base object expression is "this".
Richard Smith938f40b2011-06-11 17:19:42 +00001336 QualType ThisTy = getAndCaptureCurrentThisType();
1337 if (ThisTy.isNull()) {
John McCallf3a88602011-02-03 08:15:49 +00001338 Diag(loc, diag::err_invalid_member_use_in_static_method)
1339 << indirectField->getDeclName();
1340 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001341 }
1342
John McCallf3a88602011-02-03 08:15:49 +00001343 // Our base object expression is "this".
1344 baseObjectExpr =
Richard Smith938f40b2011-06-11 17:19:42 +00001345 new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
John McCallf3a88602011-02-03 08:15:49 +00001346 baseObjectIsPointer = true;
Richard Smith938f40b2011-06-11 17:19:42 +00001347 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001348 }
1349
1350 // Build the implicit member references to the field of the
1351 // anonymous struct/union.
John McCallf3a88602011-02-03 08:15:49 +00001352 Expr *result = baseObjectExpr;
1353 IndirectFieldDecl::chain_iterator
1354 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
John McCallfeb624a2010-11-23 20:48:44 +00001355
John McCallf3a88602011-02-03 08:15:49 +00001356 // Build the first member access in the chain with full information.
1357 if (!baseVariable) {
1358 FieldDecl *field = cast<FieldDecl>(*FI);
John McCallfeb624a2010-11-23 20:48:44 +00001359
John McCallf3a88602011-02-03 08:15:49 +00001360 // FIXME: use the real found-decl info!
1361 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCall8ccfcb52009-09-24 19:53:00 +00001362
John McCallf3a88602011-02-03 08:15:49 +00001363 // Make a nameInfo that properly uses the anonymous name.
1364 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
John McCall8ccfcb52009-09-24 19:53:00 +00001365
John McCallf3a88602011-02-03 08:15:49 +00001366 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001367 EmptySS, field, foundDecl,
John McCallf3a88602011-02-03 08:15:49 +00001368 memberNameInfo).take();
1369 baseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +00001370
John McCallf3a88602011-02-03 08:15:49 +00001371 // FIXME: check qualified member access
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001372 }
1373
John McCallf3a88602011-02-03 08:15:49 +00001374 // In all cases, we should now skip the first declaration in the chain.
1375 ++FI;
1376
Douglas Gregore10f36d2011-02-18 02:44:58 +00001377 while (FI != FEnd) {
1378 FieldDecl *field = cast<FieldDecl>(*FI++);
John McCallf3a88602011-02-03 08:15:49 +00001379
1380 // FIXME: these are somewhat meaningless
1381 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1382 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
John McCallf3a88602011-02-03 08:15:49 +00001383
1384 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Douglas Gregore10f36d2011-02-18 02:44:58 +00001385 (FI == FEnd? SS : EmptySS), field,
1386 foundDecl, memberNameInfo)
John McCallf3a88602011-02-03 08:15:49 +00001387 .take();
1388 }
1389
1390 return Owned(result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001391}
1392
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001393/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001394/// possibly a list of template arguments.
1395///
1396/// If this produces template arguments, it is permitted to call
1397/// DecomposeTemplateName.
1398///
1399/// This actually loses a lot of source location information for
1400/// non-standard name kinds; we should consider preserving that in
1401/// some way.
1402static void DecomposeUnqualifiedId(Sema &SemaRef,
1403 const UnqualifiedId &Id,
1404 TemplateArgumentListInfo &Buffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001405 DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00001406 const TemplateArgumentListInfo *&TemplateArgs) {
1407 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1408 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1409 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1410
1411 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1412 Id.TemplateId->getTemplateArgs(),
1413 Id.TemplateId->NumArgs);
1414 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1415 TemplateArgsPtr.release();
1416
John McCall3e56fd42010-08-23 07:28:44 +00001417 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001418 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1419 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001420 TemplateArgs = &Buffer;
1421 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001422 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001423 TemplateArgs = 0;
1424 }
1425}
1426
John McCall2d74de92009-12-01 22:10:20 +00001427/// Determines if the given class is provably not derived from all of
1428/// the prospective base classes.
1429static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1430 CXXRecordDecl *Record,
1431 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +00001432 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +00001433 return false;
1434
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001435 RecordDecl *RD = Record->getDefinition();
John McCalla6d407c2009-12-01 22:28:41 +00001436 if (!RD) return false;
1437 Record = cast<CXXRecordDecl>(RD);
1438
John McCall2d74de92009-12-01 22:10:20 +00001439 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1440 E = Record->bases_end(); I != E; ++I) {
1441 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1442 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1443 if (!BaseRT) return false;
1444
1445 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +00001446 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1447 return false;
1448 }
1449
1450 return true;
1451}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001452
John McCall2d74de92009-12-01 22:10:20 +00001453enum IMAKind {
1454 /// The reference is definitely not an instance member access.
1455 IMA_Static,
1456
1457 /// The reference may be an implicit instance member access.
1458 IMA_Mixed,
1459
1460 /// The reference may be to an instance member, but it is invalid if
1461 /// so, because the context is not an instance method.
1462 IMA_Mixed_StaticContext,
1463
1464 /// The reference may be to an instance member, but it is invalid if
1465 /// so, because the context is from an unrelated class.
1466 IMA_Mixed_Unrelated,
1467
1468 /// The reference is definitely an implicit instance member access.
1469 IMA_Instance,
1470
1471 /// The reference may be to an unresolved using declaration.
1472 IMA_Unresolved,
1473
1474 /// The reference may be to an unresolved using declaration and the
1475 /// context is not an instance method.
1476 IMA_Unresolved_StaticContext,
1477
John McCall2d74de92009-12-01 22:10:20 +00001478 /// All possible referrents are instance members and the current
1479 /// context is not an instance method.
1480 IMA_Error_StaticContext,
1481
1482 /// All possible referrents are instance members of an unrelated
1483 /// class.
1484 IMA_Error_Unrelated
1485};
1486
1487/// The given lookup names class member(s) and is not being used for
1488/// an address-of-member expression. Classify the type of access
1489/// according to whether it's possible that this reference names an
1490/// instance member. This is best-effort; it is okay to
1491/// conservatively answer "yes", in which case some errors will simply
1492/// not be caught until template-instantiation.
1493static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
Richard Smith938f40b2011-06-11 17:19:42 +00001494 Scope *CurScope,
John McCall2d74de92009-12-01 22:10:20 +00001495 const LookupResult &R) {
John McCall57500772009-12-16 12:17:52 +00001496 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCall2d74de92009-12-01 22:10:20 +00001497
John McCall87fe5d52010-05-20 01:18:31 +00001498 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
Richard Smith938f40b2011-06-11 17:19:42 +00001499
John McCall2d74de92009-12-01 22:10:20 +00001500 bool isStaticContext =
John McCall87fe5d52010-05-20 01:18:31 +00001501 (!isa<CXXMethodDecl>(DC) ||
1502 cast<CXXMethodDecl>(DC)->isStatic());
John McCall2d74de92009-12-01 22:10:20 +00001503
Richard Smith938f40b2011-06-11 17:19:42 +00001504 // C++0x [expr.prim]p4:
1505 // Otherwise, if a member-declarator declares a non-static data member
1506 // of a class X, the expression this is a prvalue of type "pointer to X"
1507 // within the optional brace-or-equal-initializer.
1508 if (CurScope->getFlags() & Scope::ThisScope)
1509 isStaticContext = false;
1510
John McCall2d74de92009-12-01 22:10:20 +00001511 if (R.isUnresolvableResult())
1512 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1513
1514 // Collect all the declaring classes of instance members we find.
1515 bool hasNonInstance = false;
Sebastian Redl34620312010-11-26 16:28:07 +00001516 bool hasField = false;
John McCall2d74de92009-12-01 22:10:20 +00001517 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1518 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCalla8ae2222010-04-06 21:38:20 +00001519 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00001520
John McCalla8ae2222010-04-06 21:38:20 +00001521 if (D->isCXXInstanceMember()) {
Sebastian Redl34620312010-11-26 16:28:07 +00001522 if (dyn_cast<FieldDecl>(D))
1523 hasField = true;
1524
John McCall2d74de92009-12-01 22:10:20 +00001525 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
John McCall2d74de92009-12-01 22:10:20 +00001526 Classes.insert(R->getCanonicalDecl());
1527 }
1528 else
1529 hasNonInstance = true;
1530 }
1531
1532 // If we didn't find any instance members, it can't be an implicit
1533 // member reference.
1534 if (Classes.empty())
1535 return IMA_Static;
1536
1537 // If the current context is not an instance method, it can't be
1538 // an implicit member reference.
Sebastian Redl34620312010-11-26 16:28:07 +00001539 if (isStaticContext) {
1540 if (hasNonInstance)
1541 return IMA_Mixed_StaticContext;
1542
1543 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1544 // C++0x [expr.prim.general]p10:
1545 // An id-expression that denotes a non-static data member or non-static
1546 // member function of a class can only be used:
1547 // (...)
1548 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1549 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1550 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1551 if (isUnevaluatedExpression)
1552 return IMA_Mixed_StaticContext;
1553 }
1554
1555 return IMA_Error_StaticContext;
1556 }
John McCall2d74de92009-12-01 22:10:20 +00001557
Richard Smith938f40b2011-06-11 17:19:42 +00001558 CXXRecordDecl *contextClass;
1559 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
1560 contextClass = MD->getParent()->getCanonicalDecl();
1561 else
1562 contextClass = cast<CXXRecordDecl>(DC);
Argyrios Kyrtzidis36e4ae32011-04-14 00:46:47 +00001563
1564 // [class.mfct.non-static]p3:
1565 // ...is used in the body of a non-static member function of class X,
1566 // if name lookup (3.4.1) resolves the name in the id-expression to a
1567 // non-static non-type member of some class C [...]
1568 // ...if C is not X or a base class of X, the class member access expression
1569 // is ill-formed.
1570 if (R.getNamingClass() &&
1571 contextClass != R.getNamingClass()->getCanonicalDecl() &&
1572 contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
1573 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1574
John McCall2d74de92009-12-01 22:10:20 +00001575 // If we can prove that the current context is unrelated to all the
1576 // declaring classes, it can't be an implicit member reference (in
1577 // which case it's an error if any of those members are selected).
Argyrios Kyrtzidis36e4ae32011-04-14 00:46:47 +00001578 if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
John McCall2d74de92009-12-01 22:10:20 +00001579 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1580
1581 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1582}
1583
1584/// Diagnose a reference to a field with no object available.
1585static void DiagnoseInstanceReference(Sema &SemaRef,
1586 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00001587 NamedDecl *rep,
1588 const DeclarationNameInfo &nameInfo) {
1589 SourceLocation Loc = nameInfo.getLoc();
John McCall2d74de92009-12-01 22:10:20 +00001590 SourceRange Range(Loc);
1591 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1592
John McCallf3a88602011-02-03 08:15:49 +00001593 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
John McCall2d74de92009-12-01 22:10:20 +00001594 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1595 if (MD->isStatic()) {
1596 // "invalid use of member 'x' in static member function"
1597 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
John McCallf3a88602011-02-03 08:15:49 +00001598 << Range << nameInfo.getName();
John McCall2d74de92009-12-01 22:10:20 +00001599 return;
1600 }
1601 }
1602
1603 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
John McCallf3a88602011-02-03 08:15:49 +00001604 << nameInfo.getName() << Range;
John McCall2d74de92009-12-01 22:10:20 +00001605 return;
1606 }
1607
1608 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +00001609}
1610
John McCalld681c392009-12-16 08:11:27 +00001611/// Diagnose an empty lookup.
1612///
1613/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001614bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1615 CorrectTypoContext CTC) {
John McCalld681c392009-12-16 08:11:27 +00001616 DeclarationName Name = R.getLookupName();
1617
John McCalld681c392009-12-16 08:11:27 +00001618 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001619 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001620 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1621 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001622 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001623 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001624 diagnostic_suggest = diag::err_undeclared_use_suggest;
1625 }
John McCalld681c392009-12-16 08:11:27 +00001626
Douglas Gregor598b08f2009-12-31 05:20:13 +00001627 // If the original lookup was an unqualified lookup, fake an
1628 // unqualified lookup. This is useful when (for example) the
1629 // original lookup would not have found something because it was a
1630 // dependent name.
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001631 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001632 DC; DC = DC->getParent()) {
John McCalld681c392009-12-16 08:11:27 +00001633 if (isa<CXXRecordDecl>(DC)) {
1634 LookupQualifiedName(R, DC);
1635
1636 if (!R.empty()) {
1637 // Don't give errors about ambiguities in this lookup.
1638 R.suppressDiagnostics();
1639
1640 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1641 bool isInstance = CurMethod &&
1642 CurMethod->isInstance() &&
1643 DC == CurMethod->getParent();
1644
1645 // Give a code modification hint to insert 'this->'.
1646 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1647 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001648 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001649 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1650 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001651 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001652 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001653 if (DepMethod) {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001654 Diag(R.getNameLoc(), diagnostic) << Name
1655 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1656 QualType DepThisType = DepMethod->getThisType(Context);
1657 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1658 R.getNameLoc(), DepThisType, false);
1659 TemplateArgumentListInfo TList;
1660 if (ULE->hasExplicitTemplateArgs())
1661 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001662
Douglas Gregore16af532011-02-28 18:50:33 +00001663 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001664 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001665 CXXDependentScopeMemberExpr *DepExpr =
1666 CXXDependentScopeMemberExpr::Create(
1667 Context, DepThis, DepThisType, true, SourceLocation(),
Douglas Gregore16af532011-02-28 18:50:33 +00001668 SS.getWithLocInContext(Context), NULL,
Nick Lewyckyfe712382010-08-20 20:54:15 +00001669 R.getLookupNameInfo(), &TList);
1670 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001671 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001672 // FIXME: we should be able to handle this case too. It is correct
1673 // to add this-> here. This is a workaround for PR7947.
1674 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001675 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001676 } else {
John McCalld681c392009-12-16 08:11:27 +00001677 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001678 }
John McCalld681c392009-12-16 08:11:27 +00001679
1680 // Do we really want to note all of these?
1681 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1682 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1683
1684 // Tell the callee to try to recover.
1685 return false;
1686 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001687
1688 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001689 }
1690 }
1691
Douglas Gregor598b08f2009-12-31 05:20:13 +00001692 // We didn't find anything, so try to correct for a typo.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001693 DeclarationName Corrected;
Daniel Dunbarf7ced252010-06-02 15:46:52 +00001694 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001695 if (!R.empty()) {
1696 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1697 if (SS.isEmpty())
1698 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1699 << FixItHint::CreateReplacement(R.getNameLoc(),
1700 R.getLookupName().getAsString());
1701 else
1702 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1703 << Name << computeDeclContext(SS, false) << R.getLookupName()
1704 << SS.getRange()
1705 << FixItHint::CreateReplacement(R.getNameLoc(),
1706 R.getLookupName().getAsString());
1707 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1708 Diag(ND->getLocation(), diag::note_previous_decl)
1709 << ND->getDeclName();
1710
1711 // Tell the callee to try to recover.
1712 return false;
1713 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001714
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001715 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1716 // FIXME: If we ended up with a typo for a type name or
1717 // Objective-C class name, we're in trouble because the parser
1718 // is in the wrong place to recover. Suggest the typo
1719 // correction, but don't make it a fix-it since we're not going
1720 // to recover well anyway.
1721 if (SS.isEmpty())
1722 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1723 else
1724 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1725 << Name << computeDeclContext(SS, false) << R.getLookupName()
1726 << SS.getRange();
1727
1728 // Don't try to recover; it won't work.
1729 return true;
1730 }
1731 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001732 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001733 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001734 if (SS.isEmpty())
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001735 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001736 else
Douglas Gregor25363982010-01-01 00:15:04 +00001737 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001738 << Name << computeDeclContext(SS, false) << Corrected
1739 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001740 return true;
1741 }
Douglas Gregor25363982010-01-01 00:15:04 +00001742 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001743 }
1744
1745 // Emit a special diagnostic for failed member lookups.
1746 // FIXME: computing the declaration context might fail here (?)
1747 if (!SS.isEmpty()) {
1748 Diag(R.getNameLoc(), diag::err_no_member)
1749 << Name << computeDeclContext(SS, false)
1750 << SS.getRange();
1751 return true;
1752 }
1753
John McCalld681c392009-12-16 08:11:27 +00001754 // Give up, we can't recover.
1755 Diag(R.getNameLoc(), diagnostic) << Name;
1756 return true;
1757}
1758
Douglas Gregor05fcf842010-11-02 20:36:02 +00001759ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1760 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian86151342010-07-22 23:33:21 +00001761 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1762 if (!IDecl)
1763 return 0;
1764 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1765 if (!ClassImpDecl)
1766 return 0;
Douglas Gregor05fcf842010-11-02 20:36:02 +00001767 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian86151342010-07-22 23:33:21 +00001768 if (!property)
1769 return 0;
1770 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
Douglas Gregor05fcf842010-11-02 20:36:02 +00001771 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1772 PIDecl->getPropertyIvarDecl())
Fariborz Jahanian86151342010-07-22 23:33:21 +00001773 return 0;
1774 return property;
1775}
1776
Douglas Gregor05fcf842010-11-02 20:36:02 +00001777bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1778 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1779 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1780 if (!IDecl)
1781 return false;
1782 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1783 if (!ClassImpDecl)
1784 return false;
1785 if (ObjCPropertyImplDecl *PIDecl
1786 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1787 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1788 PIDecl->getPropertyIvarDecl())
1789 return false;
1790
1791 return true;
1792}
1793
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001794ObjCIvarDecl *Sema::SynthesizeProvisionalIvar(LookupResult &Lookup,
1795 IdentifierInfo *II,
1796 SourceLocation NameLoc) {
1797 ObjCMethodDecl *CurMeth = getCurMethodDecl();
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001798 bool LookForIvars;
1799 if (Lookup.empty())
1800 LookForIvars = true;
1801 else if (CurMeth->isClassMethod())
1802 LookForIvars = false;
1803 else
1804 LookForIvars = (Lookup.isSingleResult() &&
Fariborz Jahanian9312fcc2011-01-26 00:57:01 +00001805 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1806 (Lookup.getAsSingle<VarDecl>() != 0));
Fariborz Jahanian7b70eb42010-07-30 16:59:05 +00001807 if (!LookForIvars)
1808 return 0;
1809
Fariborz Jahanian18722982010-07-17 00:59:30 +00001810 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1811 if (!IDecl)
1812 return 0;
1813 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
Fariborz Jahanian2a360892010-07-19 16:14:33 +00001814 if (!ClassImpDecl)
1815 return 0;
Fariborz Jahanian18722982010-07-17 00:59:30 +00001816 bool DynamicImplSeen = false;
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001817 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
Fariborz Jahanian18722982010-07-17 00:59:30 +00001818 if (!property)
1819 return 0;
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001820 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
Fariborz Jahanian18722982010-07-17 00:59:30 +00001821 DynamicImplSeen =
1822 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
Fariborz Jahanianbfcbc852010-10-19 19:08:23 +00001823 // property implementation has a designated ivar. No need to assume a new
1824 // one.
1825 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1826 return 0;
1827 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001828 if (!DynamicImplSeen) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001829 QualType PropType = Context.getCanonicalType(property->getType());
1830 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001831 NameLoc, NameLoc,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001832 II, PropType, /*Dinfo=*/0,
Fariborz Jahanian522eb7b2010-12-15 23:29:04 +00001833 ObjCIvarDecl::Private,
Fariborz Jahanian18722982010-07-17 00:59:30 +00001834 (Expr *)0, true);
1835 ClassImpDecl->addDecl(Ivar);
1836 IDecl->makeDeclVisibleInContext(Ivar, false);
1837 property->setPropertyIvarDecl(Ivar);
1838 return Ivar;
1839 }
1840 return 0;
1841}
1842
John McCalldadc5752010-08-24 06:29:42 +00001843ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001844 CXXScopeSpec &SS,
1845 UnqualifiedId &Id,
1846 bool HasTrailingLParen,
1847 bool isAddressOfOperand) {
John McCalle66edc12009-11-24 19:00:30 +00001848 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1849 "cannot be direct & operand and have a trailing lparen");
1850
1851 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001852 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001853
John McCall10eae182009-11-30 22:42:35 +00001854 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001855
1856 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001857 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001858 const TemplateArgumentListInfo *TemplateArgs;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001859 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001860
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001861 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001862 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001863 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001864
John McCalle66edc12009-11-24 19:00:30 +00001865 // C++ [temp.dep.expr]p3:
1866 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001867 // -- an identifier that was declared with a dependent type,
1868 // (note: handled after lookup)
1869 // -- a template-id that is dependent,
1870 // (note: handled in BuildTemplateIdExpr)
1871 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001872 // -- a nested-name-specifier that contains a class-name that
1873 // names a dependent type.
1874 // Determine whether this is a member of an unknown specialization;
1875 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001876 bool DependentID = false;
1877 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1878 Name.getCXXNameType()->isDependentType()) {
1879 DependentID = true;
1880 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001881 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001882 if (RequireCompleteDeclContext(SS, DC))
1883 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001884 } else {
1885 DependentID = true;
1886 }
1887 }
1888
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001889 if (DependentID)
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001890 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +00001891 TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001892
Fariborz Jahanian86151342010-07-22 23:33:21 +00001893 bool IvarLookupFollowUp = false;
John McCalle66edc12009-11-24 19:00:30 +00001894 // Perform the required lookup.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001895 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001896 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001897 // Lookup the template name again to correctly establish the context in
1898 // which it was found. This is really unfortunate as we already did the
1899 // lookup to determine that it was a template name in the first place. If
1900 // this becomes a performance hit, we can work harder to preserve those
1901 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001902 bool MemberOfUnknownSpecialization;
1903 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1904 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001905
1906 if (MemberOfUnknownSpecialization ||
1907 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1908 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1909 TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001910 } else {
Fariborz Jahanian86151342010-07-22 23:33:21 +00001911 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001912 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001913
Douglas Gregora5226932011-02-04 13:35:07 +00001914 // If the result might be in a dependent base class, this is a dependent
1915 // id-expression.
1916 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1917 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1918 TemplateArgs);
1919
John McCalle66edc12009-11-24 19:00:30 +00001920 // If this reference is in an Objective-C method, then we need to do
1921 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001922 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001923 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001924 if (E.isInvalid())
1925 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001926
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001927 if (Expr *Ex = E.takeAs<Expr>())
1928 return Owned(Ex);
1929
1930 // Synthesize ivars lazily.
Fariborz Jahanianc63f1c52011-01-03 18:08:02 +00001931 if (getLangOptions().ObjCDefaultSynthProperties &&
1932 getLangOptions().ObjCNonFragileABI2) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +00001933 if (SynthesizeProvisionalIvar(R, II, NameLoc)) {
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001934 if (const ObjCPropertyDecl *Property =
1935 canSynthesizeProvisionalIvar(II)) {
1936 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1937 Diag(Property->getLocation(), diag::note_property_declare);
1938 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001939 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1940 isAddressOfOperand);
Fariborz Jahanian8046af72010-11-17 19:41:23 +00001941 }
Fariborz Jahanian18722982010-07-17 00:59:30 +00001942 }
Fariborz Jahanian18d90a92010-08-13 18:09:39 +00001943 // for further use, this must be set to false if in class method.
1944 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
Steve Naroffebf4cb42008-06-02 23:03:37 +00001945 }
Chris Lattner59a25942008-03-31 00:36:02 +00001946 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001947
John McCalle66edc12009-11-24 19:00:30 +00001948 if (R.isAmbiguous())
1949 return ExprError();
1950
Douglas Gregor171c45a2009-02-18 21:56:37 +00001951 // Determine whether this name might be a candidate for
1952 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001953 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001954
John McCalle66edc12009-11-24 19:00:30 +00001955 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001956 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001957 // in C90, extension in C99, forbidden in C++).
1958 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1959 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1960 if (D) R.addDecl(D);
1961 }
1962
1963 // If this name wasn't predeclared and if this is not a function
1964 // call, diagnose the problem.
1965 if (R.empty()) {
Douglas Gregor5fd04d42010-05-18 16:14:23 +00001966 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
John McCalld681c392009-12-16 08:11:27 +00001967 return ExprError();
1968
1969 assert(!R.empty() &&
1970 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001971
1972 // If we found an Objective-C instance variable, let
1973 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001974 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001975 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1976 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001977 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001978 assert(E.isInvalid() || E.get());
1979 return move(E);
1980 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001981 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001982 }
Mike Stump11289f42009-09-09 15:08:12 +00001983
John McCalle66edc12009-11-24 19:00:30 +00001984 // This is guaranteed from this point on.
1985 assert(!R.empty() || ADL);
1986
John McCall2d74de92009-12-01 22:10:20 +00001987 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001988 // C++ [class.mfct.non-static]p3:
1989 // When an id-expression that is not part of a class member access
1990 // syntax and not used to form a pointer to member is used in the
1991 // body of a non-static member function of class X, if name lookup
1992 // resolves the name in the id-expression to a non-static non-type
1993 // member of some class C, the id-expression is transformed into a
1994 // class member access expression using (*this) as the
1995 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001996 //
1997 // But we don't actually need to do this for '&' operands if R
1998 // resolved to a function or overloaded function set, because the
1999 // expression is ill-formed if it actually works out to be a
2000 // non-static member function:
2001 //
2002 // C++ [expr.ref]p4:
2003 // Otherwise, if E1.E2 refers to a non-static member function. . .
2004 // [t]he expression can be used only as the left-hand operand of a
2005 // member function call.
2006 //
2007 // There are other safeguards against such uses, but it's important
2008 // to get this right here so that we don't end up making a
2009 // spuriously dependent expression if we're inside a dependent
2010 // instance method.
John McCall57500772009-12-16 12:17:52 +00002011 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00002012 bool MightBeImplicitMember;
2013 if (!isAddressOfOperand)
2014 MightBeImplicitMember = true;
2015 else if (!SS.isEmpty())
2016 MightBeImplicitMember = false;
2017 else if (R.isOverloadedResult())
2018 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00002019 else if (R.isUnresolvableResult())
2020 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00002021 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00002022 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2023 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00002024
2025 if (MightBeImplicitMember)
John McCall57500772009-12-16 12:17:52 +00002026 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00002027 }
2028
John McCalle66edc12009-11-24 19:00:30 +00002029 if (TemplateArgs)
2030 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00002031
John McCalle66edc12009-11-24 19:00:30 +00002032 return BuildDeclarationNameExpr(SS, R, ADL);
2033}
2034
John McCall57500772009-12-16 12:17:52 +00002035/// Builds an expression which might be an implicit member expression.
John McCalldadc5752010-08-24 06:29:42 +00002036ExprResult
John McCall57500772009-12-16 12:17:52 +00002037Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
2038 LookupResult &R,
2039 const TemplateArgumentListInfo *TemplateArgs) {
Richard Smith938f40b2011-06-11 17:19:42 +00002040 switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
John McCall57500772009-12-16 12:17:52 +00002041 case IMA_Instance:
2042 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
2043
John McCall57500772009-12-16 12:17:52 +00002044 case IMA_Mixed:
2045 case IMA_Mixed_Unrelated:
2046 case IMA_Unresolved:
2047 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
2048
2049 case IMA_Static:
2050 case IMA_Mixed_StaticContext:
2051 case IMA_Unresolved_StaticContext:
2052 if (TemplateArgs)
2053 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
2054 return BuildDeclarationNameExpr(SS, R, false);
2055
2056 case IMA_Error_StaticContext:
2057 case IMA_Error_Unrelated:
John McCallf3a88602011-02-03 08:15:49 +00002058 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
2059 R.getLookupNameInfo());
John McCall57500772009-12-16 12:17:52 +00002060 return ExprError();
2061 }
2062
2063 llvm_unreachable("unexpected instance member access kind");
2064 return ExprError();
2065}
2066
John McCall10eae182009-11-30 22:42:35 +00002067/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2068/// declaration name, generally during template instantiation.
2069/// There's a large number of things which don't need to be done along
2070/// this path.
John McCalldadc5752010-08-24 06:29:42 +00002071ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002072Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002073 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00002074 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00002075 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002076 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
John McCalle66edc12009-11-24 19:00:30 +00002077
John McCall0b66eb32010-05-01 00:40:08 +00002078 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00002079 return ExprError();
2080
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002081 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00002082 LookupQualifiedName(R, DC);
2083
2084 if (R.isAmbiguous())
2085 return ExprError();
2086
2087 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002088 Diag(NameInfo.getLoc(), diag::err_no_member)
2089 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00002090 return ExprError();
2091 }
2092
2093 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
2094}
2095
2096/// LookupInObjCMethod - The parser has read a name in, and Sema has
2097/// detected that we're currently inside an ObjC method. Perform some
2098/// additional lookup.
2099///
2100/// Ideally, most of this would be done by lookup, but there's
2101/// actually quite a lot of extra work involved.
2102///
2103/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00002104ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002105Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00002106 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00002107 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00002108 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00002109
John McCalle66edc12009-11-24 19:00:30 +00002110 // There are two cases to handle here. 1) scoped lookup could have failed,
2111 // in which case we should look for an ivar. 2) scoped lookup could have
2112 // found a decl, but that decl is outside the current instance method (i.e.
2113 // a global variable). In these two cases, we do a lookup for an ivar with
2114 // this name, if the lookup sucedes, we replace it our current decl.
2115
2116 // If we're in a class method, we don't normally want to look for
2117 // ivars. But if we don't find anything else, and there's an
2118 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00002119 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00002120
2121 bool LookForIvars;
2122 if (Lookup.empty())
2123 LookForIvars = true;
2124 else if (IsClassMethod)
2125 LookForIvars = false;
2126 else
2127 LookForIvars = (Lookup.isSingleResult() &&
2128 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00002129 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00002130 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00002131 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00002132 ObjCInterfaceDecl *ClassDeclared;
2133 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2134 // Diagnose using an ivar in a class method.
2135 if (IsClassMethod)
2136 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2137 << IV->getDeclName());
2138
2139 // If we're referencing an invalid decl, just return this as a silent
2140 // error node. The error diagnostic was already emitted on the decl.
2141 if (IV->isInvalidDecl())
2142 return ExprError();
2143
2144 // Check if referencing a field with __attribute__((deprecated)).
2145 if (DiagnoseUseOfDecl(IV, Loc))
2146 return ExprError();
2147
2148 // Diagnose the use of an ivar outside of the declaring class.
2149 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2150 ClassDeclared != IFace)
2151 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2152
2153 // FIXME: This should use a new expr for a direct reference, don't
2154 // turn this into Self->ivar, just return a BareIVarExpr or something.
2155 IdentifierInfo &II = Context.Idents.get("self");
2156 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002157 SelfName.setIdentifier(&II, SourceLocation());
John McCalle66edc12009-11-24 19:00:30 +00002158 CXXScopeSpec SelfScopeSpec;
John McCalldadc5752010-08-24 06:29:42 +00002159 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00002160 SelfName, false, false);
2161 if (SelfExpr.isInvalid())
2162 return ExprError();
2163
John Wiegley01296292011-04-08 18:41:53 +00002164 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2165 if (SelfExpr.isInvalid())
2166 return ExprError();
John McCall27584242010-12-06 20:48:59 +00002167
John McCalle66edc12009-11-24 19:00:30 +00002168 MarkDeclarationReferenced(Loc, IV);
Fariborz Jahanian82bc4362011-04-12 23:39:33 +00002169 Expr *base = SelfExpr.take();
2170 base = base->IgnoreParenImpCasts();
2171 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(base)) {
2172 const NamedDecl *ND = DE->getDecl();
2173 if (!isa<ImplicitParamDecl>(ND)) {
Fariborz Jahanian66a6c062011-04-15 17:04:42 +00002174 // relax the rule such that it is allowed to have a shadow 'self'
2175 // where stand-alone ivar can be found in this 'self' object.
2176 // This is to match gcc's behavior.
2177 ObjCInterfaceDecl *selfIFace = 0;
2178 if (const ObjCObjectPointerType *OPT =
2179 base->getType()->getAsObjCInterfacePointerType())
2180 selfIFace = OPT->getInterfaceDecl();
2181 if (!selfIFace ||
2182 !selfIFace->lookupInstanceVariable(IV->getIdentifier())) {
Fariborz Jahanian82bc4362011-04-12 23:39:33 +00002183 Diag(Loc, diag::error_implicit_ivar_access)
2184 << IV->getDeclName();
2185 Diag(ND->getLocation(), diag::note_declared_at);
2186 return ExprError();
2187 }
Fariborz Jahanian66a6c062011-04-15 17:04:42 +00002188 }
Fariborz Jahanian82bc4362011-04-12 23:39:33 +00002189 }
John McCalle66edc12009-11-24 19:00:30 +00002190 return Owned(new (Context)
2191 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00002192 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00002193 }
Chris Lattner87313662010-04-12 05:10:17 +00002194 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00002195 // We should warn if a local variable hides an ivar.
Chris Lattner87313662010-04-12 05:10:17 +00002196 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00002197 ObjCInterfaceDecl *ClassDeclared;
2198 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2199 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2200 IFace == ClassDeclared)
2201 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2202 }
2203 }
2204
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00002205 if (Lookup.empty() && II && AllowBuiltinCreation) {
2206 // FIXME. Consolidate this with similar code in LookupName.
2207 if (unsigned BuiltinID = II->getBuiltinID()) {
2208 if (!(getLangOptions().CPlusPlus &&
2209 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2210 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2211 S, Lookup.isForRedeclaration(),
2212 Lookup.getNameLoc());
2213 if (D) Lookup.addDecl(D);
2214 }
2215 }
2216 }
John McCalle66edc12009-11-24 19:00:30 +00002217 // Sentinel value saying that we didn't do anything special.
2218 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00002219}
John McCalld14a8642009-11-21 08:51:07 +00002220
John McCall16df1e52010-03-30 21:47:33 +00002221/// \brief Cast a base object to a member's actual type.
2222///
2223/// Logically this happens in three phases:
2224///
2225/// * First we cast from the base type to the naming class.
2226/// The naming class is the class into which we were looking
2227/// when we found the member; it's the qualifier type if a
2228/// qualifier was provided, and otherwise it's the base type.
2229///
2230/// * Next we cast from the naming class to the declaring class.
2231/// If the member we found was brought into a class's scope by
2232/// a using declaration, this is that class; otherwise it's
2233/// the class declaring the member.
2234///
2235/// * Finally we cast from the declaring class to the "true"
2236/// declaring class of the member. This conversion does not
2237/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00002238ExprResult
2239Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002240 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002241 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002242 NamedDecl *Member) {
2243 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2244 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00002245 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002246
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002247 QualType DestRecordType;
2248 QualType DestType;
2249 QualType FromRecordType;
2250 QualType FromType = From->getType();
2251 bool PointerConversions = false;
2252 if (isa<FieldDecl>(Member)) {
2253 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002254
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002255 if (FromType->getAs<PointerType>()) {
2256 DestType = Context.getPointerType(DestRecordType);
2257 FromRecordType = FromType->getPointeeType();
2258 PointerConversions = true;
2259 } else {
2260 DestType = DestRecordType;
2261 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002262 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002263 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2264 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00002265 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002266
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002267 DestType = Method->getThisType(Context);
2268 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002269
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002270 if (FromType->getAs<PointerType>()) {
2271 FromRecordType = FromType->getPointeeType();
2272 PointerConversions = true;
2273 } else {
2274 FromRecordType = FromType;
2275 DestType = DestRecordType;
2276 }
2277 } else {
2278 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00002279 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002280 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002281
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002282 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002283 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002284
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002285 // If the unqualified types are the same, no conversion is necessary.
2286 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002287 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002288
John McCall16df1e52010-03-30 21:47:33 +00002289 SourceRange FromRange = From->getSourceRange();
2290 SourceLocation FromLoc = FromRange.getBegin();
2291
John McCall2536c6d2010-08-25 10:28:54 +00002292 ExprValueKind VK = CastCategory(From);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002293
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002294 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002295 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002296 // class name.
2297 //
2298 // If the member was a qualified name and the qualified referred to a
2299 // specific base subobject type, we'll cast to that intermediate type
2300 // first and then to the object in which the member is declared. That allows
2301 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2302 //
2303 // class Base { public: int x; };
2304 // class Derived1 : public Base { };
2305 // class Derived2 : public Base { };
2306 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2307 //
2308 // void VeryDerived::f() {
2309 // x = 17; // error: ambiguous base subobjects
2310 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2311 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002312 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002313 QualType QType = QualType(Qualifier->getAsType(), 0);
2314 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2315 assert(QType->isRecordType() && "lookup done with non-record type");
2316
2317 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2318
2319 // In C++98, the qualifier type doesn't actually have to be a base
2320 // type of the object type, in which case we just ignore it.
2321 // Otherwise build the appropriate casts.
2322 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002323 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002324 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002325 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002326 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002327
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002328 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002329 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002330 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2331 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002332
2333 FromType = QType;
2334 FromRecordType = QRecordType;
2335
2336 // If the qualifier type was the same as the destination type,
2337 // we're done.
2338 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002339 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002340 }
2341 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002342
John McCall16df1e52010-03-30 21:47:33 +00002343 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002344
John McCall16df1e52010-03-30 21:47:33 +00002345 // If we actually found the member through a using declaration, cast
2346 // down to the using declaration's type.
2347 //
2348 // Pointer equality is fine here because only one declaration of a
2349 // class ever has member declarations.
2350 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2351 assert(isa<UsingShadowDecl>(FoundDecl));
2352 QualType URecordType = Context.getTypeDeclType(
2353 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2354
2355 // We only need to do this if the naming-class to declaring-class
2356 // conversion is non-trivial.
2357 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2358 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002359 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002360 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002361 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002362 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002363
John McCall16df1e52010-03-30 21:47:33 +00002364 QualType UType = URecordType;
2365 if (PointerConversions)
2366 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002367 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2368 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002369 FromType = UType;
2370 FromRecordType = URecordType;
2371 }
2372
2373 // We don't do access control for the conversion from the
2374 // declaring class to the true declaring class.
2375 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002376 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002377
John McCallcf142162010-08-07 06:22:56 +00002378 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002379 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2380 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002381 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002382 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002383
John Wiegley01296292011-04-08 18:41:53 +00002384 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2385 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002386}
Douglas Gregor3256d042009-06-30 15:47:41 +00002387
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002388/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00002389static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00002390 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalla8ae2222010-04-06 21:38:20 +00002391 DeclAccessPair FoundDecl,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002392 const DeclarationNameInfo &MemberNameInfo,
2393 QualType Ty,
John McCall7decc9e2010-11-18 06:31:45 +00002394 ExprValueKind VK, ExprObjectKind OK,
John McCalle66edc12009-11-24 19:00:30 +00002395 const TemplateArgumentListInfo *TemplateArgs = 0) {
Douglas Gregorea972d32011-02-28 21:54:11 +00002396 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002397 Member, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002398 TemplateArgs, Ty, VK, OK);
Douglas Gregorc1905232009-08-26 22:36:53 +00002399}
2400
John McCallfeb624a2010-11-23 20:48:44 +00002401static ExprResult
2402BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2403 const CXXScopeSpec &SS, FieldDecl *Field,
2404 DeclAccessPair FoundDecl,
2405 const DeclarationNameInfo &MemberNameInfo) {
2406 // x.a is an l-value if 'a' has a reference type. Otherwise:
2407 // x.a is an l-value/x-value/pr-value if the base is (and note
2408 // that *x is always an l-value), except that if the base isn't
2409 // an ordinary object then we must have an rvalue.
2410 ExprValueKind VK = VK_LValue;
2411 ExprObjectKind OK = OK_Ordinary;
2412 if (!IsArrow) {
2413 if (BaseExpr->getObjectKind() == OK_Ordinary)
2414 VK = BaseExpr->getValueKind();
2415 else
2416 VK = VK_RValue;
2417 }
2418 if (VK != VK_RValue && Field->isBitField())
2419 OK = OK_BitField;
2420
2421 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2422 QualType MemberType = Field->getType();
2423 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2424 MemberType = Ref->getPointeeType();
2425 VK = VK_LValue;
2426 } else {
2427 QualType BaseType = BaseExpr->getType();
2428 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2429
2430 Qualifiers BaseQuals = BaseType.getQualifiers();
2431
2432 // GC attributes are never picked up by members.
2433 BaseQuals.removeObjCGCAttr();
2434
2435 // CVR attributes from the base are picked up by members,
2436 // except that 'mutable' members don't pick up 'const'.
2437 if (Field->isMutable()) BaseQuals.removeConst();
2438
2439 Qualifiers MemberQuals
2440 = S.Context.getCanonicalType(MemberType).getQualifiers();
2441
2442 // TR 18037 does not allow fields to be declared with address spaces.
2443 assert(!MemberQuals.hasAddressSpace());
2444
2445 Qualifiers Combined = BaseQuals + MemberQuals;
2446 if (Combined != MemberQuals)
2447 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2448 }
2449
2450 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
John Wiegley01296292011-04-08 18:41:53 +00002451 ExprResult Base =
2452 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2453 FoundDecl, Field);
2454 if (Base.isInvalid())
John McCallfeb624a2010-11-23 20:48:44 +00002455 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00002456 return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
John McCallfeb624a2010-11-23 20:48:44 +00002457 Field, FoundDecl, MemberNameInfo,
2458 MemberType, VK, OK));
2459}
2460
John McCall2d74de92009-12-01 22:10:20 +00002461/// Builds an implicit member access expression. The current context
2462/// is known to be an instance method, and the given unqualified lookup
2463/// set is known to contain only instance members, at least one of which
2464/// is from an appropriate type.
John McCalldadc5752010-08-24 06:29:42 +00002465ExprResult
John McCall2d74de92009-12-01 22:10:20 +00002466Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2467 LookupResult &R,
2468 const TemplateArgumentListInfo *TemplateArgs,
2469 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00002470 assert(!R.empty() && !R.isAmbiguous());
2471
John McCallf3a88602011-02-03 08:15:49 +00002472 SourceLocation loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00002473
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002474 // We may have found a field within an anonymous union or struct
2475 // (C++ [class.union]).
John McCalle66edc12009-11-24 19:00:30 +00002476 // FIXME: template-ids inside anonymous structs?
Francois Pichet783dd6e2010-11-21 06:08:52 +00002477 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
John McCallf3a88602011-02-03 08:15:49 +00002478 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002479
John McCallf3a88602011-02-03 08:15:49 +00002480 // If this is known to be an instance access, go ahead and build an
2481 // implicit 'this' expression now.
John McCall2d74de92009-12-01 22:10:20 +00002482 // 'this' expression now.
Richard Smith938f40b2011-06-11 17:19:42 +00002483 QualType ThisTy = getAndCaptureCurrentThisType();
2484 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
John McCallf3a88602011-02-03 08:15:49 +00002485
John McCallf3a88602011-02-03 08:15:49 +00002486 Expr *baseExpr = 0; // null signifies implicit access
John McCall2d74de92009-12-01 22:10:20 +00002487 if (IsKnownInstance) {
Douglas Gregorb15af892010-01-07 23:12:05 +00002488 SourceLocation Loc = R.getNameLoc();
2489 if (SS.getRange().isValid())
2490 Loc = SS.getRange().getBegin();
Richard Smith938f40b2011-06-11 17:19:42 +00002491 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002492 }
2493
Richard Smith938f40b2011-06-11 17:19:42 +00002494 return BuildMemberReferenceExpr(baseExpr, ThisTy,
John McCall2d74de92009-12-01 22:10:20 +00002495 /*OpLoc*/ SourceLocation(),
2496 /*IsArrow*/ true,
John McCall38836f02010-01-15 08:34:02 +00002497 SS,
2498 /*FirstQualifierInScope*/ 0,
2499 R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00002500}
2501
John McCalle66edc12009-11-24 19:00:30 +00002502bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002503 const LookupResult &R,
2504 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002505 // Only when used directly as the postfix-expression of a call.
2506 if (!HasTrailingLParen)
2507 return false;
2508
2509 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002510 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002511 return false;
2512
2513 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002514 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002515 return false;
2516
2517 // Turn off ADL when we find certain kinds of declarations during
2518 // normal lookup:
2519 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2520 NamedDecl *D = *I;
2521
2522 // C++0x [basic.lookup.argdep]p3:
2523 // -- a declaration of a class member
2524 // Since using decls preserve this property, we check this on the
2525 // original decl.
John McCall57500772009-12-16 12:17:52 +00002526 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002527 return false;
2528
2529 // C++0x [basic.lookup.argdep]p3:
2530 // -- a block-scope function declaration that is not a
2531 // using-declaration
2532 // NOTE: we also trigger this for function templates (in fact, we
2533 // don't check the decl type at all, since all other decl types
2534 // turn off ADL anyway).
2535 if (isa<UsingShadowDecl>(D))
2536 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2537 else if (D->getDeclContext()->isFunctionOrMethod())
2538 return false;
2539
2540 // C++0x [basic.lookup.argdep]p3:
2541 // -- a declaration that is neither a function or a function
2542 // template
2543 // And also for builtin functions.
2544 if (isa<FunctionDecl>(D)) {
2545 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2546
2547 // But also builtin functions.
2548 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2549 return false;
2550 } else if (!isa<FunctionTemplateDecl>(D))
2551 return false;
2552 }
2553
2554 return true;
2555}
2556
2557
John McCalld14a8642009-11-21 08:51:07 +00002558/// Diagnoses obvious problems with the use of the given declaration
2559/// as an expression. This is only actually called for lookups that
2560/// were not overloaded, and it doesn't promise that the declaration
2561/// will in fact be used.
2562static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002563 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002564 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2565 return true;
2566 }
2567
2568 if (isa<ObjCInterfaceDecl>(D)) {
2569 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2570 return true;
2571 }
2572
2573 if (isa<NamespaceDecl>(D)) {
2574 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2575 return true;
2576 }
2577
2578 return false;
2579}
2580
John McCalldadc5752010-08-24 06:29:42 +00002581ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002582Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002583 LookupResult &R,
2584 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002585 // If this is a single, fully-resolved result and we don't need ADL,
2586 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002587 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002588 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2589 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002590
2591 // We only need to check the declaration if there's exactly one
2592 // result, because in the overloaded case the results can only be
2593 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002594 if (R.isSingleResult() &&
2595 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002596 return ExprError();
2597
John McCall58cc69d2010-01-27 01:50:18 +00002598 // Otherwise, just build an unresolved lookup expression. Suppress
2599 // any lookup-related diagnostics; we'll hash these out later, when
2600 // we've picked a target.
2601 R.suppressDiagnostics();
2602
John McCalld14a8642009-11-21 08:51:07 +00002603 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002604 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002605 SS.getWithLocInContext(Context),
2606 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002607 NeedsADL, R.isOverloadedResult(),
2608 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002609
2610 return Owned(ULE);
2611}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002612
John McCalld14a8642009-11-21 08:51:07 +00002613/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002614ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002615Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002616 const DeclarationNameInfo &NameInfo,
2617 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002618 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002619 assert(!isa<FunctionTemplateDecl>(D) &&
2620 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002621
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002622 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002623 if (CheckDeclInExpr(*this, Loc, D))
2624 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002625
Douglas Gregore7488b92009-12-01 16:58:18 +00002626 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2627 // Specifically diagnose references to class templates that are missing
2628 // a template argument list.
2629 Diag(Loc, diag::err_template_decl_ref)
2630 << Template << SS.getRange();
2631 Diag(Template->getLocation(), diag::note_template_decl_here);
2632 return ExprError();
2633 }
2634
2635 // Make sure that we're referring to a value.
2636 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2637 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002638 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002639 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002640 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002641 return ExprError();
2642 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002643
Douglas Gregor171c45a2009-02-18 21:56:37 +00002644 // Check whether this declaration can be used. Note that we suppress
2645 // this check when we're going to perform argument-dependent lookup
2646 // on this function name, because this might not be the function
2647 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002648 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002649 return ExprError();
2650
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002651 // Only create DeclRefExpr's for valid Decl's.
2652 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002653 return ExprError();
2654
John McCallf3a88602011-02-03 08:15:49 +00002655 // Handle members of anonymous structs and unions. If we got here,
2656 // and the reference is to a class member indirect field, then this
2657 // must be the subject of a pointer-to-member expression.
2658 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2659 if (!indirectField->isCXXClassMember())
2660 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2661 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002662
Chris Lattner2a9d9892008-10-20 05:16:36 +00002663 // If the identifier reference is inside a block, and it refers to a value
2664 // that is outside the block, create a BlockDeclRefExpr instead of a
2665 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2666 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002667 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00002668 // We do not do this for things like enum constants, global variables, etc,
2669 // as they do not get snapshotted.
2670 //
John McCall351762c2011-02-07 10:33:21 +00002671 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
John McCallc63de662011-02-02 13:00:07 +00002672 case CR_Error:
2673 return ExprError();
Mike Stump7dafa0d2010-01-05 02:56:35 +00002674
John McCallc63de662011-02-02 13:00:07 +00002675 case CR_Capture:
John McCall351762c2011-02-07 10:33:21 +00002676 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2677 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2678
2679 case CR_CaptureByRef:
2680 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2681 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
John McCallf4cd4f92011-02-09 01:13:10 +00002682
2683 case CR_NoCapture: {
2684 // If this reference is not in a block or if the referenced
2685 // variable is within the block, create a normal DeclRefExpr.
2686
2687 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002688 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002689
2690 switch (D->getKind()) {
2691 // Ignore all the non-ValueDecl kinds.
2692#define ABSTRACT_DECL(kind)
2693#define VALUE(type, base)
2694#define DECL(type, base) \
2695 case Decl::type:
2696#include "clang/AST/DeclNodes.inc"
2697 llvm_unreachable("invalid value decl kind");
2698 return ExprError();
2699
2700 // These shouldn't make it here.
2701 case Decl::ObjCAtDefsField:
2702 case Decl::ObjCIvar:
2703 llvm_unreachable("forming non-member reference to ivar?");
2704 return ExprError();
2705
2706 // Enum constants are always r-values and never references.
2707 // Unresolved using declarations are dependent.
2708 case Decl::EnumConstant:
2709 case Decl::UnresolvedUsingValue:
2710 valueKind = VK_RValue;
2711 break;
2712
2713 // Fields and indirect fields that got here must be for
2714 // pointer-to-member expressions; we just call them l-values for
2715 // internal consistency, because this subexpression doesn't really
2716 // exist in the high-level semantics.
2717 case Decl::Field:
2718 case Decl::IndirectField:
2719 assert(getLangOptions().CPlusPlus &&
2720 "building reference to field in C?");
2721
2722 // These can't have reference type in well-formed programs, but
2723 // for internal consistency we do this anyway.
2724 type = type.getNonReferenceType();
2725 valueKind = VK_LValue;
2726 break;
2727
2728 // Non-type template parameters are either l-values or r-values
2729 // depending on the type.
2730 case Decl::NonTypeTemplateParm: {
2731 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2732 type = reftype->getPointeeType();
2733 valueKind = VK_LValue; // even if the parameter is an r-value reference
2734 break;
2735 }
2736
2737 // For non-references, we need to strip qualifiers just in case
2738 // the template parameter was declared as 'const int' or whatever.
2739 valueKind = VK_RValue;
2740 type = type.getUnqualifiedType();
2741 break;
2742 }
2743
2744 case Decl::Var:
2745 // In C, "extern void blah;" is valid and is an r-value.
2746 if (!getLangOptions().CPlusPlus &&
2747 !type.hasQualifiers() &&
2748 type->isVoidType()) {
2749 valueKind = VK_RValue;
2750 break;
2751 }
2752 // fallthrough
2753
2754 case Decl::ImplicitParam:
2755 case Decl::ParmVar:
2756 // These are always l-values.
2757 valueKind = VK_LValue;
2758 type = type.getNonReferenceType();
2759 break;
2760
2761 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002762 const FunctionType *fty = type->castAs<FunctionType>();
2763
2764 // If we're referring to a function with an __unknown_anytype
2765 // result type, make the entire expression __unknown_anytype.
2766 if (fty->getResultType() == Context.UnknownAnyTy) {
2767 type = Context.UnknownAnyTy;
2768 valueKind = VK_RValue;
2769 break;
2770 }
2771
John McCallf4cd4f92011-02-09 01:13:10 +00002772 // Functions are l-values in C++.
2773 if (getLangOptions().CPlusPlus) {
2774 valueKind = VK_LValue;
2775 break;
2776 }
2777
2778 // C99 DR 316 says that, if a function type comes from a
2779 // function definition (without a prototype), that type is only
2780 // used for checking compatibility. Therefore, when referencing
2781 // the function, we pretend that we don't have the full function
2782 // type.
John McCall2979fe02011-04-12 00:42:48 +00002783 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2784 isa<FunctionProtoType>(fty))
2785 type = Context.getFunctionNoProtoType(fty->getResultType(),
2786 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002787
2788 // Functions are r-values in C.
2789 valueKind = VK_RValue;
2790 break;
2791 }
2792
2793 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002794 // If we're referring to a method with an __unknown_anytype
2795 // result type, make the entire expression __unknown_anytype.
2796 // This should only be possible with a type written directly.
2797 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(VD->getType()))
2798 if (proto->getResultType() == Context.UnknownAnyTy) {
2799 type = Context.UnknownAnyTy;
2800 valueKind = VK_RValue;
2801 break;
2802 }
2803
John McCallf4cd4f92011-02-09 01:13:10 +00002804 // C++ methods are l-values if static, r-values if non-static.
2805 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2806 valueKind = VK_LValue;
2807 break;
2808 }
2809 // fallthrough
2810
2811 case Decl::CXXConversion:
2812 case Decl::CXXDestructor:
2813 case Decl::CXXConstructor:
2814 valueKind = VK_RValue;
2815 break;
2816 }
2817
2818 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2819 }
2820
John McCallc63de662011-02-02 13:00:07 +00002821 }
John McCall7decc9e2010-11-18 06:31:45 +00002822
John McCall351762c2011-02-07 10:33:21 +00002823 llvm_unreachable("unknown capture result");
2824 return ExprError();
Chris Lattner17ed4872006-11-20 04:58:19 +00002825}
Chris Lattnere168f762006-11-10 05:29:30 +00002826
John McCall2979fe02011-04-12 00:42:48 +00002827ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002828 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002829
Chris Lattnere168f762006-11-10 05:29:30 +00002830 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00002831 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002832 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2833 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2834 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002835 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002836
Chris Lattnera81a0272008-01-12 08:14:25 +00002837 // Pre-defined identifiers are of type char[x], where x is the length of the
2838 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002839
Anders Carlsson2fb08242009-09-08 18:24:21 +00002840 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002841 if (!currentDecl && getCurBlock())
2842 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002843 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002844 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002845 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002846 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002847
Anders Carlsson0b209a82009-09-11 01:22:35 +00002848 QualType ResTy;
2849 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2850 ResTy = Context.DependentTy;
2851 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002852 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002853
Anders Carlsson0b209a82009-09-11 01:22:35 +00002854 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002855 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002856 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2857 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002858 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002859}
2860
John McCalldadc5752010-08-24 06:29:42 +00002861ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002862 llvm::SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002863 bool Invalid = false;
2864 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2865 if (Invalid)
2866 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002867
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002868 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2869 PP);
Steve Naroffae4143e2007-04-26 20:39:23 +00002870 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002871 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002872
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002873 QualType Ty;
2874 if (!getLangOptions().CPlusPlus)
2875 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2876 else if (Literal.isWide())
2877 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedmaneb1df702010-02-03 18:21:45 +00002878 else if (Literal.isMultiChar())
2879 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002880 else
2881 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002882
Sebastian Redl20614a72009-01-20 22:23:13 +00002883 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2884 Literal.isWide(),
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002885 Ty, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00002886}
2887
John McCalldadc5752010-08-24 06:29:42 +00002888ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002889 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002890 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2891 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002892 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00002893 unsigned IntSize = Context.Target.getIntWidth();
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002894 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00002895 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00002896 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002897
Chris Lattner23b7eb62007-06-15 23:05:46 +00002898 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002899 // Add padding so that NumericLiteralParser can overread by one character.
2900 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002901 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002902
Chris Lattner67ca9252007-05-21 01:08:44 +00002903 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002904 bool Invalid = false;
2905 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2906 if (Invalid)
2907 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002908
Mike Stump11289f42009-09-09 15:08:12 +00002909 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002910 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002911 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002912 return ExprError();
2913
Chris Lattner1c20a172007-08-26 03:42:43 +00002914 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002915
Chris Lattner1c20a172007-08-26 03:42:43 +00002916 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002917 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002918 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002919 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002920 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002921 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002922 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002923 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002924
2925 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2926
John McCall53b93a02009-12-24 09:08:04 +00002927 using llvm::APFloat;
2928 APFloat Val(Format);
2929
2930 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002931
2932 // Overflow is always an error, but underflow is only an error if
2933 // we underflowed to zero (APFloat reports denormals as underflow).
2934 if ((result & APFloat::opOverflow) ||
2935 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002936 unsigned diagnostic;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002937 llvm::SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002938 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002939 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002940 APFloat::getLargest(Format).toString(buffer);
2941 } else {
John McCall62abc942010-02-26 23:35:57 +00002942 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002943 APFloat::getSmallest(Format).toString(buffer);
2944 }
2945
2946 Diag(Tok.getLocation(), diagnostic)
2947 << Ty
2948 << llvm::StringRef(buffer.data(), buffer.size());
2949 }
2950
2951 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002952 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002953
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002954 if (Ty == Context.DoubleTy) {
2955 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002956 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002957 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2958 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002959 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002960 }
2961 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002962 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002963 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002964 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002965 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002966
Neil Boothac582c52007-08-29 22:00:19 +00002967 // long long is a C99 feature.
2968 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00002969 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00002970 Diag(Tok.getLocation(), diag::ext_longlong);
2971
Chris Lattner67ca9252007-05-21 01:08:44 +00002972 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00002973 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002974
Chris Lattner67ca9252007-05-21 01:08:44 +00002975 if (Literal.GetIntegerValue(ResultVal)) {
2976 // If this value didn't fit into uintmax_t, warn and force to ull.
2977 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002978 Ty = Context.UnsignedLongLongTy;
2979 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002980 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002981 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002982 // If this value fits into a ULL, try to figure out what else it fits into
2983 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002984
Chris Lattner67ca9252007-05-21 01:08:44 +00002985 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2986 // be an unsigned int.
2987 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2988
2989 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002990 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002991 if (!Literal.isLong && !Literal.isLongLong) {
2992 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00002993 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002994
Chris Lattner67ca9252007-05-21 01:08:44 +00002995 // Does it fit in a unsigned int?
2996 if (ResultVal.isIntN(IntSize)) {
2997 // Does it fit in a signed int?
2998 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002999 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00003000 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003001 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00003002 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00003003 }
Chris Lattner67ca9252007-05-21 01:08:44 +00003004 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003005
Chris Lattner67ca9252007-05-21 01:08:44 +00003006 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003007 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00003008 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003009
Chris Lattner67ca9252007-05-21 01:08:44 +00003010 // Does it fit in a unsigned long?
3011 if (ResultVal.isIntN(LongSize)) {
3012 // Does it fit in a signed long?
3013 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003014 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00003015 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003016 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00003017 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00003018 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003019 }
3020
Chris Lattner67ca9252007-05-21 01:08:44 +00003021 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003022 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00003023 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00003024
Chris Lattner67ca9252007-05-21 01:08:44 +00003025 // Does it fit in a unsigned long long?
3026 if (ResultVal.isIntN(LongLongSize)) {
3027 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00003028 // To be compatible with MSVC, hex integer literals ending with the
3029 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00003030 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3031 (getLangOptions().Microsoft && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003032 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00003033 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003034 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00003035 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00003036 }
3037 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003038
Chris Lattner67ca9252007-05-21 01:08:44 +00003039 // If we still couldn't decide a type, we probably have something that
3040 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003041 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00003042 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003043 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00003044 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00003045 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003046
Chris Lattner55258cf2008-05-09 05:59:00 +00003047 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00003048 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00003049 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003050 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00003051 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00003052
Chris Lattner1c20a172007-08-26 03:42:43 +00003053 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3054 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00003055 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00003056 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00003057
3058 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00003059}
3060
John McCalldadc5752010-08-24 06:29:42 +00003061ExprResult Sema::ActOnParenExpr(SourceLocation L,
John McCallb268a282010-08-23 23:25:46 +00003062 SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003063 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00003064 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00003065}
3066
Chandler Carruth62da79c2011-05-26 08:53:12 +00003067static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3068 SourceLocation Loc,
3069 SourceRange ArgRange) {
3070 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3071 // scalar or vector data type argument..."
3072 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3073 // type (C99 6.2.5p18) or void.
3074 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3075 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3076 << T << ArgRange;
3077 return true;
3078 }
3079
3080 assert((T->isVoidType() || !T->isIncompleteType()) &&
3081 "Scalar types should always be complete");
3082 return false;
3083}
3084
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003085static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3086 SourceLocation Loc,
3087 SourceRange ArgRange,
3088 UnaryExprOrTypeTrait TraitKind) {
3089 // C99 6.5.3.4p1:
3090 if (T->isFunctionType()) {
3091 // alignof(function) is allowed as an extension.
3092 if (TraitKind == UETT_SizeOf)
3093 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
3094 return false;
3095 }
3096
3097 // Allow sizeof(void)/alignof(void) as an extension.
3098 if (T->isVoidType()) {
3099 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
3100 return false;
3101 }
3102
3103 return true;
3104}
3105
3106static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3107 SourceLocation Loc,
3108 SourceRange ArgRange,
3109 UnaryExprOrTypeTrait TraitKind) {
3110 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
3111 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
3112 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3113 << T << (TraitKind == UETT_SizeOf)
3114 << ArgRange;
3115 return true;
3116 }
3117
3118 return false;
3119}
3120
Chandler Carruth14502c22011-05-26 08:53:10 +00003121/// \brief Check the constrains on expression operands to unary type expression
3122/// and type traits.
3123///
Chandler Carruth7c430c02011-05-27 01:33:31 +00003124/// Completes any types necessary and validates the constraints on the operand
3125/// expression. The logic mostly mirrors the type-based overload, but may modify
3126/// the expression as it completes the type for that expression through template
3127/// instantiation, etc.
Chandler Carruth14502c22011-05-26 08:53:10 +00003128bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op,
3129 UnaryExprOrTypeTrait ExprKind) {
Chandler Carruth7c430c02011-05-27 01:33:31 +00003130 QualType ExprTy = Op->getType();
3131
3132 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3133 // the result is the size of the referenced type."
3134 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3135 // result shall be the alignment of the referenced type."
3136 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3137 ExprTy = Ref->getPointeeType();
3138
3139 if (ExprKind == UETT_VecStep)
3140 return CheckVecStepTraitOperandType(*this, ExprTy, Op->getExprLoc(),
3141 Op->getSourceRange());
3142
3143 // Whitelist some types as extensions
3144 if (!CheckExtensionTraitOperandType(*this, ExprTy, Op->getExprLoc(),
3145 Op->getSourceRange(), ExprKind))
3146 return false;
3147
3148 if (RequireCompleteExprType(Op,
3149 PDiag(diag::err_sizeof_alignof_incomplete_type)
3150 << ExprKind << Op->getSourceRange(),
3151 std::make_pair(SourceLocation(), PDiag(0))))
3152 return true;
3153
3154 // Completeing the expression's type may have changed it.
3155 ExprTy = Op->getType();
3156 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3157 ExprTy = Ref->getPointeeType();
3158
3159 if (CheckObjCTraitOperandConstraints(*this, ExprTy, Op->getExprLoc(),
3160 Op->getSourceRange(), ExprKind))
3161 return true;
3162
3163 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00003164}
3165
3166/// \brief Check the constraints on operands to unary expression and type
3167/// traits.
3168///
3169/// This will complete any types necessary, and validate the various constraints
3170/// on those operands.
3171///
Steve Naroff71b59a92007-06-04 22:22:31 +00003172/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00003173/// C99 6.3.2.1p[2-4] all state:
3174/// Except when it is the operand of the sizeof operator ...
3175///
3176/// C++ [expr.sizeof]p4
3177/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3178/// standard conversions are not applied to the operand of sizeof.
3179///
3180/// This policy is followed for all of the unary trait expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003181bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType,
3182 SourceLocation OpLoc,
3183 SourceRange ExprRange,
3184 UnaryExprOrTypeTrait ExprKind) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003185 if (exprType->isDependentType())
3186 return false;
3187
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003188 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3189 // the result is the size of the referenced type."
3190 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3191 // result shall be the alignment of the referenced type."
3192 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
3193 exprType = Ref->getPointeeType();
3194
Chandler Carruth62da79c2011-05-26 08:53:12 +00003195 if (ExprKind == UETT_VecStep)
3196 return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003197
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003198 // Whitelist some types as extensions
3199 if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange,
3200 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00003201 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003202
Chris Lattner62975a72009-04-24 00:30:45 +00003203 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00003204 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00003205 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00003206 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003207
Chandler Carruthcea1aac2011-05-26 08:53:16 +00003208 if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange,
3209 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00003210 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003211
Chris Lattner62975a72009-04-24 00:30:45 +00003212 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00003213}
3214
Chandler Carruth14502c22011-05-26 08:53:10 +00003215static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00003216 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003217
Mike Stump11289f42009-09-09 15:08:12 +00003218 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00003219 if (isa<DeclRefExpr>(E))
3220 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003221
3222 // Cannot know anything else if the expression is dependent.
3223 if (E->isTypeDependent())
3224 return false;
3225
Douglas Gregor71235ec2009-05-02 02:18:30 +00003226 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003227 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3228 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00003229 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00003230 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00003231
3232 // Alignment of a field access is always okay, so long as it isn't a
3233 // bit-field.
3234 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00003235 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00003236 return false;
3237
Chandler Carruth14502c22011-05-26 08:53:10 +00003238 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003239}
3240
Chandler Carruth14502c22011-05-26 08:53:10 +00003241bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00003242 E = E->IgnoreParens();
3243
3244 // Cannot know anything else if the expression is dependent.
3245 if (E->isTypeDependent())
3246 return false;
3247
Chandler Carruth14502c22011-05-26 08:53:10 +00003248 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00003249}
3250
Douglas Gregor0950e412009-03-13 21:01:28 +00003251/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00003252ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003253Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3254 SourceLocation OpLoc,
3255 UnaryExprOrTypeTrait ExprKind,
3256 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00003257 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00003258 return ExprError();
3259
John McCallbcd03502009-12-07 02:54:59 +00003260 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00003261
Douglas Gregor0950e412009-03-13 21:01:28 +00003262 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00003263 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00003264 return ExprError();
3265
3266 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003267 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3268 Context.getSizeType(),
3269 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003270}
3271
3272/// \brief Build a sizeof or alignof expression given an expression
3273/// operand.
John McCalldadc5752010-08-24 06:29:42 +00003274ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00003275Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3276 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor0950e412009-03-13 21:01:28 +00003277 // Verify that the operand is valid.
3278 bool isInvalid = false;
3279 if (E->isTypeDependent()) {
3280 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003281 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003282 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003283 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003284 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00003285 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00003286 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00003287 isInvalid = true;
John McCall36226622010-10-12 02:09:17 +00003288 } else if (E->getType()->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00003289 ExprResult PE = CheckPlaceholderExpr(E);
John McCall36226622010-10-12 02:09:17 +00003290 if (PE.isInvalid()) return ExprError();
Chandler Carrutha923fb22011-05-29 07:32:14 +00003291 return CreateUnaryExprOrTypeTraitExpr(PE.take(), OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00003292 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00003293 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00003294 }
3295
3296 if (isInvalid)
3297 return ExprError();
3298
3299 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00003300 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00003301 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00003302 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003303}
3304
Peter Collingbournee190dee2011-03-11 19:24:49 +00003305/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3306/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00003307/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00003308ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003309Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3310 UnaryExprOrTypeTrait ExprKind, bool isType,
3311 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00003312 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003313 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00003314
Sebastian Redl6f282892008-11-11 17:56:53 +00003315 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00003316 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00003317 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003318 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00003319 }
Sebastian Redl6f282892008-11-11 17:56:53 +00003320
Douglas Gregor0950e412009-03-13 21:01:28 +00003321 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00003322 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00003323 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00003324}
3325
John Wiegley01296292011-04-08 18:41:53 +00003326static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
John McCall4bc41ae2010-11-18 19:01:18 +00003327 bool isReal) {
John Wiegley01296292011-04-08 18:41:53 +00003328 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00003329 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00003330
John McCall34376a62010-12-04 03:47:34 +00003331 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00003332 if (V.get()->getObjectKind() != OK_Ordinary) {
3333 V = S.DefaultLvalueConversion(V.take());
3334 if (V.isInvalid())
3335 return QualType();
3336 }
John McCall34376a62010-12-04 03:47:34 +00003337
Chris Lattnere267f5d2007-08-26 05:39:26 +00003338 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00003339 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00003340 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00003341
Chris Lattnere267f5d2007-08-26 05:39:26 +00003342 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00003343 if (V.get()->getType()->isArithmeticType())
3344 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003345
John McCall36226622010-10-12 02:09:17 +00003346 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00003347 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00003348 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003349 if (PR.get() != V.get()) {
3350 V = move(PR);
John McCall4bc41ae2010-11-18 19:01:18 +00003351 return CheckRealImagOperand(S, V, Loc, isReal);
John McCall36226622010-10-12 02:09:17 +00003352 }
3353
Chris Lattnere267f5d2007-08-26 05:39:26 +00003354 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003355 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Chris Lattner709322b2009-02-17 08:12:06 +00003356 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003357 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003358}
3359
3360
Chris Lattnere168f762006-11-10 05:29:30 +00003361
John McCalldadc5752010-08-24 06:29:42 +00003362ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003363Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003364 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003365 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003366 switch (Kind) {
3367 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003368 case tok::plusplus: Opc = UO_PostInc; break;
3369 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003370 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003371
John McCallb268a282010-08-23 23:25:46 +00003372 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003373}
3374
John McCall4bc41ae2010-11-18 19:01:18 +00003375/// Expressions of certain arbitrary types are forbidden by C from
3376/// having l-value type. These are:
3377/// - 'void', but not qualified void
3378/// - function types
3379///
3380/// The exact rule here is C99 6.3.2.1:
3381/// An lvalue is an expression with an object type or an incomplete
3382/// type other than void.
3383static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
3384 return ((T->isVoidType() && !T.hasQualifiers()) ||
3385 T->isFunctionType());
3386}
3387
John McCalldadc5752010-08-24 06:29:42 +00003388ExprResult
John McCallb268a282010-08-23 23:25:46 +00003389Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3390 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003391 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003392 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003393 if (Result.isInvalid()) return ExprError();
3394 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003395
John McCallb268a282010-08-23 23:25:46 +00003396 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003397
Douglas Gregor40412ac2008-11-19 17:17:41 +00003398 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003399 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003400 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003401 Context.DependentTy,
3402 VK_LValue, OK_Ordinary,
3403 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003404 }
3405
Mike Stump11289f42009-09-09 15:08:12 +00003406 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003407 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003408 LHSExp->getType()->isEnumeralType() ||
3409 RHSExp->getType()->isRecordType() ||
3410 RHSExp->getType()->isEnumeralType())) {
John McCallb268a282010-08-23 23:25:46 +00003411 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003412 }
3413
John McCallb268a282010-08-23 23:25:46 +00003414 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003415}
3416
3417
John McCalldadc5752010-08-24 06:29:42 +00003418ExprResult
John McCallb268a282010-08-23 23:25:46 +00003419Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3420 Expr *Idx, SourceLocation RLoc) {
3421 Expr *LHSExp = Base;
3422 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003423
Chris Lattner36d572b2007-07-16 00:14:47 +00003424 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003425 if (!LHSExp->getType()->getAs<VectorType>()) {
3426 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3427 if (Result.isInvalid())
3428 return ExprError();
3429 LHSExp = Result.take();
3430 }
3431 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3432 if (Result.isInvalid())
3433 return ExprError();
3434 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003435
Chris Lattner36d572b2007-07-16 00:14:47 +00003436 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003437 ExprValueKind VK = VK_LValue;
3438 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003439
Steve Naroffc1aadb12007-03-28 21:49:40 +00003440 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003441 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003442 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003443 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003444 Expr *BaseExpr, *IndexExpr;
3445 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003446 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3447 BaseExpr = LHSExp;
3448 IndexExpr = RHSExp;
3449 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003450 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003451 BaseExpr = LHSExp;
3452 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003453 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003454 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003455 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003456 BaseExpr = RHSExp;
3457 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003458 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003459 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003460 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003461 BaseExpr = LHSExp;
3462 IndexExpr = RHSExp;
3463 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003464 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003465 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003466 // Handle the uncommon case of "123[Ptr]".
3467 BaseExpr = RHSExp;
3468 IndexExpr = LHSExp;
3469 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003470 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003471 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003472 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003473 VK = LHSExp->getValueKind();
3474 if (VK != VK_RValue)
3475 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003476
Chris Lattner36d572b2007-07-16 00:14:47 +00003477 // FIXME: need to deal with const...
3478 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003479 } else if (LHSTy->isArrayType()) {
3480 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003481 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003482 // wasn't promoted because of the C90 rule that doesn't
3483 // allow promoting non-lvalue arrays. Warn, then
3484 // force the promotion here.
3485 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3486 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003487 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3488 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003489 LHSTy = LHSExp->getType();
3490
3491 BaseExpr = LHSExp;
3492 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003493 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003494 } else if (RHSTy->isArrayType()) {
3495 // Same as previous, except for 123[f().a] case
3496 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3497 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003498 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3499 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003500 RHSTy = RHSExp->getType();
3501
3502 BaseExpr = RHSExp;
3503 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003504 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003505 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003506 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3507 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003508 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003509 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003510 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003511 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3512 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003513
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003514 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003515 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3516 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003517 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3518
Douglas Gregorac1fb652009-03-24 19:52:54 +00003519 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003520 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3521 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003522 // incomplete types are not object types.
3523 if (ResultType->isFunctionType()) {
3524 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3525 << ResultType << BaseExpr->getSourceRange();
3526 return ExprError();
3527 }
Mike Stump11289f42009-09-09 15:08:12 +00003528
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003529 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3530 // GNU extension: subscripting on pointer to void
3531 Diag(LLoc, diag::ext_gnu_void_ptr)
3532 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003533
3534 // C forbids expressions of unqualified void type from being l-values.
3535 // See IsCForbiddenLValueType.
3536 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003537 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003538 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003539 PDiag(diag::err_subscript_incomplete_type)
3540 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003541 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003542
Chris Lattner62975a72009-04-24 00:30:45 +00003543 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003544 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003545 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3546 << ResultType << BaseExpr->getSourceRange();
3547 return ExprError();
3548 }
Mike Stump11289f42009-09-09 15:08:12 +00003549
John McCall4bc41ae2010-11-18 19:01:18 +00003550 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3551 !IsCForbiddenLValueType(Context, ResultType));
3552
Mike Stump4e1f26a2009-02-19 03:04:26 +00003553 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003554 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003555}
3556
John McCall4bc41ae2010-11-18 19:01:18 +00003557/// Check an ext-vector component access expression.
3558///
3559/// VK should be set in advance to the value kind of the base
3560/// expression.
3561static QualType
3562CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3563 SourceLocation OpLoc, const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00003564 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00003565 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3566 // see FIXME there.
3567 //
3568 // FIXME: This logic can be greatly simplified by splitting it along
3569 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00003570 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00003571
Steve Narofff8fd09e2007-07-27 22:15:19 +00003572 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003573 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003574
Mike Stump4e1f26a2009-02-19 03:04:26 +00003575 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00003576 // special names that indicate a subset of exactly half the elements are
3577 // to be selected.
3578 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003579
Nate Begemanbb70bf62009-01-18 01:47:54 +00003580 // This flag determines whether or not CompName has an 's' char prefix,
3581 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00003582 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00003583
John McCall4bc41ae2010-11-18 19:01:18 +00003584 bool HasRepeated = false;
3585 bool HasIndex[16] = {};
3586
3587 int Idx;
3588
Nate Begemanf322eab2008-05-09 06:41:27 +00003589 // Check that we've found one of the special components, or that the component
3590 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003591 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00003592 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3593 HalvingSwizzle = true;
John McCall4bc41ae2010-11-18 19:01:18 +00003594 } else if (!HexSwizzle &&
3595 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3596 do {
3597 if (HasIndex[Idx]) HasRepeated = true;
3598 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003599 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003600 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3601 } else {
3602 if (HexSwizzle) compStr++;
3603 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3604 if (HasIndex[Idx]) HasRepeated = true;
3605 HasIndex[Idx] = true;
Chris Lattner7e152db2007-08-02 22:33:49 +00003606 compStr++;
John McCall4bc41ae2010-11-18 19:01:18 +00003607 }
Chris Lattner7e152db2007-08-02 22:33:49 +00003608 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00003609
Mike Stump4e1f26a2009-02-19 03:04:26 +00003610 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00003611 // We didn't get to the end of the string. This means the component names
3612 // didn't come from the same set *or* we encountered an illegal name.
John McCall4bc41ae2010-11-18 19:01:18 +00003613 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Benjamin Kramere8394df2010-08-11 14:47:12 +00003614 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00003615 return QualType();
3616 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003617
Nate Begemanbb70bf62009-01-18 01:47:54 +00003618 // Ensure no component accessor exceeds the width of the vector type it
3619 // operates on.
3620 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003621 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003622
3623 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00003624 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00003625
3626 while (*compStr) {
3627 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
John McCall4bc41ae2010-11-18 19:01:18 +00003628 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Nate Begemanbb70bf62009-01-18 01:47:54 +00003629 << baseType << SourceRange(CompLoc);
3630 return QualType();
3631 }
3632 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00003633 }
Nate Begemanf322eab2008-05-09 06:41:27 +00003634
Steve Narofff8fd09e2007-07-27 22:15:19 +00003635 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003636 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00003637 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00003638 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00003639 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanac8183a2009-12-15 18:13:04 +00003640 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00003641 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00003642 if (HexSwizzle)
3643 CompSize--;
3644
Steve Narofff8fd09e2007-07-27 22:15:19 +00003645 if (CompSize == 1)
3646 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003647
John McCall4bc41ae2010-11-18 19:01:18 +00003648 if (HasRepeated) VK = VK_RValue;
3649
3650 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003651 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00003652 // diagostics look bad. We want extended vector types to appear built-in.
John McCall4bc41ae2010-11-18 19:01:18 +00003653 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3654 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3655 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00003656 }
3657 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00003658}
3659
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003660static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00003661 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003662 const Selector &Sel,
3663 ASTContext &Context) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003664 if (Member)
3665 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3666 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003667 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003668 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00003669
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003670 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3671 E = PDecl->protocol_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003672 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3673 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003674 return D;
3675 }
3676 return 0;
3677}
3678
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003679static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3680 IdentifierInfo *Member,
3681 const Selector &Sel,
3682 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003683 // Check protocols on qualified interfaces.
3684 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00003685 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003686 E = QIdTy->qual_end(); I != E; ++I) {
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003687 if (Member)
3688 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3689 GDecl = PD;
3690 break;
3691 }
3692 // Also must look for a getter or setter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003693 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003694 GDecl = OMD;
3695 break;
3696 }
3697 }
3698 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00003699 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003700 E = QIdTy->qual_end(); I != E; ++I) {
3701 // Search in the protocol-qualifier list of current protocol.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003702 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3703 Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00003704 if (GDecl)
3705 return GDecl;
3706 }
3707 }
3708 return GDecl;
3709}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00003710
John McCalldadc5752010-08-24 06:29:42 +00003711ExprResult
John McCallb268a282010-08-23 23:25:46 +00003712Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
John McCall2d74de92009-12-01 22:10:20 +00003713 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00003714 const CXXScopeSpec &SS,
3715 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003716 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003717 const TemplateArgumentListInfo *TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00003718 // Even in dependent contexts, try to diagnose base expressions with
3719 // obviously wrong types, e.g.:
3720 //
3721 // T* t;
3722 // t.f;
3723 //
3724 // In Obj-C++, however, the above expression is valid, since it could be
3725 // accessing the 'f' property if T is an Obj-C interface. The extra check
3726 // allows this, while still reporting an error if T is a struct pointer.
3727 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00003728 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00003729 if (PT && (!getLangOptions().ObjC1 ||
3730 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00003731 assert(BaseExpr && "cannot happen with implicit member accesses");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003732 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00003733 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00003734 return ExprError();
3735 }
3736 }
3737
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003738 assert(BaseType->isDependentType() ||
3739 NameInfo.getName().isDependentName() ||
Douglas Gregor41f90302010-04-12 20:54:26 +00003740 isDependentScopeSpecifier(SS));
John McCall10eae182009-11-30 22:42:35 +00003741
3742 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3743 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00003744 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003745 IsArrow, OpLoc,
Douglas Gregore16af532011-02-28 18:50:33 +00003746 SS.getWithLocInContext(Context),
John McCall10eae182009-11-30 22:42:35 +00003747 FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003748 NameInfo, TemplateArgs));
John McCall10eae182009-11-30 22:42:35 +00003749}
3750
3751/// We know that the given qualified member reference points only to
3752/// declarations which do not belong to the static type of the base
3753/// expression. Diagnose the problem.
3754static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3755 Expr *BaseExpr,
3756 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003757 const CXXScopeSpec &SS,
John McCallf3a88602011-02-03 08:15:49 +00003758 NamedDecl *rep,
3759 const DeclarationNameInfo &nameInfo) {
John McCallcd4b4772009-12-02 03:53:29 +00003760 // If this is an implicit member access, use a different set of
3761 // diagnostics.
3762 if (!BaseExpr)
John McCallf3a88602011-02-03 08:15:49 +00003763 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
John McCall10eae182009-11-30 22:42:35 +00003764
John McCallf3a88602011-02-03 08:15:49 +00003765 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3766 << SS.getRange() << rep << BaseType;
John McCall10eae182009-11-30 22:42:35 +00003767}
3768
3769// Check whether the declarations we found through a nested-name
3770// specifier in a member expression are actually members of the base
3771// type. The restriction here is:
3772//
3773// C++ [expr.ref]p2:
3774// ... In these cases, the id-expression shall name a
3775// member of the class or of one of its base classes.
3776//
3777// So it's perfectly legitimate for the nested-name specifier to name
3778// an unrelated class, and for us to find an overload set including
3779// decls from classes which are not superclasses, as long as the decl
3780// we actually pick through overload resolution is from a superclass.
3781bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3782 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00003783 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003784 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00003785 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3786 if (!BaseRT) {
3787 // We can't check this yet because the base type is still
3788 // dependent.
3789 assert(BaseType->isDependentType());
3790 return false;
3791 }
3792 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00003793
3794 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00003795 // If this is an implicit member reference and we find a
3796 // non-instance member, it's not an error.
John McCalla8ae2222010-04-06 21:38:20 +00003797 if (!BaseExpr && !(*I)->isCXXInstanceMember())
John McCall2d74de92009-12-01 22:10:20 +00003798 return false;
John McCall10eae182009-11-30 22:42:35 +00003799
John McCall2d74de92009-12-01 22:10:20 +00003800 // Note that we use the DC of the decl, not the underlying decl.
Eli Friedman75300492010-07-27 20:51:02 +00003801 DeclContext *DC = (*I)->getDeclContext();
3802 while (DC->isTransparentContext())
3803 DC = DC->getParent();
John McCall2d74de92009-12-01 22:10:20 +00003804
Douglas Gregora9c3e822010-07-28 22:27:52 +00003805 if (!DC->isRecord())
3806 continue;
3807
John McCall2d74de92009-12-01 22:10:20 +00003808 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
Eli Friedman75300492010-07-27 20:51:02 +00003809 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
John McCall2d74de92009-12-01 22:10:20 +00003810
3811 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3812 return false;
3813 }
3814
John McCallf3a88602011-02-03 08:15:49 +00003815 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3816 R.getRepresentativeDecl(),
3817 R.getLookupNameInfo());
John McCall2d74de92009-12-01 22:10:20 +00003818 return true;
3819}
3820
3821static bool
3822LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3823 SourceRange BaseRange, const RecordType *RTy,
John McCalle9cccd82010-06-16 08:42:20 +00003824 SourceLocation OpLoc, CXXScopeSpec &SS,
3825 bool HasTemplateArgs) {
John McCall2d74de92009-12-01 22:10:20 +00003826 RecordDecl *RDecl = RTy->getDecl();
3827 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor89336232010-03-29 23:34:08 +00003828 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCall2d74de92009-12-01 22:10:20 +00003829 << BaseRange))
3830 return true;
3831
John McCalle9cccd82010-06-16 08:42:20 +00003832 if (HasTemplateArgs) {
3833 // LookupTemplateName doesn't expect these both to exist simultaneously.
3834 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3835
3836 bool MOUS;
3837 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3838 return false;
3839 }
3840
John McCall2d74de92009-12-01 22:10:20 +00003841 DeclContext *DC = RDecl;
3842 if (SS.isSet()) {
3843 // If the member name was a qualified-id, look into the
3844 // nested-name-specifier.
3845 DC = SemaRef.computeDeclContext(SS, false);
3846
John McCall0b66eb32010-05-01 00:40:08 +00003847 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
John McCallcd4b4772009-12-02 03:53:29 +00003848 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3849 << SS.getRange() << DC;
3850 return true;
3851 }
3852
John McCall2d74de92009-12-01 22:10:20 +00003853 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003854
John McCall2d74de92009-12-01 22:10:20 +00003855 if (!isa<TypeDecl>(DC)) {
3856 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3857 << DC << SS.getRange();
3858 return true;
John McCall10eae182009-11-30 22:42:35 +00003859 }
3860 }
3861
John McCall2d74de92009-12-01 22:10:20 +00003862 // The record definition is complete, now look up the member.
3863 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00003864
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003865 if (!R.empty())
3866 return false;
3867
3868 // We didn't find anything with the given name, so try to correct
3869 // for typos.
3870 DeclarationName Name = R.getLookupName();
Alexis Huntc46382e2010-04-28 23:02:27 +00003871 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00003872 !R.empty() &&
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003873 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3874 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3875 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00003876 << FixItHint::CreateReplacement(R.getNameLoc(),
3877 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00003878 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3879 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3880 << ND->getDeclName();
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003881 return false;
3882 } else {
3883 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003884 R.setLookupName(Name);
Douglas Gregoraf2bd472009-12-31 07:42:17 +00003885 }
3886
John McCall10eae182009-11-30 22:42:35 +00003887 return false;
3888}
3889
John McCalldadc5752010-08-24 06:29:42 +00003890ExprResult
John McCallb268a282010-08-23 23:25:46 +00003891Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00003892 SourceLocation OpLoc, bool IsArrow,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003893 CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00003894 NamedDecl *FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003895 const DeclarationNameInfo &NameInfo,
John McCall10eae182009-11-30 22:42:35 +00003896 const TemplateArgumentListInfo *TemplateArgs) {
John McCallcd4b4772009-12-02 03:53:29 +00003897 if (BaseType->isDependentType() ||
3898 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallb268a282010-08-23 23:25:46 +00003899 return ActOnDependentMemberExpr(Base, BaseType,
John McCall10eae182009-11-30 22:42:35 +00003900 IsArrow, OpLoc,
3901 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003902 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003903
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003904 LookupResult R(*this, NameInfo, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00003905
John McCall2d74de92009-12-01 22:10:20 +00003906 // Implicit member accesses.
3907 if (!Base) {
3908 QualType RecordTy = BaseType;
3909 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3910 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3911 RecordTy->getAs<RecordType>(),
John McCalle9cccd82010-06-16 08:42:20 +00003912 OpLoc, SS, TemplateArgs != 0))
John McCall2d74de92009-12-01 22:10:20 +00003913 return ExprError();
3914
3915 // Explicit member accesses.
3916 } else {
John Wiegley01296292011-04-08 18:41:53 +00003917 ExprResult BaseResult = Owned(Base);
John McCalldadc5752010-08-24 06:29:42 +00003918 ExprResult Result =
John Wiegley01296292011-04-08 18:41:53 +00003919 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCall48871652010-08-21 09:40:31 +00003920 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
John McCall2d74de92009-12-01 22:10:20 +00003921
John Wiegley01296292011-04-08 18:41:53 +00003922 if (BaseResult.isInvalid())
3923 return ExprError();
3924 Base = BaseResult.take();
3925
John McCall2d74de92009-12-01 22:10:20 +00003926 if (Result.isInvalid()) {
3927 Owned(Base);
3928 return ExprError();
3929 }
3930
3931 if (Result.get())
3932 return move(Result);
Sebastian Redlfa1f70f2010-05-07 09:25:11 +00003933
3934 // LookupMemberExpr can modify Base, and thus change BaseType
3935 BaseType = Base->getType();
John McCall10eae182009-11-30 22:42:35 +00003936 }
3937
John McCallb268a282010-08-23 23:25:46 +00003938 return BuildMemberReferenceExpr(Base, BaseType,
John McCall38836f02010-01-15 08:34:02 +00003939 OpLoc, IsArrow, SS, FirstQualifierInScope,
3940 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00003941}
3942
John McCalldadc5752010-08-24 06:29:42 +00003943ExprResult
John McCallb268a282010-08-23 23:25:46 +00003944Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
John McCall2d74de92009-12-01 22:10:20 +00003945 SourceLocation OpLoc, bool IsArrow,
3946 const CXXScopeSpec &SS,
John McCall38836f02010-01-15 08:34:02 +00003947 NamedDecl *FirstQualifierInScope,
John McCall10eae182009-11-30 22:42:35 +00003948 LookupResult &R,
Douglas Gregorb139cd52010-05-01 20:49:11 +00003949 const TemplateArgumentListInfo *TemplateArgs,
3950 bool SuppressQualifierCheck) {
John McCall2d74de92009-12-01 22:10:20 +00003951 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00003952 if (IsArrow) {
3953 assert(BaseType->isPointerType());
3954 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3955 }
John McCalla8ae2222010-04-06 21:38:20 +00003956 R.setBaseObjectType(BaseType);
John McCall10eae182009-11-30 22:42:35 +00003957
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003958 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3959 DeclarationName MemberName = MemberNameInfo.getName();
3960 SourceLocation MemberLoc = MemberNameInfo.getLoc();
John McCall10eae182009-11-30 22:42:35 +00003961
3962 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00003963 return ExprError();
3964
John McCall10eae182009-11-30 22:42:35 +00003965 if (R.empty()) {
3966 // Rederive where we looked up.
3967 DeclContext *DC = (SS.isSet()
3968 ? computeDeclContext(SS, false)
3969 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00003970
John McCall10eae182009-11-30 22:42:35 +00003971 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00003972 << MemberName << DC
3973 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00003974 return ExprError();
3975 }
3976
John McCall38836f02010-01-15 08:34:02 +00003977 // Diagnose lookups that find only declarations from a non-base
3978 // type. This is possible for either qualified lookups (which may
3979 // have been qualified with an unrelated type) or implicit member
3980 // expressions (which were found with unqualified lookup and thus
3981 // may have come from an enclosing scope). Note that it's okay for
3982 // lookup to find declarations from a non-base type as long as those
3983 // aren't the ones picked by overload resolution.
3984 if ((SS.isSet() || !BaseExpr ||
3985 (isa<CXXThisExpr>(BaseExpr) &&
3986 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00003987 !SuppressQualifierCheck &&
John McCall38836f02010-01-15 08:34:02 +00003988 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00003989 return ExprError();
3990
3991 // Construct an unresolved result if we in fact got an unresolved
3992 // result.
3993 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall58cc69d2010-01-27 01:50:18 +00003994 // Suppress any lookup-related diagnostics; we'll do these when we
3995 // pick a member.
3996 R.suppressDiagnostics();
3997
John McCall10eae182009-11-30 22:42:35 +00003998 UnresolvedMemberExpr *MemExpr
Douglas Gregora6e053e2010-12-15 01:34:56 +00003999 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00004000 BaseExpr, BaseExprType,
4001 IsArrow, OpLoc,
Douglas Gregor0da1d432011-02-28 20:01:57 +00004002 SS.getWithLocInContext(Context),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004003 MemberNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00004004 TemplateArgs, R.begin(), R.end());
John McCall10eae182009-11-30 22:42:35 +00004005
4006 return Owned(MemExpr);
4007 }
4008
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004009 assert(R.isSingleResult());
John McCalla8ae2222010-04-06 21:38:20 +00004010 DeclAccessPair FoundDecl = R.begin().getPair();
John McCall10eae182009-11-30 22:42:35 +00004011 NamedDecl *MemberDecl = R.getFoundDecl();
4012
4013 // FIXME: diagnose the presence of template arguments now.
4014
4015 // If the decl being referenced had an error, return an error for this
4016 // sub-expr without emitting another error, in order to avoid cascading
4017 // error cases.
4018 if (MemberDecl->isInvalidDecl())
4019 return ExprError();
4020
John McCall2d74de92009-12-01 22:10:20 +00004021 // Handle the implicit-member-access case.
4022 if (!BaseExpr) {
4023 // If this is not an instance member, convert to a non-member access.
John McCalla8ae2222010-04-06 21:38:20 +00004024 if (!MemberDecl->isCXXInstanceMember())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004025 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
John McCall2d74de92009-12-01 22:10:20 +00004026
Douglas Gregorb15af892010-01-07 23:12:05 +00004027 SourceLocation Loc = R.getNameLoc();
4028 if (SS.getRange().isValid())
4029 Loc = SS.getRange().getBegin();
4030 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCall2d74de92009-12-01 22:10:20 +00004031 }
4032
John McCall10eae182009-11-30 22:42:35 +00004033 bool ShouldCheckUse = true;
4034 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
4035 // Don't diagnose the use of a virtual member function unless it's
4036 // explicitly qualified.
4037 if (MD->isVirtual() && !SS.isSet())
4038 ShouldCheckUse = false;
4039 }
4040
4041 // Check the use of this member.
4042 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
4043 Owned(BaseExpr);
4044 return ExprError();
4045 }
4046
John McCall34376a62010-12-04 03:47:34 +00004047 // Perform a property load on the base regardless of whether we
4048 // actually need it for the declaration.
John Wiegley01296292011-04-08 18:41:53 +00004049 if (BaseExpr->getObjectKind() == OK_ObjCProperty) {
4050 ExprResult Result = ConvertPropertyForRValue(BaseExpr);
4051 if (Result.isInvalid())
4052 return ExprError();
4053 BaseExpr = Result.take();
4054 }
John McCall34376a62010-12-04 03:47:34 +00004055
John McCallfeb624a2010-11-23 20:48:44 +00004056 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
4057 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
4058 SS, FD, FoundDecl, MemberNameInfo);
John McCall10eae182009-11-30 22:42:35 +00004059
Francois Pichet783dd6e2010-11-21 06:08:52 +00004060 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
4061 // We may have found a field within an anonymous union or struct
4062 // (C++ [class.union]).
John McCallf3a88602011-02-03 08:15:49 +00004063 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
John McCall34376a62010-12-04 03:47:34 +00004064 BaseExpr, OpLoc);
Francois Pichet783dd6e2010-11-21 06:08:52 +00004065
John McCall10eae182009-11-30 22:42:35 +00004066 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
4067 MarkDeclarationReferenced(MemberLoc, Var);
4068 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004069 Var, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00004070 Var->getType().getNonReferenceType(),
John McCall4bc41ae2010-11-18 19:01:18 +00004071 VK_LValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00004072 }
4073
John McCall7decc9e2010-11-18 06:31:45 +00004074 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
John McCall0009fcc2011-04-26 20:42:42 +00004075 ExprValueKind valueKind;
4076 QualType type;
4077 if (MemberFn->isInstance()) {
4078 valueKind = VK_RValue;
4079 type = Context.BoundMemberTy;
4080 } else {
4081 valueKind = VK_LValue;
4082 type = MemberFn->getType();
4083 }
4084
John McCall10eae182009-11-30 22:42:35 +00004085 MarkDeclarationReferenced(MemberLoc, MemberDecl);
4086 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004087 MemberFn, FoundDecl, MemberNameInfo,
John McCall0009fcc2011-04-26 20:42:42 +00004088 type, valueKind, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00004089 }
John McCall7decc9e2010-11-18 06:31:45 +00004090 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
John McCall10eae182009-11-30 22:42:35 +00004091
4092 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
4093 MarkDeclarationReferenced(MemberLoc, MemberDecl);
4094 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004095 Enum, FoundDecl, MemberNameInfo,
John McCall7decc9e2010-11-18 06:31:45 +00004096 Enum->getType(), VK_RValue, OK_Ordinary));
John McCall10eae182009-11-30 22:42:35 +00004097 }
4098
4099 Owned(BaseExpr);
4100
Douglas Gregor861eb802010-04-25 20:55:08 +00004101 // We found something that we didn't expect. Complain.
John McCall10eae182009-11-30 22:42:35 +00004102 if (isa<TypeDecl>(MemberDecl))
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004103 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
Douglas Gregor861eb802010-04-25 20:55:08 +00004104 << MemberName << BaseType << int(IsArrow);
4105 else
4106 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
4107 << MemberName << BaseType << int(IsArrow);
John McCall10eae182009-11-30 22:42:35 +00004108
Douglas Gregor861eb802010-04-25 20:55:08 +00004109 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
4110 << MemberName;
Douglas Gregor516d6722010-04-25 21:15:30 +00004111 R.suppressDiagnostics();
Douglas Gregor861eb802010-04-25 20:55:08 +00004112 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00004113}
4114
John McCall68fc88ec2010-12-15 16:46:44 +00004115/// Given that normal member access failed on the given expression,
4116/// and given that the expression's type involves builtin-id or
4117/// builtin-Class, decide whether substituting in the redefinition
4118/// types would be profitable. The redefinition type is whatever
4119/// this translation unit tried to typedef to id/Class; we store
4120/// it to the side and then re-use it in places like this.
John Wiegley01296292011-04-08 18:41:53 +00004121static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
John McCall68fc88ec2010-12-15 16:46:44 +00004122 const ObjCObjectPointerType *opty
John Wiegley01296292011-04-08 18:41:53 +00004123 = base.get()->getType()->getAs<ObjCObjectPointerType>();
John McCall68fc88ec2010-12-15 16:46:44 +00004124 if (!opty) return false;
4125
4126 const ObjCObjectType *ty = opty->getObjectType();
4127
4128 QualType redef;
4129 if (ty->isObjCId()) {
4130 redef = S.Context.ObjCIdRedefinitionType;
4131 } else if (ty->isObjCClass()) {
4132 redef = S.Context.ObjCClassRedefinitionType;
4133 } else {
4134 return false;
4135 }
4136
4137 // Do the substitution as long as the redefinition type isn't just a
4138 // possibly-qualified pointer to builtin-id or builtin-Class again.
4139 opty = redef->getAs<ObjCObjectPointerType>();
4140 if (opty && !opty->getObjectType()->getInterface() != 0)
4141 return false;
4142
John Wiegley01296292011-04-08 18:41:53 +00004143 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
John McCall68fc88ec2010-12-15 16:46:44 +00004144 return true;
4145}
4146
John McCall10eae182009-11-30 22:42:35 +00004147/// Look up the given member of the given non-type-dependent
4148/// expression. This can return in one of two ways:
4149/// * If it returns a sentinel null-but-valid result, the caller will
4150/// assume that lookup was performed and the results written into
4151/// the provided structure. It will take over from there.
4152/// * Otherwise, the returned expression will be produced in place of
4153/// an ordinary member expression.
4154///
4155/// The ObjCImpDecl bit is a gross hack that will need to be properly
4156/// fixed for ObjC++.
John McCalldadc5752010-08-24 06:29:42 +00004157ExprResult
John Wiegley01296292011-04-08 18:41:53 +00004158Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
John McCalla928c652009-12-07 22:46:59 +00004159 bool &IsArrow, SourceLocation OpLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004160 CXXScopeSpec &SS,
John McCall48871652010-08-21 09:40:31 +00004161 Decl *ObjCImpDecl, bool HasTemplateArgs) {
John Wiegley01296292011-04-08 18:41:53 +00004162 assert(BaseExpr.get() && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00004163
Steve Naroffeaaae462007-12-16 21:42:28 +00004164 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00004165 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004166
John Wiegley01296292011-04-08 18:41:53 +00004167 if (IsArrow) {
4168 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4169 if (BaseExpr.isInvalid())
4170 return ExprError();
4171 }
4172
4173 QualType BaseType = BaseExpr.get()->getType();
John McCall10eae182009-11-30 22:42:35 +00004174 assert(!BaseType->isDependentType());
4175
4176 DeclarationName MemberName = R.getLookupName();
4177 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00004178
John McCall68fc88ec2010-12-15 16:46:44 +00004179 // For later type-checking purposes, turn arrow accesses into dot
4180 // accesses. The only access type we support that doesn't follow
4181 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
4182 // and those never use arrows, so this is unaffected.
4183 if (IsArrow) {
4184 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4185 BaseType = Ptr->getPointeeType();
4186 else if (const ObjCObjectPointerType *Ptr
4187 = BaseType->getAs<ObjCObjectPointerType>())
4188 BaseType = Ptr->getPointeeType();
4189 else if (BaseType->isRecordType()) {
4190 // Recover from arrow accesses to records, e.g.:
4191 // struct MyRecord foo;
4192 // foo->bar
4193 // This is actually well-formed in C++ if MyRecord has an
4194 // overloaded operator->, but that should have been dealt with
4195 // by now.
4196 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley01296292011-04-08 18:41:53 +00004197 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
John McCall68fc88ec2010-12-15 16:46:44 +00004198 << FixItHint::CreateReplacement(OpLoc, ".");
4199 IsArrow = false;
John McCall0009fcc2011-04-26 20:42:42 +00004200 } else if (BaseType == Context.BoundMemberTy) {
4201 goto fail;
John McCall68fc88ec2010-12-15 16:46:44 +00004202 } else {
4203 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
John Wiegley01296292011-04-08 18:41:53 +00004204 << BaseType << BaseExpr.get()->getSourceRange();
John McCall68fc88ec2010-12-15 16:46:44 +00004205 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00004206 }
4207 }
4208
John McCall68fc88ec2010-12-15 16:46:44 +00004209 // Handle field access to simple records.
4210 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John Wiegley01296292011-04-08 18:41:53 +00004211 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
John McCall68fc88ec2010-12-15 16:46:44 +00004212 RTy, OpLoc, SS, HasTemplateArgs))
4213 return ExprError();
4214
4215 // Returning valid-but-null is how we indicate to the caller that
4216 // the lookup result was filled in.
4217 return Owned((Expr*) 0);
David Chisnall9f57c292009-08-17 16:35:33 +00004218 }
John McCall10eae182009-11-30 22:42:35 +00004219
John McCall68fc88ec2010-12-15 16:46:44 +00004220 // Handle ivar access to Objective-C objects.
4221 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004222 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John McCall68fc88ec2010-12-15 16:46:44 +00004223
4224 // There are three cases for the base type:
4225 // - builtin id (qualified or unqualified)
4226 // - builtin Class (qualified or unqualified)
4227 // - an interface
4228 ObjCInterfaceDecl *IDecl = OTy->getInterface();
4229 if (!IDecl) {
4230 // There's an implicit 'isa' ivar on all objects.
4231 // But we only actually find it this way on objects of type 'id',
4232 // apparently.
4233 if (OTy->isObjCId() && Member->isStr("isa"))
John Wiegley01296292011-04-08 18:41:53 +00004234 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
John McCall68fc88ec2010-12-15 16:46:44 +00004235 Context.getObjCClassType()));
4236
4237 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4238 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4239 ObjCImpDecl, HasTemplateArgs);
4240 goto fail;
4241 }
4242
4243 ObjCInterfaceDecl *ClassDeclared;
4244 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
4245
4246 if (!IV) {
4247 // Attempt to correct for typos in ivar names.
4248 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
4249 LookupMemberName);
4250 if (CorrectTypo(Res, 0, 0, IDecl, false,
4251 IsArrow ? CTC_ObjCIvarLookup
4252 : CTC_ObjCPropertyLookup) &&
4253 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
4254 Diag(R.getNameLoc(),
4255 diag::err_typecheck_member_reference_ivar_suggest)
4256 << IDecl->getDeclName() << MemberName << IV->getDeclName()
4257 << FixItHint::CreateReplacement(R.getNameLoc(),
4258 IV->getNameAsString());
4259 Diag(IV->getLocation(), diag::note_previous_decl)
4260 << IV->getDeclName();
4261 } else {
4262 Res.clear();
4263 Res.setLookupName(Member);
4264
4265 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
4266 << IDecl->getDeclName() << MemberName
John Wiegley01296292011-04-08 18:41:53 +00004267 << BaseExpr.get()->getSourceRange();
John McCall68fc88ec2010-12-15 16:46:44 +00004268 return ExprError();
4269 }
4270 }
4271
4272 // If the decl being referenced had an error, return an error for this
4273 // sub-expr without emitting another error, in order to avoid cascading
4274 // error cases.
4275 if (IV->isInvalidDecl())
4276 return ExprError();
4277
4278 // Check whether we can reference this field.
4279 if (DiagnoseUseOfDecl(IV, MemberLoc))
4280 return ExprError();
4281 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
4282 IV->getAccessControl() != ObjCIvarDecl::Package) {
4283 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
4284 if (ObjCMethodDecl *MD = getCurMethodDecl())
4285 ClassOfMethodDecl = MD->getClassInterface();
4286 else if (ObjCImpDecl && getCurFunctionDecl()) {
4287 // Case of a c-function declared inside an objc implementation.
4288 // FIXME: For a c-style function nested inside an objc implementation
4289 // class, there is no implementation context available, so we pass
4290 // down the context as argument to this routine. Ideally, this context
4291 // need be passed down in the AST node and somehow calculated from the
4292 // AST for a function decl.
4293 if (ObjCImplementationDecl *IMPD =
4294 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
4295 ClassOfMethodDecl = IMPD->getClassInterface();
4296 else if (ObjCCategoryImplDecl* CatImplClass =
4297 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
4298 ClassOfMethodDecl = CatImplClass->getClassInterface();
4299 }
4300
4301 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
4302 if (ClassDeclared != IDecl ||
4303 ClassOfMethodDecl != ClassDeclared)
4304 Diag(MemberLoc, diag::error_private_ivar_access)
4305 << IV->getDeclName();
4306 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
4307 // @protected
4308 Diag(MemberLoc, diag::error_protected_ivar_access)
4309 << IV->getDeclName();
4310 }
4311
4312 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
John Wiegley01296292011-04-08 18:41:53 +00004313 MemberLoc, BaseExpr.take(),
John McCall68fc88ec2010-12-15 16:46:44 +00004314 IsArrow));
4315 }
4316
4317 // Objective-C property access.
4318 const ObjCObjectPointerType *OPT;
4319 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
4320 // This actually uses the base as an r-value.
John Wiegley01296292011-04-08 18:41:53 +00004321 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
4322 if (BaseExpr.isInvalid())
4323 return ExprError();
4324
4325 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
John McCall68fc88ec2010-12-15 16:46:44 +00004326
4327 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
4328
4329 const ObjCObjectType *OT = OPT->getObjectType();
4330
4331 // id, with and without qualifiers.
4332 if (OT->isObjCId()) {
4333 // Check protocols on qualified interfaces.
4334 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
4335 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
4336 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
4337 // Check the use of this declaration
4338 if (DiagnoseUseOfDecl(PD, MemberLoc))
4339 return ExprError();
4340
Douglas Gregor33823722011-06-11 01:09:30 +00004341 QualType T = PD->getType();
4342 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
4343 T = getMessageSendResultType(BaseType, Getter, false, false);
4344
4345 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCall68fc88ec2010-12-15 16:46:44 +00004346 VK_LValue,
4347 OK_ObjCProperty,
4348 MemberLoc,
John Wiegley01296292011-04-08 18:41:53 +00004349 BaseExpr.take()));
John McCall68fc88ec2010-12-15 16:46:44 +00004350 }
4351
4352 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
4353 // Check the use of this method.
4354 if (DiagnoseUseOfDecl(OMD, MemberLoc))
4355 return ExprError();
4356 Selector SetterSel =
4357 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4358 PP.getSelectorTable(), Member);
4359 ObjCMethodDecl *SMD = 0;
4360 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
4361 SetterSel, Context))
4362 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Douglas Gregor33823722011-06-11 01:09:30 +00004363 QualType PType = getMessageSendResultType(BaseType, OMD, false,
4364 false);
John McCall68fc88ec2010-12-15 16:46:44 +00004365
4366 ExprValueKind VK = VK_LValue;
4367 if (!getLangOptions().CPlusPlus &&
4368 IsCForbiddenLValueType(Context, PType))
4369 VK = VK_RValue;
4370 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4371
4372 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
4373 VK, OK,
John Wiegley01296292011-04-08 18:41:53 +00004374 MemberLoc, BaseExpr.take()));
John McCall68fc88ec2010-12-15 16:46:44 +00004375 }
4376 }
Fariborz Jahanianb03a4c22011-03-15 17:27:48 +00004377 // Use of id.member can only be for a property reference. Do not
4378 // use the 'id' redefinition in this case.
4379 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
John McCall68fc88ec2010-12-15 16:46:44 +00004380 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4381 ObjCImpDecl, HasTemplateArgs);
4382
4383 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
4384 << MemberName << BaseType);
4385 }
4386
4387 // 'Class', unqualified only.
4388 if (OT->isObjCClass()) {
4389 // Only works in a method declaration (??!).
4390 ObjCMethodDecl *MD = getCurMethodDecl();
4391 if (!MD) {
4392 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4393 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4394 ObjCImpDecl, HasTemplateArgs);
4395
4396 goto fail;
4397 }
4398
4399 // Also must look for a getter name which uses property syntax.
4400 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004401 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4402 ObjCMethodDecl *Getter;
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004403 if ((Getter = IFace->lookupClassMethod(Sel))) {
4404 // Check the use of this method.
4405 if (DiagnoseUseOfDecl(Getter, MemberLoc))
4406 return ExprError();
John McCall68fc88ec2010-12-15 16:46:44 +00004407 } else
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00004408 Getter = IFace->lookupPrivateMethod(Sel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004409 // If we found a getter then this may be a valid dot-reference, we
4410 // will look for the matching setter, in case it is needed.
4411 Selector SetterSel =
John McCall68fc88ec2010-12-15 16:46:44 +00004412 SelectorTable::constructSetterName(PP.getIdentifierTable(),
4413 PP.getSelectorTable(), Member);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004414 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
4415 if (!Setter) {
4416 // If this reference is in an @implementation, also check for 'private'
4417 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00004418 Setter = IFace->lookupPrivateMethod(SetterSel, false);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004419 }
4420 // Look through local category implementations associated with the class.
4421 if (!Setter)
4422 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004423
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004424 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
4425 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004426
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004427 if (Getter || Setter) {
4428 QualType PType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004429
John McCall4bc41ae2010-11-18 19:01:18 +00004430 ExprValueKind VK = VK_LValue;
4431 if (Getter) {
Douglas Gregor33823722011-06-11 01:09:30 +00004432 PType = getMessageSendResultType(QualType(OT, 0), Getter, true,
4433 false);
John McCall4bc41ae2010-11-18 19:01:18 +00004434 if (!getLangOptions().CPlusPlus &&
4435 IsCForbiddenLValueType(Context, PType))
4436 VK = VK_RValue;
4437 } else {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004438 // Get the expression type from Setter's incoming parameter.
4439 PType = (*(Setter->param_end() -1))->getType();
John McCall4bc41ae2010-11-18 19:01:18 +00004440 }
4441 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
4442
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004443 // FIXME: we must check that the setter has property type.
John McCallb7bd14f2010-12-02 01:19:52 +00004444 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
4445 PType, VK, OK,
John Wiegley01296292011-04-08 18:41:53 +00004446 MemberLoc, BaseExpr.take()));
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004447 }
John McCall68fc88ec2010-12-15 16:46:44 +00004448
4449 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
4450 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4451 ObjCImpDecl, HasTemplateArgs);
4452
Fariborz Jahaniane983d172009-09-22 16:48:37 +00004453 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
John McCall68fc88ec2010-12-15 16:46:44 +00004454 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004455 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004456
John McCall68fc88ec2010-12-15 16:46:44 +00004457 // Normal property access.
John Wiegley01296292011-04-08 18:41:53 +00004458 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), MemberName, MemberLoc,
John McCall68fc88ec2010-12-15 16:46:44 +00004459 SourceLocation(), QualType(), false);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004460 }
Alexis Huntc46382e2010-04-28 23:02:27 +00004461
Chris Lattnerb63a7452008-07-21 04:28:12 +00004462 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00004463 if (BaseType->isExtVectorType()) {
John McCall15317a22010-12-15 04:42:30 +00004464 // FIXME: this expr should store IsArrow.
Anders Carlssonf571c112009-08-26 18:25:21 +00004465 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
John Wiegley01296292011-04-08 18:41:53 +00004466 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
John McCall4bc41ae2010-11-18 19:01:18 +00004467 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
4468 Member, MemberLoc);
Chris Lattnerb63a7452008-07-21 04:28:12 +00004469 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004470 return ExprError();
John McCall4bc41ae2010-11-18 19:01:18 +00004471
John Wiegley01296292011-04-08 18:41:53 +00004472 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
John McCall4bc41ae2010-11-18 19:01:18 +00004473 *Member, MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00004474 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004475
John McCall68fc88ec2010-12-15 16:46:44 +00004476 // Adjust builtin-sel to the appropriate redefinition type if that's
4477 // not just a pointer to builtin-sel again.
4478 if (IsArrow &&
4479 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
4480 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
John Wiegley01296292011-04-08 18:41:53 +00004481 BaseExpr = ImpCastExprToType(BaseExpr.take(), Context.ObjCSelRedefinitionType,
4482 CK_BitCast);
John McCall68fc88ec2010-12-15 16:46:44 +00004483 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4484 ObjCImpDecl, HasTemplateArgs);
4485 }
4486
4487 // Failure cases.
4488 fail:
4489
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004490 // Recover from dot accesses to pointers, e.g.:
4491 // type *foo;
4492 // foo.bar
4493 // This is actually well-formed in two cases:
4494 // - 'type' is an Objective C type
4495 // - 'bar' is a pseudo-destructor name which happens to refer to
4496 // the appropriate pointer type
John McCall68fc88ec2010-12-15 16:46:44 +00004497 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004498 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
4499 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
John McCall68fc88ec2010-12-15 16:46:44 +00004500 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
John Wiegley01296292011-04-08 18:41:53 +00004501 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004502 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall68fc88ec2010-12-15 16:46:44 +00004503
4504 // Recurse as an -> access.
4505 IsArrow = true;
4506 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4507 ObjCImpDecl, HasTemplateArgs);
4508 }
John McCall68fc88ec2010-12-15 16:46:44 +00004509 }
4510
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004511 // If the user is trying to apply -> or . to a function name, it's probably
4512 // because they forgot parentheses to call that function.
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00004513 QualType ZeroArgCallTy;
4514 UnresolvedSet<4> Overloads;
4515 if (isExprCallable(*BaseExpr.get(), ZeroArgCallTy, Overloads)) {
4516 if (ZeroArgCallTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +00004517 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00004518 << (Overloads.size() > 1) << 0 << BaseExpr.get()->getSourceRange();
4519 UnresolvedSet<2> PlausibleOverloads;
4520 for (OverloadExpr::decls_iterator It = Overloads.begin(),
4521 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
4522 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
4523 QualType OverloadResultTy = OverloadDecl->getResultType();
4524 if ((!IsArrow && OverloadResultTy->isRecordType()) ||
4525 (IsArrow && OverloadResultTy->isPointerType() &&
4526 OverloadResultTy->getPointeeType()->isRecordType()))
4527 PlausibleOverloads.addDecl(It.getDecl());
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004528 }
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00004529 NoteOverloads(PlausibleOverloads, BaseExpr.get()->getExprLoc());
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004530 return ExprError();
4531 }
Matt Beaumont-Gay3c273912011-05-04 22:10:40 +00004532 if ((!IsArrow && ZeroArgCallTy->isRecordType()) ||
4533 (IsArrow && ZeroArgCallTy->isPointerType() &&
4534 ZeroArgCallTy->getPointeeType()->isRecordType())) {
4535 // At this point, we know BaseExpr looks like it's potentially callable
4536 // with 0 arguments, and that it returns something of a reasonable type,
4537 // so we can emit a fixit and carry on pretending that BaseExpr was
4538 // actually a CallExpr.
4539 SourceLocation ParenInsertionLoc =
4540 PP.getLocForEndOfToken(BaseExpr.get()->getLocEnd());
4541 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
4542 << (Overloads.size() > 1) << 1 << BaseExpr.get()->getSourceRange()
4543 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4544 // FIXME: Try this before emitting the fixit, and suppress diagnostics
4545 // while doing so.
4546 ExprResult NewBase =
4547 ActOnCallExpr(0, BaseExpr.take(), ParenInsertionLoc,
4548 MultiExprArg(*this, 0, 0),
4549 ParenInsertionLoc.getFileLocWithOffset(1));
4550 if (NewBase.isInvalid())
4551 return ExprError();
4552 BaseExpr = NewBase;
4553 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
4554 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4555 ObjCImpDecl, HasTemplateArgs);
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004556 }
Matt Beaumont-Gay06de2552011-02-22 23:52:53 +00004557 }
4558
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004559 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
John Wiegley01296292011-04-08 18:41:53 +00004560 << BaseType << BaseExpr.get()->getSourceRange();
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004561
Douglas Gregor0b08ba42009-03-27 06:00:30 +00004562 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00004563}
4564
John McCall10eae182009-11-30 22:42:35 +00004565/// The main callback when the parser finds something like
4566/// expression . [nested-name-specifier] identifier
4567/// expression -> [nested-name-specifier] identifier
4568/// where 'identifier' encompasses a fairly broad spectrum of
4569/// possibilities, including destructor and operator references.
4570///
4571/// \param OpKind either tok::arrow or tok::period
4572/// \param HasTrailingLParen whether the next token is '(', which
4573/// is used to diagnose mis-uses of special members that can
4574/// only be called
4575/// \param ObjCImpDecl the current ObjC @implementation decl;
4576/// this is an ugly hack around the fact that ObjC @implementations
4577/// aren't properly put in the context chain
John McCalldadc5752010-08-24 06:29:42 +00004578ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
John McCall15317a22010-12-15 04:42:30 +00004579 SourceLocation OpLoc,
4580 tok::TokenKind OpKind,
4581 CXXScopeSpec &SS,
4582 UnqualifiedId &Id,
4583 Decl *ObjCImpDecl,
4584 bool HasTrailingLParen) {
John McCall10eae182009-11-30 22:42:35 +00004585 if (SS.isSet() && SS.isInvalid())
4586 return ExprError();
4587
Francois Pichet64225792011-01-18 05:04:39 +00004588 // Warn about the explicit constructor calls Microsoft extension.
4589 if (getLangOptions().Microsoft &&
4590 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4591 Diag(Id.getSourceRange().getBegin(),
4592 diag::ext_ms_explicit_constructor_call);
4593
John McCall10eae182009-11-30 22:42:35 +00004594 TemplateArgumentListInfo TemplateArgsBuffer;
4595
4596 // Decompose the name into its component parts.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004597 DeclarationNameInfo NameInfo;
John McCall10eae182009-11-30 22:42:35 +00004598 const TemplateArgumentListInfo *TemplateArgs;
4599 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004600 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004601
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004602 DeclarationName Name = NameInfo.getName();
John McCall10eae182009-11-30 22:42:35 +00004603 bool IsArrow = (OpKind == tok::arrow);
4604
4605 NamedDecl *FirstQualifierInScope
4606 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4607 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4608
4609 // This is a postfix expression, so get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004610 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00004611 if (Result.isInvalid()) return ExprError();
4612 Base = Result.take();
John McCall10eae182009-11-30 22:42:35 +00004613
Douglas Gregor41f90302010-04-12 20:54:26 +00004614 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4615 isDependentScopeSpecifier(SS)) {
John McCallb268a282010-08-23 23:25:46 +00004616 Result = ActOnDependentMemberExpr(Base, Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00004617 IsArrow, OpLoc,
4618 SS, FirstQualifierInScope,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004619 NameInfo, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004620 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004621 LookupResult R(*this, NameInfo, LookupMemberName);
John Wiegley01296292011-04-08 18:41:53 +00004622 ExprResult BaseResult = Owned(Base);
4623 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
John McCalle9cccd82010-06-16 08:42:20 +00004624 SS, ObjCImpDecl, TemplateArgs != 0);
John Wiegley01296292011-04-08 18:41:53 +00004625 if (BaseResult.isInvalid())
4626 return ExprError();
4627 Base = BaseResult.take();
Alexis Huntc46382e2010-04-28 23:02:27 +00004628
John McCalle9cccd82010-06-16 08:42:20 +00004629 if (Result.isInvalid()) {
4630 Owned(Base);
4631 return ExprError();
4632 }
John McCall10eae182009-11-30 22:42:35 +00004633
John McCalle9cccd82010-06-16 08:42:20 +00004634 if (Result.get()) {
4635 // The only way a reference to a destructor can be used is to
4636 // immediately call it, which falls into this case. If the
4637 // next token is not a '(', produce a diagnostic and build the
4638 // call now.
4639 if (!HasTrailingLParen &&
4640 Id.getKind() == UnqualifiedId::IK_DestructorName)
John McCallb268a282010-08-23 23:25:46 +00004641 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
John McCall10eae182009-11-30 22:42:35 +00004642
John McCalle9cccd82010-06-16 08:42:20 +00004643 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00004644 }
4645
John McCallb268a282010-08-23 23:25:46 +00004646 Result = BuildMemberReferenceExpr(Base, Base->getType(),
John McCall38836f02010-01-15 08:34:02 +00004647 OpLoc, IsArrow, SS, FirstQualifierInScope,
4648 R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004649 }
4650
4651 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00004652}
4653
John McCalldadc5752010-08-24 06:29:42 +00004654ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00004655 FunctionDecl *FD,
4656 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00004657 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004658 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00004659 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00004660 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004661 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00004662 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004663 return ExprError();
4664 }
4665
4666 if (Param->hasUninstantiatedDefaultArg()) {
4667 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00004668
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004669 // Instantiate the expression.
4670 MultiLevelTemplateArgumentList ArgList
4671 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00004672
Nico Weber44887f62010-11-29 18:19:25 +00004673 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004674 = ArgList.getInnermost();
4675 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4676 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00004677
Nico Weber44887f62010-11-29 18:19:25 +00004678 ExprResult Result;
4679 {
4680 // C++ [dcl.fct.default]p5:
4681 // The names in the [default argument] expression are bound, and
4682 // the semantic constraints are checked, at the point where the
4683 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00004684 ContextRAII SavedContext(*this, FD);
Nico Weber44887f62010-11-29 18:19:25 +00004685 Result = SubstExpr(UninstExpr, ArgList);
4686 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004687 if (Result.isInvalid())
4688 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004689
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004690 // Check the expression as an initializer for the parameter.
4691 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004692 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004693 InitializationKind Kind
4694 = InitializationKind::CreateCopy(Param->getLocation(),
4695 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4696 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00004697
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004698 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4699 Result = InitSeq.Perform(*this, Entity, Kind,
4700 MultiExprArg(*this, &ResultE, 1));
4701 if (Result.isInvalid())
4702 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004703
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004704 // Build the default argument expression.
4705 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4706 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00004707 }
4708
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004709 // If the default expression creates temporaries, we need to
4710 // push them to the current stack of expression temporaries so they'll
4711 // be properly destroyed.
4712 // FIXME: We should really be rebuilding the default argument with new
4713 // bound temporaries; see the comment in PR5810.
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00004714 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4715 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4716 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4717 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4718 ExprTemporaries.push_back(Temporary);
4719 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004720
4721 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00004722 // Just mark all of the declarations in this potentially-evaluated expression
4723 // as being "referenced".
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00004724 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
Douglas Gregor033f6752009-12-23 23:03:06 +00004725 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00004726}
4727
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004728/// ConvertArgumentsForCall - Converts the arguments specified in
4729/// Args/NumArgs to the parameter types of the function FDecl with
4730/// function prototype Proto. Call is the call expression itself, and
4731/// Fn is the function expression. For a C++ member function, this
4732/// routine does not attempt to convert the object argument. Returns
4733/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004734bool
4735Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004736 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004737 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004738 Expr **Args, unsigned NumArgs,
4739 SourceLocation RParenLoc) {
John McCallbebede42011-02-26 05:39:39 +00004740 // Bail out early if calling a builtin with custom typechecking.
4741 // We don't need to do this in the
4742 if (FDecl)
4743 if (unsigned ID = FDecl->getBuiltinID())
4744 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4745 return false;
4746
Mike Stump4e1f26a2009-02-19 03:04:26 +00004747 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004748 // assignment, to the types of the corresponding parameter, ...
4749 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00004750 bool Invalid = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004751
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004752 // If too few arguments are available (and we don't have default
4753 // arguments for the remaining parameters), don't make the call.
4754 if (NumArgs < NumArgsInProto) {
4755 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4756 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004757 << Fn->getType()->isBlockPointerType()
Eric Christopherabf1e182010-04-16 04:48:22 +00004758 << NumArgsInProto << NumArgs << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00004759 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004760 }
4761
4762 // If too many are passed and not variadic, error on the extras and drop
4763 // them.
4764 if (NumArgs > NumArgsInProto) {
4765 if (!Proto->isVariadic()) {
4766 Diag(Args[NumArgsInProto]->getLocStart(),
4767 diag::err_typecheck_call_too_many_args)
Alexis Huntc46382e2010-04-28 23:02:27 +00004768 << Fn->getType()->isBlockPointerType()
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004769 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004770 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4771 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00004772
4773 // Emit the location of the prototype.
4774 if (FDecl && !FDecl->getBuiltinID())
4775 Diag(FDecl->getLocStart(),
4776 diag::note_typecheck_call_too_many_args)
4777 << FDecl;
4778
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004779 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00004780 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004781 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004782 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004783 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004784 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004785 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004786 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4787 if (Fn->getType()->isBlockPointerType())
4788 CallType = VariadicBlock; // Block
4789 else if (isa<MemberExpr>(Fn))
4790 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004791 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004792 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004793 if (Invalid)
4794 return true;
4795 unsigned TotalNumArgs = AllArgs.size();
4796 for (unsigned i = 0; i < TotalNumArgs; ++i)
4797 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004798
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004799 return false;
4800}
Mike Stump4e1f26a2009-02-19 03:04:26 +00004801
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004802bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4803 FunctionDecl *FDecl,
4804 const FunctionProtoType *Proto,
4805 unsigned FirstProtoArg,
4806 Expr **Args, unsigned NumArgs,
4807 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004808 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004809 unsigned NumArgsInProto = Proto->getNumArgs();
4810 unsigned NumArgsToCheck = NumArgs;
4811 bool Invalid = false;
4812 if (NumArgs != NumArgsInProto)
4813 // Use default arguments for missing arguments
4814 NumArgsToCheck = NumArgsInProto;
4815 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004816 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004817 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004818 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004819
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004820 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004821 if (ArgIx < NumArgs) {
4822 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004823
Eli Friedman3164fb12009-03-22 22:00:50 +00004824 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4825 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00004826 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004827 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00004828 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004829
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004830 // Pass the argument
4831 ParmVarDecl *Param = 0;
4832 if (FDecl && i < FDecl->getNumParams())
4833 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00004834
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004835 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004836 Param? InitializedEntity::InitializeParameter(Context, Param)
4837 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
John McCalldadc5752010-08-24 06:29:42 +00004838 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00004839 SourceLocation(),
4840 Owned(Arg));
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00004841 if (ArgE.isInvalid())
4842 return true;
4843
4844 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004845 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00004846 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004847
John McCalldadc5752010-08-24 06:29:42 +00004848 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004849 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00004850 if (ArgExpr.isInvalid())
4851 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004852
Anders Carlsson355933d2009-08-25 03:49:14 +00004853 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00004854 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00004855 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004856 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004857
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004858 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00004859 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00004860
4861 // Assume that extern "C" functions with variadic arguments that
4862 // return __unknown_anytype aren't *really* variadic.
4863 if (Proto->getResultType() == Context.UnknownAnyTy &&
4864 FDecl && FDecl->isExternC()) {
4865 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4866 ExprResult arg;
4867 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
4868 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
4869 else
4870 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4871 Invalid |= arg.isInvalid();
4872 AllArgs.push_back(arg.take());
4873 }
4874
4875 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4876 } else {
4877 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4878 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
4879 Invalid |= Arg.isInvalid();
4880 AllArgs.push_back(Arg.take());
4881 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004882 }
4883 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00004884 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004885}
4886
John McCall2979fe02011-04-12 00:42:48 +00004887/// Given a function expression of unknown-any type, try to rebuild it
4888/// to have a function type.
4889static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4890
Steve Naroff83895f72007-09-16 03:34:24 +00004891/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00004892/// This provides the location of the left/right parens and a list of comma
4893/// locations.
John McCalldadc5752010-08-24 06:29:42 +00004894ExprResult
John McCallb268a282010-08-23 23:25:46 +00004895Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Peter Collingbourne41f85462011-02-09 21:07:24 +00004896 MultiExprArg args, SourceLocation RParenLoc,
4897 Expr *ExecConfig) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004898 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00004899
4900 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004901 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00004902 if (Result.isInvalid()) return ExprError();
4903 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00004904
John McCallb268a282010-08-23 23:25:46 +00004905 Expr **Args = args.release();
Mike Stump11289f42009-09-09 15:08:12 +00004906
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004907 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00004908 // If this is a pseudo-destructor expression, build the call immediately.
4909 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4910 if (NumArgs > 0) {
4911 // Pseudo-destructor calls should not have any arguments.
4912 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00004913 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00004914 SourceRange(Args[0]->getLocStart(),
4915 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00004916
Douglas Gregorad8a3362009-09-04 17:36:40 +00004917 NumArgs = 0;
4918 }
Mike Stump11289f42009-09-09 15:08:12 +00004919
Douglas Gregorad8a3362009-09-04 17:36:40 +00004920 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00004921 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00004922 }
Mike Stump11289f42009-09-09 15:08:12 +00004923
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004924 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00004925 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00004926 // FIXME: Will need to cache the results of name lookup (including ADL) in
4927 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004928 bool Dependent = false;
4929 if (Fn->isTypeDependent())
4930 Dependent = true;
4931 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4932 Dependent = true;
4933
Peter Collingbourne41f85462011-02-09 21:07:24 +00004934 if (Dependent) {
4935 if (ExecConfig) {
4936 return Owned(new (Context) CUDAKernelCallExpr(
4937 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4938 Context.DependentTy, VK_RValue, RParenLoc));
4939 } else {
4940 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4941 Context.DependentTy, VK_RValue,
4942 RParenLoc));
4943 }
4944 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004945
4946 // Determine whether this is a call to an object (C++ [over.call.object]).
4947 if (Fn->getType()->isRecordType())
4948 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004949 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004950
John McCall2979fe02011-04-12 00:42:48 +00004951 if (Fn->getType() == Context.UnknownAnyTy) {
4952 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4953 if (result.isInvalid()) return ExprError();
4954 Fn = result.take();
4955 }
4956
John McCall0009fcc2011-04-26 20:42:42 +00004957 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00004958 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004959 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00004960 }
John McCall0009fcc2011-04-26 20:42:42 +00004961 }
John McCall10eae182009-11-30 22:42:35 +00004962
John McCall0009fcc2011-04-26 20:42:42 +00004963 // Check for overloaded calls. This can happen even in C due to extensions.
4964 if (Fn->getType() == Context.OverloadTy) {
4965 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4966
4967 // We aren't supposed to apply this logic if there's an '&' involved.
4968 if (!find.IsAddressOfOperand) {
4969 OverloadExpr *ovl = find.Expression;
4970 if (isa<UnresolvedLookupExpr>(ovl)) {
4971 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4972 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
4973 RParenLoc, ExecConfig);
4974 } else {
John McCall2d74de92009-12-01 22:10:20 +00004975 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004976 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00004977 }
4978 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004979 }
4980
Douglas Gregore254f902009-02-04 00:32:51 +00004981 // If we're directly calling a function, get the appropriate declaration.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004982
Eli Friedmane14b1992009-12-26 03:35:45 +00004983 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00004984
John McCall57500772009-12-16 12:17:52 +00004985 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00004986 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4987 if (UnOp->getOpcode() == UO_AddrOf)
4988 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4989
John McCall57500772009-12-16 12:17:52 +00004990 if (isa<DeclRefExpr>(NakedFn))
4991 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00004992 else if (isa<MemberExpr>(NakedFn))
4993 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00004994
Peter Collingbourne41f85462011-02-09 21:07:24 +00004995 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4996 ExecConfig);
4997}
4998
4999ExprResult
5000Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
5001 MultiExprArg execConfig, SourceLocation GGGLoc) {
5002 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
5003 if (!ConfigDecl)
5004 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
5005 << "cudaConfigureCall");
5006 QualType ConfigQTy = ConfigDecl->getType();
5007
5008 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
5009 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
5010
5011 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
John McCall2d74de92009-12-01 22:10:20 +00005012}
5013
Tanya Lattner55808c12011-06-04 00:47:47 +00005014/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5015///
5016/// __builtin_astype( value, dst type )
5017///
5018ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty,
5019 SourceLocation BuiltinLoc,
5020 SourceLocation RParenLoc) {
5021 ExprValueKind VK = VK_RValue;
5022 ExprObjectKind OK = OK_Ordinary;
5023 QualType DstTy = GetTypeFromParser(destty);
5024 QualType SrcTy = expr->getType();
5025 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5026 return ExprError(Diag(BuiltinLoc,
5027 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00005028 << DstTy
5029 << SrcTy
Tanya Lattner55808c12011-06-04 00:47:47 +00005030 << expr->getSourceRange());
5031 return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc, RParenLoc));
5032}
5033
John McCall57500772009-12-16 12:17:52 +00005034/// BuildResolvedCallExpr - Build a call to a resolved expression,
5035/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00005036/// unary-convert to an expression of function-pointer or
5037/// block-pointer type.
5038///
5039/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00005040ExprResult
John McCall2d74de92009-12-01 22:10:20 +00005041Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5042 SourceLocation LParenLoc,
5043 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00005044 SourceLocation RParenLoc,
5045 Expr *Config) {
John McCall2d74de92009-12-01 22:10:20 +00005046 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5047
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005048 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00005049 ExprResult Result = UsualUnaryConversions(Fn);
5050 if (Result.isInvalid())
5051 return ExprError();
5052 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005053
Chris Lattner08464942007-12-28 05:29:59 +00005054 // Make the call expr early, before semantic checks. This guarantees cleanup
5055 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00005056 CallExpr *TheCall;
5057 if (Config) {
5058 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5059 cast<CallExpr>(Config),
5060 Args, NumArgs,
5061 Context.BoolTy,
5062 VK_RValue,
5063 RParenLoc);
5064 } else {
5065 TheCall = new (Context) CallExpr(Context, Fn,
5066 Args, NumArgs,
5067 Context.BoolTy,
5068 VK_RValue,
5069 RParenLoc);
5070 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005071
John McCallbebede42011-02-26 05:39:39 +00005072 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5073
5074 // Bail out early if calling a builtin with custom typechecking.
5075 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5076 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
5077
John McCall31996342011-04-07 08:22:57 +00005078 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005079 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00005080 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005081 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5082 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00005083 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00005084 if (FuncT == 0)
5085 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5086 << Fn->getType() << Fn->getSourceRange());
5087 } else if (const BlockPointerType *BPT =
5088 Fn->getType()->getAs<BlockPointerType>()) {
5089 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5090 } else {
John McCall31996342011-04-07 08:22:57 +00005091 // Handle calls to expressions of unknown-any type.
5092 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00005093 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00005094 if (rewrite.isInvalid()) return ExprError();
5095 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00005096 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00005097 goto retry;
5098 }
5099
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005100 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5101 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00005102 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005103
Peter Collingbourne4b66c472011-02-23 01:53:29 +00005104 if (getLangOptions().CUDA) {
5105 if (Config) {
5106 // CUDA: Kernel calls must be to global functions
5107 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5108 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5109 << FDecl->getName() << Fn->getSourceRange());
5110
5111 // CUDA: Kernel function must have 'void' return type
5112 if (!FuncT->getResultType()->isVoidType())
5113 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5114 << Fn->getType() << Fn->getSourceRange());
5115 }
5116 }
5117
Eli Friedman3164fb12009-03-22 22:00:50 +00005118 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005119 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00005120 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00005121 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00005122 return ExprError();
5123
Chris Lattner08464942007-12-28 05:29:59 +00005124 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00005125 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00005126 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005127
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005128 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00005129 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005130 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005131 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00005132 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005133 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005134
Douglas Gregord8e97de2009-04-02 15:37:10 +00005135 if (FDecl) {
5136 // Check if we have too few/too many template arguments, based
5137 // on our knowledge of the function definition.
5138 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00005139 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00005140 const FunctionProtoType *Proto
5141 = Def->getType()->getAs<FunctionProtoType>();
5142 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00005143 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5144 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00005145 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00005146
5147 // If the function we're calling isn't a function prototype, but we have
5148 // a function prototype from a prior declaratiom, use that prototype.
5149 if (!FDecl->hasPrototype())
5150 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00005151 }
5152
Steve Naroff0b661582007-08-28 23:30:39 +00005153 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00005154 for (unsigned i = 0; i != NumArgs; i++) {
5155 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00005156
5157 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00005158 InitializedEntity Entity
5159 = InitializedEntity::InitializeParameter(Context,
5160 Proto->getArgType(i));
5161 ExprResult ArgE = PerformCopyInitialization(Entity,
5162 SourceLocation(),
5163 Owned(Arg));
5164 if (ArgE.isInvalid())
5165 return true;
5166
5167 Arg = ArgE.takeAs<Expr>();
5168
5169 } else {
John Wiegley01296292011-04-08 18:41:53 +00005170 ExprResult ArgE = DefaultArgumentPromotion(Arg);
5171
5172 if (ArgE.isInvalid())
5173 return true;
5174
5175 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00005176 }
5177
Douglas Gregor83025412010-10-26 05:45:40 +00005178 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
5179 Arg->getType(),
5180 PDiag(diag::err_call_incomplete_argument)
5181 << Arg->getSourceRange()))
5182 return ExprError();
5183
Chris Lattner08464942007-12-28 05:29:59 +00005184 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00005185 }
Steve Naroffae4143e2007-04-26 20:39:23 +00005186 }
Chris Lattner08464942007-12-28 05:29:59 +00005187
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005188 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5189 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005190 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5191 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005192
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00005193 // Check for sentinels
5194 if (NDecl)
5195 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00005196
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005197 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005198 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00005199 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005200 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00005201
John McCallbebede42011-02-26 05:39:39 +00005202 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00005203 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005204 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00005205 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005206 return ExprError();
5207 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005208
John McCallb268a282010-08-23 23:25:46 +00005209 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00005210}
5211
John McCalldadc5752010-08-24 06:29:42 +00005212ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005213Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005214 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00005215 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00005216 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00005217 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00005218
5219 TypeSourceInfo *TInfo;
5220 QualType literalType = GetTypeFromParser(Ty, &TInfo);
5221 if (!TInfo)
5222 TInfo = Context.getTrivialTypeSourceInfo(literalType);
5223
John McCallb268a282010-08-23 23:25:46 +00005224 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00005225}
5226
John McCalldadc5752010-08-24 06:29:42 +00005227ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00005228Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
John McCallb268a282010-08-23 23:25:46 +00005229 SourceLocation RParenLoc, Expr *literalExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00005230 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00005231
Eli Friedman37a186d2008-05-20 05:22:08 +00005232 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00005233 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5234 PDiag(diag::err_illegal_decl_array_incomplete_type)
5235 << SourceRange(LParenLoc,
5236 literalExpr->getSourceRange().getEnd())))
5237 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00005238 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005239 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5240 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00005241 } else if (!literalType->isDependentType() &&
5242 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00005243 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00005244 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00005245 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005246 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00005247
Douglas Gregor85dabae2009-12-16 01:38:02 +00005248 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00005249 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005250 InitializationKind Kind
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005251 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor85dabae2009-12-16 01:38:02 +00005252 /*IsCStyleCast=*/true);
Eli Friedmana553d4a2009-12-22 02:35:53 +00005253 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00005254 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00005255 MultiExprArg(*this, &literalExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00005256 &literalType);
5257 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005258 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00005259 literalExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00005260
Chris Lattner79413952008-12-04 23:50:19 +00005261 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00005262 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00005263 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00005264 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00005265 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00005266
John McCall7decc9e2010-11-18 06:31:45 +00005267 // In C, compound literals are l-values for some reason.
5268 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
5269
John McCall5d7aa7f2010-01-19 22:33:45 +00005270 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
John McCall7decc9e2010-11-18 06:31:45 +00005271 VK, literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00005272}
5273
John McCalldadc5752010-08-24 06:29:42 +00005274ExprResult
Sebastian Redlb5d49352009-01-19 22:31:54 +00005275Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00005276 SourceLocation RBraceLoc) {
5277 unsigned NumInit = initlist.size();
John McCallb268a282010-08-23 23:25:46 +00005278 Expr **InitList = initlist.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00005279
Steve Naroff30d242c2007-09-15 18:49:24 +00005280 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00005281 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005282
Ted Kremenekac034612010-04-13 23:39:13 +00005283 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
5284 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005285 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005286 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00005287}
5288
John McCalld7646252010-11-14 08:17:51 +00005289/// Prepares for a scalar cast, performing all the necessary stages
5290/// except the final cast and returning the kind required.
John Wiegley01296292011-04-08 18:41:53 +00005291static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00005292 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5293 // Also, callers should have filtered out the invalid cases with
5294 // pointers. Everything else should be possible.
5295
John Wiegley01296292011-04-08 18:41:53 +00005296 QualType SrcTy = Src.get()->getType();
John McCalld7646252010-11-14 08:17:51 +00005297 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00005298 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00005299
John McCall8cb679e2010-11-15 09:13:47 +00005300 switch (SrcTy->getScalarTypeKind()) {
5301 case Type::STK_MemberPointer:
5302 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00005303
John McCall8cb679e2010-11-15 09:13:47 +00005304 case Type::STK_Pointer:
5305 switch (DestTy->getScalarTypeKind()) {
5306 case Type::STK_Pointer:
5307 return DestTy->isObjCObjectPointerType() ?
John McCalld7646252010-11-14 08:17:51 +00005308 CK_AnyPointerToObjCPointerCast :
5309 CK_BitCast;
John McCall8cb679e2010-11-15 09:13:47 +00005310 case Type::STK_Bool:
5311 return CK_PointerToBoolean;
5312 case Type::STK_Integral:
5313 return CK_PointerToIntegral;
5314 case Type::STK_Floating:
5315 case Type::STK_FloatingComplex:
5316 case Type::STK_IntegralComplex:
5317 case Type::STK_MemberPointer:
5318 llvm_unreachable("illegal cast from pointer");
5319 }
5320 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005321
John McCall8cb679e2010-11-15 09:13:47 +00005322 case Type::STK_Bool: // casting from bool is like casting from an integer
5323 case Type::STK_Integral:
5324 switch (DestTy->getScalarTypeKind()) {
5325 case Type::STK_Pointer:
John Wiegley01296292011-04-08 18:41:53 +00005326 if (Src.get()->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00005327 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00005328 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005329 case Type::STK_Bool:
5330 return CK_IntegralToBoolean;
5331 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00005332 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00005333 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00005334 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00005335 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00005336 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5337 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00005338 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005339 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00005340 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5341 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00005342 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005343 case Type::STK_MemberPointer:
5344 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005345 }
5346 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005347
John McCall8cb679e2010-11-15 09:13:47 +00005348 case Type::STK_Floating:
5349 switch (DestTy->getScalarTypeKind()) {
5350 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00005351 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00005352 case Type::STK_Bool:
5353 return CK_FloatingToBoolean;
5354 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00005355 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00005356 case Type::STK_FloatingComplex:
John Wiegley01296292011-04-08 18:41:53 +00005357 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5358 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00005359 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005360 case Type::STK_IntegralComplex:
John Wiegley01296292011-04-08 18:41:53 +00005361 Src = S.ImpCastExprToType(Src.take(), DestTy->getAs<ComplexType>()->getElementType(),
5362 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00005363 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005364 case Type::STK_Pointer:
5365 llvm_unreachable("valid float->pointer cast?");
5366 case Type::STK_MemberPointer:
5367 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005368 }
5369 break;
5370
John McCall8cb679e2010-11-15 09:13:47 +00005371 case Type::STK_FloatingComplex:
5372 switch (DestTy->getScalarTypeKind()) {
5373 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005374 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00005375 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005376 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00005377 case Type::STK_Floating: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00005378 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005379 if (S.Context.hasSameType(ET, DestTy))
5380 return CK_FloatingComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00005381 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00005382 return CK_FloatingCast;
5383 }
John McCall8cb679e2010-11-15 09:13:47 +00005384 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005385 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005386 case Type::STK_Integral:
John Wiegley01296292011-04-08 18:41:53 +00005387 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5388 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00005389 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00005390 case Type::STK_Pointer:
5391 llvm_unreachable("valid complex float->pointer cast?");
5392 case Type::STK_MemberPointer:
5393 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005394 }
5395 break;
5396
John McCall8cb679e2010-11-15 09:13:47 +00005397 case Type::STK_IntegralComplex:
5398 switch (DestTy->getScalarTypeKind()) {
5399 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00005400 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00005401 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00005402 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00005403 case Type::STK_Integral: {
Abramo Bagnaraba854972011-01-04 09:50:03 +00005404 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005405 if (S.Context.hasSameType(ET, DestTy))
5406 return CK_IntegralComplexToReal;
John Wiegley01296292011-04-08 18:41:53 +00005407 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00005408 return CK_IntegralCast;
5409 }
John McCall8cb679e2010-11-15 09:13:47 +00005410 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00005411 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00005412 case Type::STK_Floating:
John Wiegley01296292011-04-08 18:41:53 +00005413 Src = S.ImpCastExprToType(Src.take(), SrcTy->getAs<ComplexType>()->getElementType(),
5414 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00005415 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00005416 case Type::STK_Pointer:
5417 llvm_unreachable("valid complex int->pointer cast?");
5418 case Type::STK_MemberPointer:
5419 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00005420 }
5421 break;
Anders Carlsson094c4592009-10-18 18:12:03 +00005422 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005423
John McCalld7646252010-11-14 08:17:51 +00005424 llvm_unreachable("Unhandled scalar cast");
5425 return CK_BitCast;
Anders Carlsson094c4592009-10-18 18:12:03 +00005426}
5427
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005428/// CheckCastTypes - Check type constraints for casting between types.
John Wiegley01296292011-04-08 18:41:53 +00005429ExprResult Sema::CheckCastTypes(SourceRange TyR, QualType castType,
5430 Expr *castExpr, CastKind& Kind, ExprValueKind &VK,
5431 CXXCastPath &BasePath, bool FunctionalStyle) {
John McCall31996342011-04-07 08:22:57 +00005432 if (castExpr->getType() == Context.UnknownAnyTy)
5433 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath);
5434
Sebastian Redl9f831db2009-07-25 15:41:38 +00005435 if (getLangOptions().CPlusPlus)
Douglas Gregor15417cf2010-11-03 00:35:38 +00005436 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
5437 castExpr->getLocEnd()),
John McCall7decc9e2010-11-18 06:31:45 +00005438 castType, VK, castExpr, Kind, BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00005439 FunctionalStyle);
Sebastian Redl9f831db2009-07-25 15:41:38 +00005440
John McCall3aef3d82011-04-10 19:13:55 +00005441 assert(!castExpr->getType()->isPlaceholderType());
5442
John McCall7decc9e2010-11-18 06:31:45 +00005443 // We only support r-value casts in C.
5444 VK = VK_RValue;
5445
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005446 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
5447 // type needs to be scalar.
5448 if (castType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00005449 // We don't necessarily do lvalue-to-rvalue conversions on this.
John Wiegley01296292011-04-08 18:41:53 +00005450 ExprResult castExprRes = IgnoredValueConversions(castExpr);
5451 if (castExprRes.isInvalid())
5452 return ExprError();
5453 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00005454
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005455 // Cast to void allows any expr type.
John McCalle3027922010-08-25 11:45:40 +00005456 Kind = CK_ToVoid;
John Wiegley01296292011-04-08 18:41:53 +00005457 return Owned(castExpr);
Anders Carlssonef918ac2009-10-16 02:35:04 +00005458 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005459
John Wiegley01296292011-04-08 18:41:53 +00005460 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr);
5461 if (castExprRes.isInvalid())
5462 return ExprError();
5463 castExpr = castExprRes.take();
John McCall34376a62010-12-04 03:47:34 +00005464
Eli Friedmane98194d2010-07-17 20:43:49 +00005465 if (RequireCompleteType(TyR.getBegin(), castType,
5466 diag::err_typecheck_cast_to_incomplete))
John Wiegley01296292011-04-08 18:41:53 +00005467 return ExprError();
Eli Friedmane98194d2010-07-17 20:43:49 +00005468
Anders Carlssonef918ac2009-10-16 02:35:04 +00005469 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005470 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005471 (castType->isStructureType() || castType->isUnionType())) {
5472 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00005473 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005474 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
5475 << castType << castExpr->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005476 Kind = CK_NoOp;
John Wiegley01296292011-04-08 18:41:53 +00005477 return Owned(castExpr);
Anders Carlsson525b76b2009-10-16 02:48:28 +00005478 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005479
Anders Carlsson525b76b2009-10-16 02:48:28 +00005480 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005481 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005482 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005483 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005484 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005485 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005486 if (Context.hasSameUnqualifiedType(Field->getType(),
Abramo Bagnara5d3e7242010-10-07 21:20:44 +00005487 castExpr->getType()) &&
5488 !Field->isUnnamedBitfield()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005489 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
5490 << castExpr->getSourceRange();
5491 break;
5492 }
5493 }
John Wiegley01296292011-04-08 18:41:53 +00005494 if (Field == FieldEnd) {
5495 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00005496 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005497 return ExprError();
5498 }
John McCalle3027922010-08-25 11:45:40 +00005499 Kind = CK_ToUnion;
John Wiegley01296292011-04-08 18:41:53 +00005500 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005501 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005502
Anders Carlsson525b76b2009-10-16 02:48:28 +00005503 // Reject any other conversions to non-scalar types.
John Wiegley01296292011-04-08 18:41:53 +00005504 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Anders Carlsson525b76b2009-10-16 02:48:28 +00005505 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005506 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005507 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005508
John McCalld7646252010-11-14 08:17:51 +00005509 // The type we're casting to is known to be a scalar or vector.
5510
5511 // Require the operand to be a scalar or vector.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005512 if (!castExpr->getType()->isScalarType() &&
Anders Carlsson525b76b2009-10-16 02:48:28 +00005513 !castExpr->getType()->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005514 Diag(castExpr->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00005515 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005516 << castExpr->getType() << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005517 return ExprError();
Anders Carlsson525b76b2009-10-16 02:48:28 +00005518 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005519
5520 if (castType->isExtVectorType())
Anders Carlsson43d70f82009-10-16 05:23:41 +00005521 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005522
Anton Yartsev28ccef72011-03-27 09:32:40 +00005523 if (castType->isVectorType()) {
5524 if (castType->getAs<VectorType>()->getVectorKind() ==
5525 VectorType::AltiVecVector &&
5526 (castExpr->getType()->isIntegerType() ||
5527 castExpr->getType()->isFloatingType())) {
5528 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00005529 return Owned(castExpr);
5530 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) {
5531 return ExprError();
Anton Yartsev28ccef72011-03-27 09:32:40 +00005532 } else
John Wiegley01296292011-04-08 18:41:53 +00005533 return Owned(castExpr);
Anton Yartsev28ccef72011-03-27 09:32:40 +00005534 }
John Wiegley01296292011-04-08 18:41:53 +00005535 if (castExpr->getType()->isVectorType()) {
5536 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind))
5537 return ExprError();
5538 else
5539 return Owned(castExpr);
5540 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00005541
John McCalld7646252010-11-14 08:17:51 +00005542 // The source and target types are both scalars, i.e.
5543 // - arithmetic types (fundamental, enum, and complex)
5544 // - all kinds of pointers
5545 // Note that member pointers were filtered out with C++, above.
5546
John Wiegley01296292011-04-08 18:41:53 +00005547 if (isa<ObjCSelectorExpr>(castExpr)) {
5548 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
5549 return ExprError();
5550 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005551
John McCalld7646252010-11-14 08:17:51 +00005552 // If either type is a pointer, the other type has to be either an
5553 // integer or a pointer.
Anders Carlsson525b76b2009-10-16 02:48:28 +00005554 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005555 QualType castExprType = castExpr->getType();
Douglas Gregor6972a622010-06-16 00:35:25 +00005556 if (!castExprType->isIntegralType(Context) &&
John Wiegley01296292011-04-08 18:41:53 +00005557 castExprType->isArithmeticType()) {
5558 Diag(castExpr->getLocStart(),
5559 diag::err_cast_pointer_from_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005560 << castExprType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005561 return ExprError();
5562 }
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005563 } else if (!castExpr->getType()->isArithmeticType()) {
John Wiegley01296292011-04-08 18:41:53 +00005564 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) {
5565 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int)
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00005566 << castType << castExpr->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00005567 return ExprError();
5568 }
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005569 }
Anders Carlsson094c4592009-10-18 18:12:03 +00005570
John Wiegley01296292011-04-08 18:41:53 +00005571 castExprRes = Owned(castExpr);
5572 Kind = PrepareScalarCast(*this, castExprRes, castType);
5573 if (castExprRes.isInvalid())
5574 return ExprError();
5575 castExpr = castExprRes.take();
John McCall2b5c1b22010-08-12 21:44:57 +00005576
John McCalld7646252010-11-14 08:17:51 +00005577 if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00005578 CheckCastAlign(castExpr, castType, TyR);
5579
John Wiegley01296292011-04-08 18:41:53 +00005580 return Owned(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00005581}
5582
Anders Carlsson525b76b2009-10-16 02:48:28 +00005583bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00005584 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00005585 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005586
Anders Carlssonde71adf2007-11-27 05:51:55 +00005587 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00005588 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00005589 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00005590 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00005591 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00005592 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005593 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005594 } else
5595 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00005596 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005597 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005598
John McCalle3027922010-08-25 11:45:40 +00005599 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00005600 return false;
5601}
5602
John Wiegley01296292011-04-08 18:41:53 +00005603ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5604 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00005605 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005606
Anders Carlsson43d70f82009-10-16 05:23:41 +00005607 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005608
Nate Begemanc8961a42009-06-27 22:05:55 +00005609 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5610 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00005611 if (SrcTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005612 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) {
5613 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00005614 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00005615 return ExprError();
5616 }
John McCalle3027922010-08-25 11:45:40 +00005617 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00005618 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00005619 }
5620
Nate Begemanbd956c42009-06-28 02:36:38 +00005621 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00005622 // conversion will take place first from scalar to elt type, and then
5623 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00005624 if (SrcTy->isPointerType())
5625 return Diag(R.getBegin(),
5626 diag::err_invalid_conversion_between_vector_and_scalar)
5627 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00005628
5629 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00005630 ExprResult CastExprRes = Owned(CastExpr);
5631 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy);
5632 if (CastExprRes.isInvalid())
5633 return ExprError();
5634 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005635
John McCalle3027922010-08-25 11:45:40 +00005636 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00005637 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00005638}
5639
John McCalldadc5752010-08-24 06:29:42 +00005640ExprResult
John McCallba7bf592010-08-24 05:47:05 +00005641Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00005642 SourceLocation RParenLoc, Expr *castExpr) {
5643 assert((Ty != 0) && (castExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00005644 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00005645
John McCall97513962010-01-15 18:39:57 +00005646 TypeSourceInfo *castTInfo;
5647 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5648 if (!castTInfo)
John McCalle15bbff2010-01-18 19:35:47 +00005649 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump11289f42009-09-09 15:08:12 +00005650
Nate Begeman5ec4b312009-08-10 23:49:36 +00005651 // If the Expr being casted is a ParenListExpr, handle it specially.
5652 if (isa<ParenListExpr>(castExpr))
John McCallb268a282010-08-23 23:25:46 +00005653 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
John McCalle15bbff2010-01-18 19:35:47 +00005654 castTInfo);
John McCallebe54742010-01-15 18:56:44 +00005655
John McCallb268a282010-08-23 23:25:46 +00005656 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
John McCallebe54742010-01-15 18:56:44 +00005657}
5658
John McCalldadc5752010-08-24 06:29:42 +00005659ExprResult
John McCallebe54742010-01-15 18:56:44 +00005660Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
John McCallb268a282010-08-23 23:25:46 +00005661 SourceLocation RParenLoc, Expr *castExpr) {
John McCall8cb679e2010-11-15 09:13:47 +00005662 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +00005663 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +00005664 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +00005665 ExprResult CastResult =
5666 CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
5667 Kind, VK, BasePath);
5668 if (CastResult.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005669 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00005670 castExpr = CastResult.take();
Anders Carlssone9766d52009-09-09 21:33:21 +00005671
John McCallcf142162010-08-07 06:22:56 +00005672 return Owned(CStyleCastExpr::Create(Context,
John Wiegley01296292011-04-08 18:41:53 +00005673 Ty->getType().getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +00005674 VK, Kind, castExpr, &BasePath, Ty,
John McCallcf142162010-08-07 06:22:56 +00005675 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00005676}
5677
Nate Begeman5ec4b312009-08-10 23:49:36 +00005678/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5679/// of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00005680ExprResult
John McCallb268a282010-08-23 23:25:46 +00005681Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005682 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5683 if (!E)
5684 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00005685
John McCalldadc5752010-08-24 06:29:42 +00005686 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00005687
Nate Begeman5ec4b312009-08-10 23:49:36 +00005688 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00005689 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5690 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00005691
John McCallb268a282010-08-23 23:25:46 +00005692 if (Result.isInvalid()) return ExprError();
5693
5694 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005695}
5696
John McCalldadc5752010-08-24 06:29:42 +00005697ExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00005698Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00005699 SourceLocation RParenLoc, Expr *Op,
John McCalle15bbff2010-01-18 19:35:47 +00005700 TypeSourceInfo *TInfo) {
John McCallb268a282010-08-23 23:25:46 +00005701 ParenListExpr *PE = cast<ParenListExpr>(Op);
John McCalle15bbff2010-01-18 19:35:47 +00005702 QualType Ty = TInfo->getType();
Anton Yartsev28ccef72011-03-27 09:32:40 +00005703 bool isVectorLiteral = false;
Mike Stump11289f42009-09-09 15:08:12 +00005704
Anton Yartsev28ccef72011-03-27 09:32:40 +00005705 // Check for an altivec or OpenCL literal,
John Thompson781ad172010-06-30 22:55:51 +00005706 // i.e. all the elements are integer constants.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005707 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5708 if (PE->getNumExprs() == 0) {
5709 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5710 return ExprError();
5711 }
John Thompson781ad172010-06-30 22:55:51 +00005712 if (PE->getNumExprs() == 1) {
5713 if (!PE->getExpr(0)->getType()->isVectorType())
Anton Yartsev28ccef72011-03-27 09:32:40 +00005714 isVectorLiteral = true;
John Thompson781ad172010-06-30 22:55:51 +00005715 }
5716 else
Anton Yartsev28ccef72011-03-27 09:32:40 +00005717 isVectorLiteral = true;
John Thompson781ad172010-06-30 22:55:51 +00005718 }
Nate Begeman5ec4b312009-08-10 23:49:36 +00005719
Anton Yartsev28ccef72011-03-27 09:32:40 +00005720 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
John Thompson781ad172010-06-30 22:55:51 +00005721 // then handle it as such.
Anton Yartsev28ccef72011-03-27 09:32:40 +00005722 if (isVectorLiteral) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005723 llvm::SmallVector<Expr *, 8> initExprs;
Anton Yartsev28ccef72011-03-27 09:32:40 +00005724 // '(...)' form of vector initialization in AltiVec: the number of
5725 // initializers must be one or must match the size of the vector.
5726 // If a single value is specified in the initializer then it will be
5727 // replicated to all the components of the vector
5728 if (Ty->getAs<VectorType>()->getVectorKind() ==
5729 VectorType::AltiVecVector) {
5730 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5731 // The number of initializers must be one or must match the size of the
5732 // vector. If a single value is specified in the initializer then it will
5733 // be replicated to all the components of the vector
5734 if (PE->getNumExprs() == 1) {
5735 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00005736 ExprResult Literal = Owned(PE->getExpr(0));
5737 Literal = ImpCastExprToType(Literal.take(), ElemTy,
5738 PrepareScalarCast(*this, Literal, ElemTy));
5739 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
Anton Yartsev28ccef72011-03-27 09:32:40 +00005740 }
5741 else if (PE->getNumExprs() < numElems) {
5742 Diag(PE->getExprLoc(),
5743 diag::err_incorrect_number_of_vector_initializers);
5744 return ExprError();
5745 }
5746 else
5747 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5748 initExprs.push_back(PE->getExpr(i));
5749 }
5750 else
5751 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5752 initExprs.push_back(PE->getExpr(i));
Nate Begeman5ec4b312009-08-10 23:49:36 +00005753
5754 // FIXME: This means that pretty-printing the final AST will produce curly
5755 // braces instead of the original commas.
Ted Kremenekac034612010-04-13 23:39:13 +00005756 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5757 &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00005758 initExprs.size(), RParenLoc);
5759 E->setType(Ty);
John McCallb268a282010-08-23 23:25:46 +00005760 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005761 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005762 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00005763 // sequence of BinOp comma operators.
John McCalldadc5752010-08-24 06:29:42 +00005764 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
John McCallb268a282010-08-23 23:25:46 +00005765 if (Result.isInvalid()) return ExprError();
5766 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
Nate Begeman5ec4b312009-08-10 23:49:36 +00005767 }
5768}
5769
John McCalldadc5752010-08-24 06:29:42 +00005770ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00005771 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005772 MultiExprArg Val,
John McCallba7bf592010-08-24 05:47:05 +00005773 ParsedType TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00005774 unsigned nexprs = Val.size();
5775 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00005776 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5777 Expr *expr;
5778 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5779 expr = new (Context) ParenExpr(L, R, exprs[0]);
5780 else
5781 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00005782 return Owned(expr);
5783}
5784
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005785/// \brief Emit a specialized diagnostic when one expression is a null pointer
5786/// constant and the other is not a pointer.
5787bool Sema::DiagnoseConditionalForNull(Expr *LHS, Expr *RHS,
5788 SourceLocation QuestionLoc) {
5789 Expr *NullExpr = LHS;
5790 Expr *NonPointerExpr = RHS;
5791 Expr::NullPointerConstantKind NullKind =
5792 NullExpr->isNullPointerConstant(Context,
5793 Expr::NPC_ValueDependentIsNotNull);
5794
5795 if (NullKind == Expr::NPCK_NotNull) {
5796 NullExpr = RHS;
5797 NonPointerExpr = LHS;
5798 NullKind =
5799 NullExpr->isNullPointerConstant(Context,
5800 Expr::NPC_ValueDependentIsNotNull);
5801 }
5802
5803 if (NullKind == Expr::NPCK_NotNull)
5804 return false;
5805
5806 if (NullKind == Expr::NPCK_ZeroInteger) {
5807 // In this case, check to make sure that we got here from a "NULL"
5808 // string in the source code.
5809 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00005810 SourceLocation loc = NullExpr->getExprLoc();
5811 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005812 return false;
5813 }
5814
5815 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
5816 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5817 << NonPointerExpr->getType() << DiagType
5818 << NonPointerExpr->getSourceRange();
5819 return true;
5820}
5821
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005822/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5823/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00005824/// C99 6.5.15
John Wiegley01296292011-04-08 18:41:53 +00005825QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005826 ExprValueKind &VK, ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00005827 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00005828
John McCall3aef3d82011-04-10 19:13:55 +00005829 ExprResult lhsResult = CheckPlaceholderExpr(LHS.get());
John McCall31996342011-04-07 08:22:57 +00005830 if (!lhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005831 LHS = move(lhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005832
John McCall3aef3d82011-04-10 19:13:55 +00005833 ExprResult rhsResult = CheckPlaceholderExpr(RHS.get());
John McCall31996342011-04-07 08:22:57 +00005834 if (!rhsResult.isUsable()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005835 RHS = move(rhsResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00005836
Sebastian Redl1a99f442009-04-16 17:51:27 +00005837 // C++ is sufficiently different to merit its own checker.
5838 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00005839 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00005840
5841 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005842 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005843
John Wiegley01296292011-04-08 18:41:53 +00005844 Cond = UsualUnaryConversions(Cond.take());
5845 if (Cond.isInvalid())
5846 return QualType();
5847 LHS = UsualUnaryConversions(LHS.take());
5848 if (LHS.isInvalid())
5849 return QualType();
5850 RHS = UsualUnaryConversions(RHS.take());
5851 if (RHS.isInvalid())
5852 return QualType();
5853
5854 QualType CondTy = Cond.get()->getType();
5855 QualType LHSTy = LHS.get()->getType();
5856 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00005857
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005858 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005859 if (!CondTy->isScalarType()) { // C99 6.5.15p2
Nate Begemanabb5a732010-09-20 22:41:17 +00005860 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5861 // Throw an error if its not either.
5862 if (getLangOptions().OpenCL) {
5863 if (!CondTy->isVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00005864 Diag(Cond.get()->getLocStart(),
Nate Begemanabb5a732010-09-20 22:41:17 +00005865 diag::err_typecheck_cond_expect_scalar_or_vector)
5866 << CondTy;
5867 return QualType();
5868 }
5869 }
5870 else {
John Wiegley01296292011-04-08 18:41:53 +00005871 Diag(Cond.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005872 << CondTy;
5873 return QualType();
5874 }
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005875 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005876
Chris Lattnere2949f42008-01-06 22:42:25 +00005877 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00005878 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5879 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00005880
Nate Begemanabb5a732010-09-20 22:41:17 +00005881 // OpenCL: If the condition is a vector, and both operands are scalar,
5882 // attempt to implicity convert them to the vector type to act like the
5883 // built in select.
5884 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5885 // Both operands should be of scalar type.
5886 if (!LHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00005887 Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005888 << CondTy;
5889 return QualType();
5890 }
5891 if (!RHSTy->isScalarType()) {
John Wiegley01296292011-04-08 18:41:53 +00005892 Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
Nate Begemanabb5a732010-09-20 22:41:17 +00005893 << CondTy;
5894 return QualType();
5895 }
5896 // Implicity convert these scalars to the type of the condition.
John Wiegley01296292011-04-08 18:41:53 +00005897 LHS = ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5898 RHS = ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
Nate Begemanabb5a732010-09-20 22:41:17 +00005899 }
5900
Chris Lattnere2949f42008-01-06 22:42:25 +00005901 // If both operands have arithmetic type, do the usual arithmetic conversions
5902 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00005903 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5904 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005905 if (LHS.isInvalid() || RHS.isInvalid())
5906 return QualType();
5907 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00005908 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005909
Chris Lattnere2949f42008-01-06 22:42:25 +00005910 // If both operands are the same structure or union type, the result is that
5911 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005912 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5913 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00005914 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005915 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00005916 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00005917 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00005918 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005919 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005920
Chris Lattnere2949f42008-01-06 22:42:25 +00005921 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00005922 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00005923 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5924 if (!LHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00005925 Diag(RHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5926 << RHS.get()->getSourceRange();
Chris Lattner432cff52009-02-18 04:28:32 +00005927 if (!RHSTy->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +00005928 Diag(LHS.get()->getLocStart(), diag::ext_typecheck_cond_one_void)
5929 << LHS.get()->getSourceRange();
5930 LHS = ImpCastExprToType(LHS.take(), Context.VoidTy, CK_ToVoid);
5931 RHS = ImpCastExprToType(RHS.take(), Context.VoidTy, CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00005932 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00005933 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00005934 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5935 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00005936 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00005937 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005938 // promote the null to a pointer.
John Wiegley01296292011-04-08 18:41:53 +00005939 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005940 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005941 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005942 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
John Wiegley01296292011-04-08 18:41:53 +00005943 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5944 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_NullToPointer);
Chris Lattner432cff52009-02-18 04:28:32 +00005945 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00005946 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005947
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005948 // All objective-c pointer type analysis is done here.
5949 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5950 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005951 if (LHS.isInvalid() || RHS.isInvalid())
5952 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005953 if (!compositeType.isNull())
5954 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005955
5956
Steve Naroff05efa972009-07-01 14:36:47 +00005957 // Handle block pointer types.
5958 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5959 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5960 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5961 QualType destType = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00005962 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5963 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00005964 return destType;
5965 }
5966 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005967 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00005968 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00005969 }
Steve Naroff05efa972009-07-01 14:36:47 +00005970 // We have 2 block pointer types.
5971 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5972 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00005973 return LHSTy;
5974 }
Steve Naroff05efa972009-07-01 14:36:47 +00005975 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005976 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5977 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005978
Steve Naroff05efa972009-07-01 14:36:47 +00005979 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5980 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00005981 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00005982 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump1b821b42009-05-07 03:14:14 +00005983 // In this situation, we assume void* type. No especially good
5984 // reason, but this is what gcc does, and we do have to pick
5985 // to get a consistent AST.
5986 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00005987 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5988 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00005989 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005990 }
Steve Naroff05efa972009-07-01 14:36:47 +00005991 // The block pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00005992 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
5993 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00005994 return LHSTy;
5995 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005996
Steve Naroff05efa972009-07-01 14:36:47 +00005997 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5998 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5999 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006000 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6001 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00006002
6003 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6004 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6005 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00006006 QualType destPointee
6007 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00006008 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00006009 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00006010 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00006011 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00006012 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00006013 return destType;
6014 }
6015 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006016 QualType destPointee
6017 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00006018 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00006019 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00006020 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00006021 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00006022 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00006023 return destType;
6024 }
6025
6026 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6027 // Two identical pointer types are always compatible.
6028 return LHSTy;
6029 }
6030 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
6031 rhptee.getUnqualifiedType())) {
6032 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
John Wiegley01296292011-04-08 18:41:53 +00006033 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff05efa972009-07-01 14:36:47 +00006034 // In this situation, we assume void* type. No especially good
6035 // reason, but this is what gcc does, and we do have to pick
6036 // to get a consistent AST.
6037 QualType incompatTy = Context.getPointerType(Context.VoidTy);
John Wiegley01296292011-04-08 18:41:53 +00006038 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6039 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00006040 return incompatTy;
6041 }
6042 // The pointer types are compatible.
6043 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
6044 // differently qualified versions of compatible types, the result type is
6045 // a pointer to an appropriately qualified version of the *composite*
6046 // type.
6047 // FIXME: Need to calculate the composite type.
6048 // FIXME: Need to add qualifiers
John Wiegley01296292011-04-08 18:41:53 +00006049 LHS = ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
6050 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00006051 return LHSTy;
6052 }
Mike Stump11289f42009-09-09 15:08:12 +00006053
John McCalle84af4e2010-11-13 01:35:44 +00006054 // GCC compatibility: soften pointer/integer mismatch. Note that
6055 // null pointers have been filtered out by this point.
Steve Naroff05efa972009-07-01 14:36:47 +00006056 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
6057 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00006058 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6059 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00006060 return RHSTy;
6061 }
6062 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
6063 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
John Wiegley01296292011-04-08 18:41:53 +00006064 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6065 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00006066 return LHSTy;
6067 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00006068
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006069 // Emit a better diagnostic if one of the expressions is a null pointer
6070 // constant and the other is not a pointer type. In this case, the user most
6071 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00006072 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00006073 return QualType();
6074
Chris Lattnere2949f42008-01-06 22:42:25 +00006075 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00006076 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00006077 << LHSTy << RHSTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00006078 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00006079}
6080
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006081/// FindCompositeObjCPointerType - Helper method to find composite type of
6082/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00006083QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006084 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00006085 QualType LHSTy = LHS.get()->getType();
6086 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006087
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006088 // Handle things like Class and struct objc_class*. Here we case the result
6089 // to the pseudo-builtin, because that will be implicitly cast back to the
6090 // redefinition type if an attempt is made to access its fields.
6091 if (LHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00006092 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006093 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006094 return LHSTy;
6095 }
6096 if (RHSTy->isObjCClassType() &&
John McCall717d9b02010-12-10 11:01:00 +00006097 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006098 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006099 return RHSTy;
6100 }
6101 // And the same for struct objc_object* / id
6102 if (LHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00006103 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006104 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006105 return LHSTy;
6106 }
6107 if (RHSTy->isObjCIdType() &&
John McCall717d9b02010-12-10 11:01:00 +00006108 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006109 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006110 return RHSTy;
6111 }
6112 // And the same for struct objc_selector* / SEL
6113 if (Context.isObjCSelType(LHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00006114 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006115 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006116 return LHSTy;
6117 }
6118 if (Context.isObjCSelType(RHSTy) &&
John McCall717d9b02010-12-10 11:01:00 +00006119 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
John Wiegley01296292011-04-08 18:41:53 +00006120 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006121 return RHSTy;
6122 }
6123 // Check constraints for Objective-C object pointers types.
6124 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006125
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006126 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6127 // Two identical object pointer types are always compatible.
6128 return LHSTy;
6129 }
6130 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
6131 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
6132 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006133
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006134 // If both operands are interfaces and either operand can be
6135 // assigned to the other, use that type as the composite
6136 // type. This allows
6137 // xxx ? (A*) a : (B*) b
6138 // where B is a subclass of A.
6139 //
6140 // Additionally, as for assignment, if either type is 'id'
6141 // allow silent coercion. Finally, if the types are
6142 // incompatible then make sure to use 'id' as the composite
6143 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006144
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006145 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6146 // It could return the composite type.
6147 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6148 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6149 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6150 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6151 } else if ((LHSTy->isObjCQualifiedIdType() ||
6152 RHSTy->isObjCQualifiedIdType()) &&
6153 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6154 // Need to handle "id<xx>" explicitly.
6155 // GCC allows qualified id and any Objective-C type to devolve to
6156 // id. Currently localizing to here until clear this should be
6157 // part of ObjCQualifiedIdTypesAreCompatible.
6158 compositeType = Context.getObjCIdType();
6159 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6160 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006161 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006162 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
6163 ;
6164 else {
6165 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6166 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00006167 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006168 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00006169 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
6170 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006171 return incompatTy;
6172 }
6173 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00006174 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
6175 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006176 return compositeType;
6177 }
6178 // Check Objective-C object pointer types and 'void *'
6179 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6180 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6181 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6182 QualType destPointee
6183 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6184 QualType destType = Context.getPointerType(destPointee);
6185 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00006186 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006187 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00006188 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006189 return destType;
6190 }
6191 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6192 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6193 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6194 QualType destPointee
6195 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6196 QualType destType = Context.getPointerType(destPointee);
6197 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00006198 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006199 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00006200 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00006201 return destType;
6202 }
6203 return QualType();
6204}
6205
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006206/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6207/// ParenRange in parentheses.
6208static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6209 const PartialDiagnostic &PD,
6210 const PartialDiagnostic &FirstNote,
6211 SourceRange FirstParenRange,
6212 const PartialDiagnostic &SecondNote,
6213 SourceRange SecondParenRange) {
6214 Self.Diag(Loc, PD);
6215
6216 if (!FirstNote.getDiagID())
6217 return;
6218
6219 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
6220 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6221 // We can't display the parentheses, so just return.
6222 return;
6223 }
6224
6225 Self.Diag(Loc, FirstNote)
6226 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
6227 << FixItHint::CreateInsertion(EndLoc, ")");
6228
6229 if (!SecondNote.getDiagID())
6230 return;
6231
6232 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
6233 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6234 // We can't display the parentheses, so just dig the
6235 // warning/error and return.
6236 Self.Diag(Loc, SecondNote);
6237 return;
6238 }
6239
6240 Self.Diag(Loc, SecondNote)
6241 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
6242 << FixItHint::CreateInsertion(EndLoc, ")");
6243}
6244
6245static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6246 return Opc >= BO_Mul && Opc <= BO_Shr;
6247}
6248
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006249/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6250/// expression, either using a built-in or overloaded operator,
6251/// and sets *OpCode to the opcode and *RHS to the right-hand side expression.
6252static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6253 Expr **RHS) {
6254 E = E->IgnoreParenImpCasts();
6255 E = E->IgnoreConversionOperator();
6256 E = E->IgnoreParenImpCasts();
6257
6258 // Built-in binary operator.
6259 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6260 if (IsArithmeticOp(OP->getOpcode())) {
6261 *Opcode = OP->getOpcode();
6262 *RHS = OP->getRHS();
6263 return true;
6264 }
6265 }
6266
6267 // Overloaded operator.
6268 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6269 if (Call->getNumArgs() != 2)
6270 return false;
6271
6272 // Make sure this is really a binary operator that is safe to pass into
6273 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6274 OverloadedOperatorKind OO = Call->getOperator();
6275 if (OO < OO_Plus || OO > OO_Arrow)
6276 return false;
6277
6278 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6279 if (IsArithmeticOp(OpKind)) {
6280 *Opcode = OpKind;
6281 *RHS = Call->getArg(1);
6282 return true;
6283 }
6284 }
6285
6286 return false;
6287}
6288
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006289static bool IsLogicOp(BinaryOperatorKind Opc) {
6290 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
6291}
6292
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006293/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6294/// or is a logical expression such as (x==y) which has int type, but is
6295/// commonly interpreted as boolean.
6296static bool ExprLooksBoolean(Expr *E) {
6297 E = E->IgnoreParenImpCasts();
6298
6299 if (E->getType()->isBooleanType())
6300 return true;
6301 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6302 return IsLogicOp(OP->getOpcode());
6303 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6304 return OP->getOpcode() == UO_LNot;
6305
6306 return false;
6307}
6308
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006309/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6310/// and binary operator are mixed in a way that suggests the programmer assumed
6311/// the conditional operator has higher precedence, for example:
6312/// "int x = a + someBinaryCondition ? 1 : 2".
6313static void DiagnoseConditionalPrecedence(Sema &Self,
6314 SourceLocation OpLoc,
6315 Expr *cond,
6316 Expr *lhs,
6317 Expr *rhs) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006318 BinaryOperatorKind CondOpcode;
6319 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006320
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006321 if (!IsArithmeticBinaryExpr(cond, &CondOpcode, &CondRHS))
6322 return;
6323 if (!ExprLooksBoolean(CondRHS))
6324 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006325
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006326 // The condition is an arithmetic binary expression, with a right-
6327 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006328
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006329 PartialDiagnostic Warn = Self.PDiag(diag::warn_precedence_conditional)
6330 << cond->getSourceRange()
6331 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006332
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006333 PartialDiagnostic FirstNote =
6334 Self.PDiag(diag::note_precedence_conditional_silence)
6335 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006336
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006337 SourceRange FirstParenRange(cond->getLocStart(),
6338 cond->getLocEnd());
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006339
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006340 PartialDiagnostic SecondNote =
6341 Self.PDiag(diag::note_precedence_conditional_first);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006342
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006343 SourceRange SecondParenRange(CondRHS->getLocStart(),
6344 rhs->getLocEnd());
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006345
Hans Wennborgde2e67e2011-06-09 17:06:51 +00006346 SuggestParentheses(Self, OpLoc, Warn, FirstNote, FirstParenRange,
6347 SecondNote, SecondParenRange);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006348}
6349
Steve Naroff83895f72007-09-16 03:34:24 +00006350/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00006351/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00006352ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00006353 SourceLocation ColonLoc,
6354 Expr *CondExpr, Expr *LHSExpr,
6355 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00006356 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6357 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00006358 OpaqueValueExpr *opaqueValue = 0;
6359 Expr *commonExpr = 0;
6360 if (LHSExpr == 0) {
6361 commonExpr = CondExpr;
6362
6363 // We usually want to apply unary conversions *before* saving, except
6364 // in the special case of a C++ l-value conditional.
6365 if (!(getLangOptions().CPlusPlus
6366 && !commonExpr->isTypeDependent()
6367 && commonExpr->getValueKind() == RHSExpr->getValueKind()
6368 && commonExpr->isGLValue()
6369 && commonExpr->isOrdinaryOrBitFieldObject()
6370 && RHSExpr->isOrdinaryOrBitFieldObject()
6371 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00006372 ExprResult commonRes = UsualUnaryConversions(commonExpr);
6373 if (commonRes.isInvalid())
6374 return ExprError();
6375 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00006376 }
6377
6378 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6379 commonExpr->getType(),
6380 commonExpr->getValueKind(),
6381 commonExpr->getObjectKind());
6382 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00006383 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00006384
John McCall7decc9e2010-11-18 06:31:45 +00006385 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00006386 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00006387 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
6388 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00006389 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00006390 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6391 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00006392 return ExprError();
6393
Hans Wennborgcf9bac42011-06-03 18:00:36 +00006394 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6395 RHS.get());
6396
John McCallc07a0c72011-02-17 10:25:35 +00006397 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00006398 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
6399 LHS.take(), ColonLoc,
6400 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00006401
6402 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00006403 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
6404 RHS.take(), QuestionLoc, ColonLoc, result, VK, OK));
Chris Lattnere168f762006-11-10 05:29:30 +00006405}
6406
John McCallaba90822011-01-31 23:13:11 +00006407// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00006408// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00006409// routine is it effectively iqnores the qualifiers on the top level pointee.
6410// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6411// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00006412static Sema::AssignConvertType
6413checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6414 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6415 assert(rhsType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006416
Steve Naroff1f4d7272007-05-11 04:00:31 +00006417 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00006418 const Type *lhptee, *rhptee;
6419 Qualifiers lhq, rhq;
6420 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
6421 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006422
John McCallaba90822011-01-31 23:13:11 +00006423 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006424
6425 // C99 6.5.16.1p1: This following citation is common to constraints
6426 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6427 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00006428 Qualifiers lq;
6429
6430 if (!lhq.compatiblyIncludes(rhq)) {
6431 // Treat address-space mismatches as fatal. TODO: address subspaces
6432 if (lhq.getAddressSpace() != rhq.getAddressSpace())
6433 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6434
John McCall78535952011-03-26 02:56:45 +00006435 // It's okay to add or remove GC qualifiers when converting to
6436 // and from void*.
6437 else if (lhq.withoutObjCGCAttr().compatiblyIncludes(rhq.withoutObjCGCAttr())
6438 && (lhptee->isVoidType() || rhptee->isVoidType()))
6439 ; // keep old
6440
John McCall4fff8f62011-02-01 00:10:29 +00006441 // For GCC compatibility, other qualifier mismatches are treated
6442 // as still compatible in C.
6443 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6444 }
Steve Naroff3f597292007-05-11 22:18:03 +00006445
Mike Stump4e1f26a2009-02-19 03:04:26 +00006446 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6447 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00006448 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00006449 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006450 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00006451 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006452
Chris Lattner0a788432008-01-03 22:56:36 +00006453 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006454 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00006455 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00006456 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006457
Chris Lattner0a788432008-01-03 22:56:36 +00006458 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006459 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00006460 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00006461
6462 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00006463 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00006464 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00006465 }
John McCall4fff8f62011-02-01 00:10:29 +00006466
Mike Stump4e1f26a2009-02-19 03:04:26 +00006467 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00006468 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00006469 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6470 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00006471 // Check if the pointee types are compatible ignoring the sign.
6472 // We explicitly check for char so that we catch "char" vs
6473 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00006474 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00006475 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006476 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00006477 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006478
Chris Lattnerec3a1562009-10-17 20:33:28 +00006479 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00006480 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006481 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00006482 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00006483
John McCall4fff8f62011-02-01 00:10:29 +00006484 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00006485 // Types are compatible ignoring the sign. Qualifier incompatibility
6486 // takes priority over sign incompatibility because the sign
6487 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00006488 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00006489 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00006490
John McCallaba90822011-01-31 23:13:11 +00006491 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00006492 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006493
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006494 // If we are a multi-level pointer, it's possible that our issue is simply
6495 // one of qualification - e.g. char ** -> const char ** is not allowed. If
6496 // the eventual target type is the same and the pointers have the same
6497 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00006498 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006499 do {
John McCall4fff8f62011-02-01 00:10:29 +00006500 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6501 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00006502 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006503
John McCall4fff8f62011-02-01 00:10:29 +00006504 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00006505 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006506 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006507
Eli Friedman80160bd2009-03-22 23:59:44 +00006508 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00006509 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00006510 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00006511 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00006512}
6513
John McCallaba90822011-01-31 23:13:11 +00006514/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00006515/// block pointer types are compatible or whether a block and normal pointer
6516/// are compatible. It is more restrict than comparing two function pointer
6517// types.
John McCallaba90822011-01-31 23:13:11 +00006518static Sema::AssignConvertType
6519checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
6520 QualType rhsType) {
6521 assert(lhsType.isCanonical() && "LHS not canonicalized!");
6522 assert(rhsType.isCanonical() && "RHS not canonicalized!");
6523
Steve Naroff081c7422008-09-04 15:10:53 +00006524 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006525
Steve Naroff081c7422008-09-04 15:10:53 +00006526 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCallaba90822011-01-31 23:13:11 +00006527 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
6528 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006529
John McCallaba90822011-01-31 23:13:11 +00006530 // In C++, the types have to match exactly.
6531 if (S.getLangOptions().CPlusPlus)
6532 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006533
John McCallaba90822011-01-31 23:13:11 +00006534 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006535
Steve Naroff081c7422008-09-04 15:10:53 +00006536 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00006537 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6538 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006539
John McCallaba90822011-01-31 23:13:11 +00006540 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
6541 return Sema::IncompatibleBlockPointer;
6542
Steve Naroff081c7422008-09-04 15:10:53 +00006543 return ConvTy;
6544}
6545
John McCallaba90822011-01-31 23:13:11 +00006546/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006547/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00006548static Sema::AssignConvertType
6549checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
6550 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
6551 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
6552
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006553 if (lhsType->isObjCBuiltinType()) {
6554 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00006555 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
6556 !rhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00006557 return Sema::IncompatiblePointer;
6558 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006559 }
6560 if (rhsType->isObjCBuiltinType()) {
6561 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian9b37b1d2010-03-24 21:00:27 +00006562 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
6563 !lhsType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00006564 return Sema::IncompatiblePointer;
6565 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00006566 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006567 QualType lhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006568 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006569 QualType rhptee =
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006570 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006571
John McCallaba90822011-01-31 23:13:11 +00006572 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
6573 return Sema::CompatiblePointerDiscardsQualifiers;
6574
6575 if (S.Context.typesAreCompatible(lhsType, rhsType))
6576 return Sema::Compatible;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006577 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00006578 return Sema::IncompatibleObjCQualifiedId;
6579 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00006580}
6581
John McCall29600e12010-11-16 02:32:08 +00006582Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00006583Sema::CheckAssignmentConstraints(SourceLocation Loc,
6584 QualType lhsType, QualType rhsType) {
John McCall29600e12010-11-16 02:32:08 +00006585 // Fake up an opaque expression. We don't actually care about what
6586 // cast operations are required, so if CheckAssignmentConstraints
6587 // adds casts to this they'll be wasted, but fortunately that doesn't
6588 // usually happen on valid code.
Douglas Gregorc03a1082011-01-28 02:26:04 +00006589 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00006590 ExprResult rhsPtr = &rhs;
John McCall29600e12010-11-16 02:32:08 +00006591 CastKind K = CK_Invalid;
6592
6593 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
6594}
6595
Mike Stump4e1f26a2009-02-19 03:04:26 +00006596/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6597/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00006598/// pointers. Here are some objectionable examples that GCC considers warnings:
6599///
6600/// int a, *pint;
6601/// short *pshort;
6602/// struct foo *pfoo;
6603///
6604/// pint = pshort; // warning: assignment from incompatible pointer type
6605/// a = pint; // warning: assignment makes integer from pointer without a cast
6606/// pint = a; // warning: assignment makes pointer from integer without a cast
6607/// pint = pfoo; // warning: assignment from incompatible pointer type
6608///
6609/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00006610/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00006611///
John McCall8cb679e2010-11-15 09:13:47 +00006612/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00006613Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006614Sema::CheckAssignmentConstraints(QualType lhsType, ExprResult &rhs,
John McCall8cb679e2010-11-15 09:13:47 +00006615 CastKind &Kind) {
John Wiegley01296292011-04-08 18:41:53 +00006616 QualType rhsType = rhs.get()->getType();
John McCall29600e12010-11-16 02:32:08 +00006617
Chris Lattnera52c2f22008-01-04 23:18:45 +00006618 // Get canonical types. We're not formatting these types, just comparing
6619 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00006620 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
6621 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00006622
John McCalle5255932011-01-31 22:28:28 +00006623 // Common case: no conversion required.
John McCall8cb679e2010-11-15 09:13:47 +00006624 if (lhsType == rhsType) {
6625 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00006626 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00006627 }
6628
Douglas Gregor6b754842008-10-28 00:22:11 +00006629 // If the left-hand side is a reference type, then we are in a
6630 // (rare!) case where we've allowed the use of references in C,
6631 // e.g., as a parameter type in a built-in function. In this case,
6632 // just make sure that the type referenced is compatible with the
6633 // right-hand side type. The caller is responsible for adjusting
6634 // lhsType so that the resulting expression does not have reference
6635 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006636 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
John McCall8cb679e2010-11-15 09:13:47 +00006637 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
6638 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00006639 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006640 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00006641 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00006642 }
John McCalle5255932011-01-31 22:28:28 +00006643
Nate Begemanbd956c42009-06-28 02:36:38 +00006644 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6645 // to the same ExtVector type.
6646 if (lhsType->isExtVectorType()) {
6647 if (rhsType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00006648 return Incompatible;
6649 if (rhsType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00006650 // CK_VectorSplat does T -> vector T, so first cast to the
6651 // element type.
6652 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
6653 if (elType != rhsType) {
6654 Kind = PrepareScalarCast(*this, rhs, elType);
John Wiegley01296292011-04-08 18:41:53 +00006655 rhs = ImpCastExprToType(rhs.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00006656 }
6657 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00006658 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006659 }
Nate Begemanbd956c42009-06-28 02:36:38 +00006660 }
Mike Stump11289f42009-09-09 15:08:12 +00006661
John McCalle5255932011-01-31 22:28:28 +00006662 // Conversions to or from vector type.
Nate Begeman191a6b12008-07-14 18:02:46 +00006663 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006664 if (lhsType->isVectorType() && rhsType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00006665 // Allow assignments of an AltiVec vector type to an equivalent GCC
6666 // vector type and vice versa
6667 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6668 Kind = CK_BitCast;
6669 return Compatible;
6670 }
6671
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006672 // If we are allowing lax vector conversions, and LHS and RHS are both
6673 // vectors, the total size only needs to be the same. This is a bitcast;
6674 // no bits are changed but the result type is different.
6675 if (getLangOptions().LaxVectorConversions &&
John McCall8cb679e2010-11-15 09:13:47 +00006676 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
John McCall3065d042010-11-15 10:08:00 +00006677 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006678 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00006679 }
Chris Lattner881a2122008-01-04 23:32:24 +00006680 }
6681 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006682 }
Eli Friedman3360d892008-05-30 18:07:22 +00006683
John McCalle5255932011-01-31 22:28:28 +00006684 // Arithmetic conversions.
Douglas Gregorbea453a2010-05-23 21:53:47 +00006685 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
John McCall8cb679e2010-11-15 09:13:47 +00006686 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
John McCall29600e12010-11-16 02:32:08 +00006687 Kind = PrepareScalarCast(*this, rhs, lhsType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00006688 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006689 }
Eli Friedman3360d892008-05-30 18:07:22 +00006690
John McCalle5255932011-01-31 22:28:28 +00006691 // Conversions to normal pointers.
6692 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
6693 // U* -> T*
John McCall8cb679e2010-11-15 09:13:47 +00006694 if (isa<PointerType>(rhsType)) {
6695 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006696 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
John McCall8cb679e2010-11-15 09:13:47 +00006697 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006698
John McCalle5255932011-01-31 22:28:28 +00006699 // int -> T*
6700 if (rhsType->isIntegerType()) {
6701 Kind = CK_IntegralToPointer; // FIXME: null?
6702 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006703 }
John McCalle5255932011-01-31 22:28:28 +00006704
6705 // C pointers are not compatible with ObjC object pointers,
6706 // with two exceptions:
6707 if (isa<ObjCObjectPointerType>(rhsType)) {
6708 // - conversions to void*
6709 if (lhsPointer->getPointeeType()->isVoidType()) {
6710 Kind = CK_AnyPointerToObjCPointerCast;
6711 return Compatible;
6712 }
6713
6714 // - conversions from 'Class' to the redefinition type
6715 if (rhsType->isObjCClassType() &&
6716 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006717 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006718 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006719 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006720
John McCalle5255932011-01-31 22:28:28 +00006721 Kind = CK_BitCast;
6722 return IncompatiblePointer;
6723 }
6724
6725 // U^ -> void*
6726 if (rhsType->getAs<BlockPointerType>()) {
6727 if (lhsPointer->getPointeeType()->isVoidType()) {
6728 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006729 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006730 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006731 }
John McCalle5255932011-01-31 22:28:28 +00006732
Steve Naroff081c7422008-09-04 15:10:53 +00006733 return Incompatible;
6734 }
6735
John McCalle5255932011-01-31 22:28:28 +00006736 // Conversions to block pointers.
Steve Naroff081c7422008-09-04 15:10:53 +00006737 if (isa<BlockPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006738 // U^ -> T^
6739 if (rhsType->isBlockPointerType()) {
6740 Kind = CK_AnyPointerToBlockPointerCast;
John McCallaba90822011-01-31 23:13:11 +00006741 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006742 }
6743
6744 // int or null -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006745 if (rhsType->isIntegerType()) {
6746 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00006747 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006748 }
6749
John McCalle5255932011-01-31 22:28:28 +00006750 // id -> T^
6751 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
6752 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00006753 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006754 }
Steve Naroff32d072c2008-09-29 18:10:17 +00006755
John McCalle5255932011-01-31 22:28:28 +00006756 // void* -> T^
John McCall8cb679e2010-11-15 09:13:47 +00006757 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00006758 if (RHSPT->getPointeeType()->isVoidType()) {
6759 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00006760 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006761 }
John McCall8cb679e2010-11-15 09:13:47 +00006762
Chris Lattnera52c2f22008-01-04 23:18:45 +00006763 return Incompatible;
6764 }
6765
John McCalle5255932011-01-31 22:28:28 +00006766 // Conversions to Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006767 if (isa<ObjCObjectPointerType>(lhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006768 // A* -> B*
6769 if (rhsType->isObjCObjectPointerType()) {
6770 Kind = CK_BitCast;
John McCallaba90822011-01-31 23:13:11 +00006771 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
John McCalle5255932011-01-31 22:28:28 +00006772 }
6773
6774 // int or null -> A*
John McCall8cb679e2010-11-15 09:13:47 +00006775 if (rhsType->isIntegerType()) {
6776 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00006777 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00006778 }
6779
John McCalle5255932011-01-31 22:28:28 +00006780 // In general, C pointers are not compatible with ObjC object pointers,
6781 // with two exceptions:
Steve Naroff7cae42b2009-07-10 23:34:53 +00006782 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006783 // - conversions from 'void*'
6784 if (rhsType->isVoidPointerType()) {
6785 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006786 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006787 }
6788
6789 // - conversions to 'Class' from its redefinition type
6790 if (lhsType->isObjCClassType() &&
6791 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6792 Kind = CK_BitCast;
6793 return Compatible;
6794 }
6795
6796 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroffaccc4882009-07-20 17:56:53 +00006797 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006798 }
John McCalle5255932011-01-31 22:28:28 +00006799
6800 // T^ -> A*
6801 if (rhsType->isBlockPointerType()) {
6802 Kind = CK_AnyPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006803 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00006804 }
6805
Steve Naroff7cae42b2009-07-10 23:34:53 +00006806 return Incompatible;
6807 }
John McCalle5255932011-01-31 22:28:28 +00006808
6809 // Conversions from pointers that are not covered by the above.
Chris Lattnerec646832008-04-07 06:49:41 +00006810 if (isa<PointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006811 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006812 if (lhsType == Context.BoolTy) {
6813 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00006814 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006815 }
Eli Friedman3360d892008-05-30 18:07:22 +00006816
John McCalle5255932011-01-31 22:28:28 +00006817 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006818 if (lhsType->isIntegerType()) {
6819 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006820 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006821 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006822
Chris Lattnera52c2f22008-01-04 23:18:45 +00006823 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00006824 }
John McCalle5255932011-01-31 22:28:28 +00006825
6826 // Conversions from Objective-C pointers that are not covered by the above.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006827 if (isa<ObjCObjectPointerType>(rhsType)) {
John McCalle5255932011-01-31 22:28:28 +00006828 // T* -> _Bool
John McCall8cb679e2010-11-15 09:13:47 +00006829 if (lhsType == Context.BoolTy) {
6830 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006831 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006832 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006833
John McCalle5255932011-01-31 22:28:28 +00006834 // T* -> int
John McCall8cb679e2010-11-15 09:13:47 +00006835 if (lhsType->isIntegerType()) {
6836 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006837 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00006838 }
6839
Steve Naroff7cae42b2009-07-10 23:34:53 +00006840 return Incompatible;
6841 }
Eli Friedman3360d892008-05-30 18:07:22 +00006842
John McCalle5255932011-01-31 22:28:28 +00006843 // struct A -> struct B
Chris Lattnera52c2f22008-01-04 23:18:45 +00006844 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
John McCall8cb679e2010-11-15 09:13:47 +00006845 if (Context.typesAreCompatible(lhsType, rhsType)) {
6846 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00006847 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00006848 }
Bill Wendling216423b2007-05-30 06:30:29 +00006849 }
John McCalle5255932011-01-31 22:28:28 +00006850
Steve Naroff98cf3e92007-06-06 18:38:38 +00006851 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00006852}
6853
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006854/// \brief Constructs a transparent union from an expression that is
6855/// used to initialize the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00006856static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006857 QualType UnionType, FieldDecl *Field) {
6858 // Build an initializer list that designates the appropriate member
6859 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00006860 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00006861 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00006862 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006863 SourceLocation());
6864 Initializer->setType(UnionType);
6865 Initializer->setInitializedFieldInUnion(Field);
6866
6867 // Build a compound literal constructing a value of the transparent
6868 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00006869 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00006870 EResult = S.Owned(
6871 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6872 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006873}
6874
6875Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006876Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &rExpr) {
6877 QualType FromType = rExpr.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006878
Mike Stump11289f42009-09-09 15:08:12 +00006879 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006880 // transparent_union GCC extension.
6881 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006882 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006883 return Incompatible;
6884
6885 // The field to initialize within the transparent union.
6886 RecordDecl *UD = UT->getDecl();
6887 FieldDecl *InitField = 0;
6888 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006889 for (RecordDecl::field_iterator it = UD->field_begin(),
6890 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006891 it != itend; ++it) {
6892 if (it->getType()->isPointerType()) {
6893 // If the transparent union contains a pointer type, we allow:
6894 // 1) void pointer
6895 // 2) null pointer constant
6896 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006897 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
John Wiegley01296292011-04-08 18:41:53 +00006898 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006899 InitField = *it;
6900 break;
6901 }
Mike Stump11289f42009-09-09 15:08:12 +00006902
John Wiegley01296292011-04-08 18:41:53 +00006903 if (rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006904 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006905 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006906 InitField = *it;
6907 break;
6908 }
6909 }
6910
John McCall8cb679e2010-11-15 09:13:47 +00006911 CastKind Kind = CK_Invalid;
John Wiegley01296292011-04-08 18:41:53 +00006912 if (CheckAssignmentConstraints(it->getType(), rExpr, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006913 == Compatible) {
John Wiegley01296292011-04-08 18:41:53 +00006914 rExpr = ImpCastExprToType(rExpr.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006915 InitField = *it;
6916 break;
6917 }
6918 }
6919
6920 if (!InitField)
6921 return Incompatible;
6922
John Wiegley01296292011-04-08 18:41:53 +00006923 ConstructTransparentUnion(*this, Context, rExpr, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00006924 return Compatible;
6925}
6926
Chris Lattner9bad62c2008-01-04 18:04:52 +00006927Sema::AssignConvertType
John Wiegley01296292011-04-08 18:41:53 +00006928Sema::CheckSingleAssignmentConstraints(QualType lhsType, ExprResult &rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00006929 if (getLangOptions().CPlusPlus) {
6930 if (!lhsType->isRecordType()) {
6931 // C++ 5.17p3: If the left operand is not of class type, the
6932 // expression is implicitly converted (C++ 4) to the
6933 // cv-unqualified type of the left operand.
John Wiegley01296292011-04-08 18:41:53 +00006934 ExprResult Res = PerformImplicitConversion(rExpr.get(),
6935 lhsType.getUnqualifiedType(),
6936 AA_Assigning);
6937 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00006938 return Incompatible;
John Wiegley01296292011-04-08 18:41:53 +00006939 rExpr = move(Res);
Chris Lattner0d5640c2009-04-12 09:02:39 +00006940 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00006941 }
6942
6943 // FIXME: Currently, we fall through and treat C++ classes like C
6944 // structures.
John McCall34376a62010-12-04 03:47:34 +00006945 }
Douglas Gregor9a657932008-10-21 23:43:52 +00006946
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006947 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6948 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00006949 if ((lhsType->isPointerType() ||
6950 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00006951 lhsType->isBlockPointerType())
John Wiegley01296292011-04-08 18:41:53 +00006952 && rExpr.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006953 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00006954 rExpr = ImpCastExprToType(rExpr.take(), lhsType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00006955 return Compatible;
6956 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006957
Chris Lattnere6dcd502007-10-16 02:55:40 +00006958 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006959 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00006960 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00006961 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00006962 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00006963 // Suppress this for references: C++ 8.5.3p5.
John Wiegley01296292011-04-08 18:41:53 +00006964 if (!lhsType->isReferenceType()) {
6965 rExpr = DefaultFunctionArrayLvalueConversion(rExpr.take());
6966 if (rExpr.isInvalid())
6967 return Incompatible;
6968 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006969
John McCall8cb679e2010-11-15 09:13:47 +00006970 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006971 Sema::AssignConvertType result =
John McCall29600e12010-11-16 02:32:08 +00006972 CheckAssignmentConstraints(lhsType, rExpr, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006973
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006974 // C99 6.5.16.1p2: The value of the right operand is converted to the
6975 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00006976 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6977 // so that we can use references in built-in functions even in C.
6978 // The getNonReferenceType() call makes sure that the resulting expression
6979 // does not have reference type.
John Wiegley01296292011-04-08 18:41:53 +00006980 if (result != Incompatible && rExpr.get()->getType() != lhsType)
6981 rExpr = ImpCastExprToType(rExpr.take(), lhsType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00006982 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006983}
6984
John Wiegley01296292011-04-08 18:41:53 +00006985QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006986 Diag(Loc, diag::err_typecheck_invalid_operands)
John Wiegley01296292011-04-08 18:41:53 +00006987 << lex.get()->getType() << rex.get()->getType()
6988 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00006989 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00006990}
6991
John Wiegley01296292011-04-08 18:41:53 +00006992QualType Sema::CheckVectorOperands(SourceLocation Loc, ExprResult &lex, ExprResult &rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00006993 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00006994 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00006995 QualType lhsType =
John Wiegley01296292011-04-08 18:41:53 +00006996 Context.getCanonicalType(lex.get()->getType()).getUnqualifiedType();
Chris Lattner574dee62008-07-26 22:17:49 +00006997 QualType rhsType =
John Wiegley01296292011-04-08 18:41:53 +00006998 Context.getCanonicalType(rex.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006999
Nate Begeman191a6b12008-07-14 18:02:46 +00007000 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00007001 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00007002 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00007003
Nate Begeman191a6b12008-07-14 18:02:46 +00007004 // Handle the case of a vector & extvector type of the same size and element
7005 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00007006 if (getLangOptions().LaxVectorConversions) {
John McCall9dd450b2009-09-21 23:43:11 +00007007 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00007008 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00007009 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00007010 LV->getNumElements() == RV->getNumElements()) {
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007011 if (lhsType->isExtVectorType()) {
John Wiegley01296292011-04-08 18:41:53 +00007012 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007013 return lhsType;
7014 }
7015
John Wiegley01296292011-04-08 18:41:53 +00007016 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00007017 return rhsType;
Eric Christophera613f562010-08-26 00:42:16 +00007018 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
7019 // If we are allowing lax vector conversions, and LHS and RHS are both
7020 // vectors, the total size only needs to be the same. This is a
7021 // bitcast; no bits are changed but the result type is different.
John Wiegley01296292011-04-08 18:41:53 +00007022 rex = ImpCastExprToType(rex.take(), lhsType, CK_BitCast);
Eric Christophera613f562010-08-26 00:42:16 +00007023 return lhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00007024 }
Eric Christophera613f562010-08-26 00:42:16 +00007025 }
Chandler Carruth9ed87ba2010-08-30 07:36:24 +00007026 }
Anders Carlssondb5a9b62009-01-30 23:17:46 +00007027 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007028
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007029 // Handle the case of equivalent AltiVec and GCC vector types
7030 if (lhsType->isVectorType() && rhsType->isVectorType() &&
7031 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
John Wiegley01296292011-04-08 18:41:53 +00007032 lex = ImpCastExprToType(lex.take(), rhsType, CK_BitCast);
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007033 return rhsType;
7034 }
7035
Nate Begemanbd956c42009-06-28 02:36:38 +00007036 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
7037 // swap back (so that we don't reverse the inputs to a subtract, for instance.
7038 bool swapped = false;
7039 if (rhsType->isExtVectorType()) {
7040 swapped = true;
7041 std::swap(rex, lex);
7042 std::swap(rhsType, lhsType);
7043 }
Mike Stump11289f42009-09-09 15:08:12 +00007044
Nate Begeman886448d2009-06-28 19:12:57 +00007045 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00007046 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00007047 QualType EltTy = LV->getElementType();
Douglas Gregor6972a622010-06-16 00:35:25 +00007048 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
John McCall8cb679e2010-11-15 09:13:47 +00007049 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
7050 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00007051 rex = ImpCastExprToType(rex.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00007052 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00007053 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00007054 if (swapped) std::swap(rex, lex);
7055 return lhsType;
7056 }
7057 }
7058 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
7059 rhsType->isRealFloatingType()) {
John McCall8cb679e2010-11-15 09:13:47 +00007060 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
7061 if (order > 0)
John Wiegley01296292011-04-08 18:41:53 +00007062 rex = ImpCastExprToType(rex.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00007063 if (order >= 0) {
John Wiegley01296292011-04-08 18:41:53 +00007064 rex = ImpCastExprToType(rex.take(), lhsType, CK_VectorSplat);
Nate Begemanbd956c42009-06-28 02:36:38 +00007065 if (swapped) std::swap(rex, lex);
7066 return lhsType;
7067 }
Nate Begeman330aaa72007-12-30 02:59:45 +00007068 }
7069 }
Mike Stump11289f42009-09-09 15:08:12 +00007070
Nate Begeman886448d2009-06-28 19:12:57 +00007071 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00007072 Diag(Loc, diag::err_typecheck_vector_not_convertable)
John Wiegley01296292011-04-08 18:41:53 +00007073 << lex.get()->getType() << rex.get()->getType()
7074 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00007075 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00007076}
7077
Chris Lattnerfaa54172010-01-12 21:23:57 +00007078QualType Sema::CheckMultiplyDivideOperands(
John Wiegley01296292011-04-08 18:41:53 +00007079 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
7080 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00007081 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007082
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007083 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00007084 if (lex.isInvalid() || rex.isInvalid())
7085 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007086
John Wiegley01296292011-04-08 18:41:53 +00007087 if (!lex.get()->getType()->isArithmeticType() ||
7088 !rex.get()->getType()->isArithmeticType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00007089 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007090
Chris Lattnerfaa54172010-01-12 21:23:57 +00007091 // Check for division by zero.
7092 if (isDiv &&
John Wiegley01296292011-04-08 18:41:53 +00007093 rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
7094 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_division_by_zero)
7095 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007096
Chris Lattnerfaa54172010-01-12 21:23:57 +00007097 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00007098}
7099
Chris Lattnerfaa54172010-01-12 21:23:57 +00007100QualType Sema::CheckRemainderOperands(
John Wiegley01296292011-04-08 18:41:53 +00007101 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
7102 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
7103 if (lex.get()->getType()->hasIntegerRepresentation() &&
7104 rex.get()->getType()->hasIntegerRepresentation())
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00007105 return CheckVectorOperands(Loc, lex, rex);
7106 return InvalidOperands(Loc, lex, rex);
7107 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007108
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007109 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
John Wiegley01296292011-04-08 18:41:53 +00007110 if (lex.isInvalid() || rex.isInvalid())
7111 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007112
John Wiegley01296292011-04-08 18:41:53 +00007113 if (!lex.get()->getType()->isIntegerType() || !rex.get()->getType()->isIntegerType())
Chris Lattnerfaa54172010-01-12 21:23:57 +00007114 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007115
Chris Lattnerfaa54172010-01-12 21:23:57 +00007116 // Check for remainder by zero.
John Wiegley01296292011-04-08 18:41:53 +00007117 if (rex.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
7118 DiagRuntimeBehavior(Loc, rex.get(), PDiag(diag::warn_remainder_by_zero)
7119 << rex.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007120
Chris Lattnerfaa54172010-01-12 21:23:57 +00007121 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007122}
7123
Chris Lattnerfaa54172010-01-12 21:23:57 +00007124QualType Sema::CheckAdditionOperands( // C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00007125 ExprResult &lex, ExprResult &rex, SourceLocation Loc, QualType* CompLHSTy) {
7126 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007127 QualType compType = CheckVectorOperands(Loc, lex, rex);
7128 if (CompLHSTy) *CompLHSTy = compType;
7129 return compType;
7130 }
Steve Naroff7a5af782007-07-13 16:58:59 +00007131
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007132 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007133 if (lex.isInvalid() || rex.isInvalid())
7134 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00007135
Steve Naroffe4718892007-04-27 18:30:00 +00007136 // handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00007137 if (lex.get()->getType()->isArithmeticType() &&
7138 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007139 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007140 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007141 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00007142
Eli Friedman8e122982008-05-18 18:08:51 +00007143 // Put any potential pointer into PExp
John Wiegley01296292011-04-08 18:41:53 +00007144 Expr* PExp = lex.get(), *IExp = rex.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00007145 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00007146 std::swap(PExp, IExp);
7147
Steve Naroff6b712a72009-07-14 18:25:06 +00007148 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00007149
Eli Friedman8e122982008-05-18 18:08:51 +00007150 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00007151 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00007152
Chris Lattner12bdebb2009-04-24 23:50:08 +00007153 // Check for arithmetic on pointers to incomplete types.
7154 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00007155 if (getLangOptions().CPlusPlus) {
7156 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00007157 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00007158 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00007159 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00007160
7161 // GNU extension: arithmetic on pointer to void
7162 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00007163 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00007164 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00007165 if (getLangOptions().CPlusPlus) {
7166 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00007167 << lex.get()->getType() << lex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007168 return QualType();
7169 }
7170
7171 // GNU extension: arithmetic on pointer to function
7172 Diag(Loc, diag::ext_gnu_ptr_func_arith)
John Wiegley01296292011-04-08 18:41:53 +00007173 << lex.get()->getType() << lex.get()->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00007174 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00007175 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00007176 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00007177 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00007178 PExp->getType()->isObjCObjectPointerType()) &&
7179 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00007180 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
7181 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00007182 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00007183 return QualType();
7184 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00007185 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00007186 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00007187 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
7188 << PointeeTy << PExp->getSourceRange();
7189 return QualType();
7190 }
Mike Stump11289f42009-09-09 15:08:12 +00007191
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007192 if (CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00007193 QualType LHSTy = Context.isPromotableBitField(lex.get());
Eli Friedman629ffb92009-08-20 04:21:42 +00007194 if (LHSTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +00007195 LHSTy = lex.get()->getType();
Eli Friedman629ffb92009-08-20 04:21:42 +00007196 if (LHSTy->isPromotableIntegerType())
7197 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00007198 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007199 *CompLHSTy = LHSTy;
7200 }
Eli Friedman8e122982008-05-18 18:08:51 +00007201 return PExp->getType();
7202 }
7203 }
7204
Chris Lattner326f7572008-11-18 01:30:42 +00007205 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007206}
7207
Chris Lattner2a3569b2008-04-07 05:30:13 +00007208// C99 6.5.6
John Wiegley01296292011-04-08 18:41:53 +00007209QualType Sema::CheckSubtractionOperands(ExprResult &lex, ExprResult &rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007210 SourceLocation Loc, QualType* CompLHSTy) {
John Wiegley01296292011-04-08 18:41:53 +00007211 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007212 QualType compType = CheckVectorOperands(Loc, lex, rex);
7213 if (CompLHSTy) *CompLHSTy = compType;
7214 return compType;
7215 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007216
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007217 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00007218 if (lex.isInvalid() || rex.isInvalid())
7219 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007220
Chris Lattner4d62f422007-12-09 21:53:25 +00007221 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007222
Chris Lattner4d62f422007-12-09 21:53:25 +00007223 // Handle the common case first (both operands are arithmetic).
John Wiegley01296292011-04-08 18:41:53 +00007224 if (lex.get()->getType()->isArithmeticType() &&
7225 rex.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007226 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007227 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007228 }
Mike Stump11289f42009-09-09 15:08:12 +00007229
Chris Lattner4d62f422007-12-09 21:53:25 +00007230 // Either ptr - int or ptr - ptr.
John Wiegley01296292011-04-08 18:41:53 +00007231 if (lex.get()->getType()->isAnyPointerType()) {
7232 QualType lpointee = lex.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007233
Douglas Gregorac1fb652009-03-24 19:52:54 +00007234 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00007235
Douglas Gregorac1fb652009-03-24 19:52:54 +00007236 bool ComplainAboutVoid = false;
7237 Expr *ComplainAboutFunc = 0;
7238 if (lpointee->isVoidType()) {
7239 if (getLangOptions().CPlusPlus) {
7240 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00007241 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007242 return QualType();
7243 }
7244
7245 // GNU C extension: arithmetic on pointer to void
7246 ComplainAboutVoid = true;
7247 } else if (lpointee->isFunctionType()) {
7248 if (getLangOptions().CPlusPlus) {
7249 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00007250 << lex.get()->getType() << lex.get()->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00007251 return QualType();
7252 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00007253
7254 // GNU C extension: arithmetic on pointer to function
John Wiegley01296292011-04-08 18:41:53 +00007255 ComplainAboutFunc = lex.get();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007256 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00007257 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00007258 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley01296292011-04-08 18:41:53 +00007259 << lex.get()->getSourceRange()
7260 << lex.get()->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00007261 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00007262
Chris Lattner12bdebb2009-04-24 23:50:08 +00007263 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00007264 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner12bdebb2009-04-24 23:50:08 +00007265 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
John Wiegley01296292011-04-08 18:41:53 +00007266 << lpointee << lex.get()->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00007267 return QualType();
7268 }
Mike Stump11289f42009-09-09 15:08:12 +00007269
Chris Lattner4d62f422007-12-09 21:53:25 +00007270 // The result type of a pointer-int computation is the pointer type.
John Wiegley01296292011-04-08 18:41:53 +00007271 if (rex.get()->getType()->isIntegerType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00007272 if (ComplainAboutVoid)
7273 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00007274 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007275 if (ComplainAboutFunc)
7276 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00007277 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00007278 << ComplainAboutFunc->getSourceRange();
7279
John Wiegley01296292011-04-08 18:41:53 +00007280 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
7281 return lex.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007282 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007283
Chris Lattner4d62f422007-12-09 21:53:25 +00007284 // Handle pointer-pointer subtractions.
John Wiegley01296292011-04-08 18:41:53 +00007285 if (const PointerType *RHSPTy = rex.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00007286 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007287
Douglas Gregorac1fb652009-03-24 19:52:54 +00007288 // RHS must be a completely-type object type.
7289 // Handle the GNU void* extension.
7290 if (rpointee->isVoidType()) {
7291 if (getLangOptions().CPlusPlus) {
7292 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
John Wiegley01296292011-04-08 18:41:53 +00007293 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007294 return QualType();
7295 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007296
Douglas Gregorac1fb652009-03-24 19:52:54 +00007297 ComplainAboutVoid = true;
7298 } else if (rpointee->isFunctionType()) {
7299 if (getLangOptions().CPlusPlus) {
7300 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
John Wiegley01296292011-04-08 18:41:53 +00007301 << rex.get()->getType() << rex.get()->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00007302 return QualType();
7303 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00007304
7305 // GNU extension: arithmetic on pointer to function
7306 if (!ComplainAboutFunc)
John Wiegley01296292011-04-08 18:41:53 +00007307 ComplainAboutFunc = rex.get();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007308 } else if (!rpointee->isDependentType() &&
7309 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00007310 PDiag(diag::err_typecheck_sub_ptr_object)
John Wiegley01296292011-04-08 18:41:53 +00007311 << rex.get()->getSourceRange()
7312 << rex.get()->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00007313 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007314
Eli Friedman168fe152009-05-16 13:54:38 +00007315 if (getLangOptions().CPlusPlus) {
7316 // Pointee types must be the same: C++ [expr.add]
7317 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7318 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00007319 << lex.get()->getType() << rex.get()->getType()
7320 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00007321 return QualType();
7322 }
7323 } else {
7324 // Pointee types must be compatible C99 6.5.6p3
7325 if (!Context.typesAreCompatible(
7326 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7327 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7328 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
John Wiegley01296292011-04-08 18:41:53 +00007329 << lex.get()->getType() << rex.get()->getType()
7330 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman168fe152009-05-16 13:54:38 +00007331 return QualType();
7332 }
Chris Lattner4d62f422007-12-09 21:53:25 +00007333 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007334
Douglas Gregorac1fb652009-03-24 19:52:54 +00007335 if (ComplainAboutVoid)
7336 Diag(Loc, diag::ext_gnu_void_ptr)
John Wiegley01296292011-04-08 18:41:53 +00007337 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorac1fb652009-03-24 19:52:54 +00007338 if (ComplainAboutFunc)
7339 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00007340 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00007341 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007342
John Wiegley01296292011-04-08 18:41:53 +00007343 if (CompLHSTy) *CompLHSTy = lex.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00007344 return Context.getPointerDiffType();
7345 }
7346 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007347
Chris Lattner326f7572008-11-18 01:30:42 +00007348 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00007349}
7350
Douglas Gregor0bf31402010-10-08 23:50:27 +00007351static bool isScopedEnumerationType(QualType T) {
7352 if (const EnumType *ET = dyn_cast<EnumType>(T))
7353 return ET->getDecl()->isScoped();
7354 return false;
7355}
7356
John Wiegley01296292011-04-08 18:41:53 +00007357static void DiagnoseBadShiftValues(Sema& S, ExprResult &lex, ExprResult &rex,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007358 SourceLocation Loc, unsigned Opc,
7359 QualType LHSTy) {
7360 llvm::APSInt Right;
7361 // Check right/shifter operand
John Wiegley01296292011-04-08 18:41:53 +00007362 if (rex.get()->isValueDependent() || !rex.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007363 return;
7364
7365 if (Right.isNegative()) {
John Wiegley01296292011-04-08 18:41:53 +00007366 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00007367 S.PDiag(diag::warn_shift_negative)
John Wiegley01296292011-04-08 18:41:53 +00007368 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007369 return;
7370 }
7371 llvm::APInt LeftBits(Right.getBitWidth(),
John Wiegley01296292011-04-08 18:41:53 +00007372 S.Context.getTypeSize(lex.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007373 if (Right.uge(LeftBits)) {
John Wiegley01296292011-04-08 18:41:53 +00007374 S.DiagRuntimeBehavior(Loc, rex.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00007375 S.PDiag(diag::warn_shift_gt_typewidth)
John Wiegley01296292011-04-08 18:41:53 +00007376 << rex.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007377 return;
7378 }
7379 if (Opc != BO_Shl)
7380 return;
7381
7382 // When left shifting an ICE which is signed, we can check for overflow which
7383 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7384 // integers have defined behavior modulo one more than the maximum value
7385 // representable in the result type, so never warn for those.
7386 llvm::APSInt Left;
John Wiegley01296292011-04-08 18:41:53 +00007387 if (lex.get()->isValueDependent() || !lex.get()->isIntegerConstantExpr(Left, S.Context) ||
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007388 LHSTy->hasUnsignedIntegerRepresentation())
7389 return;
7390 llvm::APInt ResultBits =
7391 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7392 if (LeftBits.uge(ResultBits))
7393 return;
7394 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7395 Result = Result.shl(Right);
7396
7397 // If we are only missing a sign bit, this is less likely to result in actual
7398 // bugs -- if the result is cast back to an unsigned type, it will have the
7399 // expected value. Thus we place this behind a different warning that can be
7400 // turned off separately if needed.
7401 if (LeftBits == ResultBits - 1) {
7402 S.Diag(Loc, diag::warn_shift_result_overrides_sign_bit)
7403 << Result.toString(10) << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00007404 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007405 return;
7406 }
7407
7408 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7409 << Result.toString(10) << Result.getMinSignedBits() << LHSTy
John Wiegley01296292011-04-08 18:41:53 +00007410 << Left.getBitWidth() << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007411}
7412
Chris Lattner2a3569b2008-04-07 05:30:13 +00007413// C99 6.5.7
John Wiegley01296292011-04-08 18:41:53 +00007414QualType Sema::CheckShiftOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007415 unsigned Opc, bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00007416 // C99 6.5.7p2: Each of the operands shall have integer type.
John Wiegley01296292011-04-08 18:41:53 +00007417 if (!lex.get()->getType()->hasIntegerRepresentation() ||
7418 !rex.get()->getType()->hasIntegerRepresentation())
Chris Lattner326f7572008-11-18 01:30:42 +00007419 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007420
Douglas Gregor0bf31402010-10-08 23:50:27 +00007421 // C++0x: Don't allow scoped enums. FIXME: Use something better than
7422 // hasIntegerRepresentation() above instead of this.
John Wiegley01296292011-04-08 18:41:53 +00007423 if (isScopedEnumerationType(lex.get()->getType()) ||
7424 isScopedEnumerationType(rex.get()->getType())) {
Douglas Gregor0bf31402010-10-08 23:50:27 +00007425 return InvalidOperands(Loc, lex, rex);
7426 }
7427
Nate Begemane46ee9a2009-10-25 02:26:48 +00007428 // Vector shifts promote their scalar inputs to vector type.
John Wiegley01296292011-04-08 18:41:53 +00007429 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Nate Begemane46ee9a2009-10-25 02:26:48 +00007430 return CheckVectorOperands(Loc, lex, rex);
7431
Chris Lattner5c11c412007-12-12 05:47:28 +00007432 // Shifts don't perform usual arithmetic conversions, they just do integer
7433 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007434
John McCall57cdd882010-12-16 19:28:59 +00007435 // For the LHS, do usual unary conversions, but then reset them away
7436 // if this is a compound assignment.
John Wiegley01296292011-04-08 18:41:53 +00007437 ExprResult old_lex = lex;
7438 lex = UsualUnaryConversions(lex.take());
7439 if (lex.isInvalid())
7440 return QualType();
7441 QualType LHSTy = lex.get()->getType();
John McCall57cdd882010-12-16 19:28:59 +00007442 if (isCompAssign) lex = old_lex;
7443
7444 // The RHS is simpler.
John Wiegley01296292011-04-08 18:41:53 +00007445 rex = UsualUnaryConversions(rex.take());
7446 if (rex.isInvalid())
7447 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007448
Ryan Flynnf53fab82009-08-07 16:20:20 +00007449 // Sanity-check shift operands
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00007450 DiagnoseBadShiftValues(*this, lex, rex, Loc, Opc, LHSTy);
Ryan Flynnf53fab82009-08-07 16:20:20 +00007451
Chris Lattner5c11c412007-12-12 05:47:28 +00007452 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007453 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00007454}
7455
Chandler Carruth17773fc2010-07-10 12:30:03 +00007456static bool IsWithinTemplateSpecialization(Decl *D) {
7457 if (DeclContext *DC = D->getDeclContext()) {
7458 if (isa<ClassTemplateSpecializationDecl>(DC))
7459 return true;
7460 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7461 return FD->isFunctionTemplateSpecialization();
7462 }
7463 return false;
7464}
7465
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007466// C99 6.5.8, C++ [expr.rel]
John Wiegley01296292011-04-08 18:41:53 +00007467QualType Sema::CheckCompareOperands(ExprResult &lex, ExprResult &rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007468 unsigned OpaqueOpc, bool isRelational) {
John McCalle3027922010-08-25 11:45:40 +00007469 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007470
Chris Lattner9a152e22009-12-05 05:40:13 +00007471 // Handle vector comparisons separately.
John Wiegley01296292011-04-08 18:41:53 +00007472 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00007473 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007474
John Wiegley01296292011-04-08 18:41:53 +00007475 QualType lType = lex.get()->getType();
7476 QualType rType = rex.get()->getType();
Douglas Gregor1beec452011-03-12 01:48:56 +00007477
John Wiegley01296292011-04-08 18:41:53 +00007478 Expr *LHSStripped = lex.get()->IgnoreParenImpCasts();
7479 Expr *RHSStripped = rex.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00007480 QualType LHSStrippedType = LHSStripped->getType();
7481 QualType RHSStrippedType = RHSStripped->getType();
7482
Douglas Gregor1beec452011-03-12 01:48:56 +00007483
7484
Chandler Carruth712563b2011-02-17 08:37:06 +00007485 // Two different enums will raise a warning when compared.
7486 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
7487 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
7488 if (LHSEnumType->getDecl()->getIdentifier() &&
7489 RHSEnumType->getDecl()->getIdentifier() &&
7490 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
7491 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7492 << LHSStrippedType << RHSStrippedType
John Wiegley01296292011-04-08 18:41:53 +00007493 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Chandler Carruth712563b2011-02-17 08:37:06 +00007494 }
7495 }
7496 }
7497
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007498 if (!lType->hasFloatingRepresentation() &&
Ted Kremenek853734e2010-09-16 00:03:01 +00007499 !(lType->isBlockPointerType() && isRelational) &&
John Wiegley01296292011-04-08 18:41:53 +00007500 !lex.get()->getLocStart().isMacroID() &&
7501 !rex.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00007502 // For non-floating point types, check for self-comparisons of the form
7503 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7504 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00007505 //
7506 // NOTE: Don't warn about comparison expressions resulting from macro
7507 // expansion. Also don't warn about comparisons which are only self
7508 // comparisons within a template specialization. The warnings should catch
7509 // obvious cases in the definition of the template anyways. The idea is to
7510 // warn when the typed comparison operator will always evaluate to the same
7511 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00007512 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00007513 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00007514 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00007515 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00007516 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00007517 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00007518 << (Opc == BO_EQ
7519 || Opc == BO_LE
7520 || Opc == BO_GE));
Douglas Gregorec170db2010-06-08 19:50:34 +00007521 } else if (lType->isArrayType() && rType->isArrayType() &&
7522 !DRL->getDecl()->getType()->isReferenceType() &&
7523 !DRR->getDecl()->getType()->isReferenceType()) {
7524 // what is it always going to eval to?
7525 char always_evals_to;
7526 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00007527 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00007528 always_evals_to = 0; // false
7529 break;
John McCalle3027922010-08-25 11:45:40 +00007530 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00007531 always_evals_to = 1; // true
7532 break;
7533 default:
7534 // best we can say is 'a constant'
7535 always_evals_to = 2; // e.g. array1 <= array2
7536 break;
7537 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00007538 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00007539 << 1 // array
7540 << always_evals_to);
7541 }
7542 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00007543 }
Mike Stump11289f42009-09-09 15:08:12 +00007544
Chris Lattner222b8bd2009-03-08 19:39:53 +00007545 if (isa<CastExpr>(LHSStripped))
7546 LHSStripped = LHSStripped->IgnoreParenCasts();
7547 if (isa<CastExpr>(RHSStripped))
7548 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00007549
Chris Lattner222b8bd2009-03-08 19:39:53 +00007550 // Warn about comparisons against a string constant (unless the other
7551 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007552 Expr *literalString = 0;
7553 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00007554 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007555 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007556 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00007557 literalString = lex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007558 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00007559 } else if ((isa<StringLiteral>(RHSStripped) ||
7560 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007561 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007562 Expr::NPC_ValueDependentIsNull)) {
John Wiegley01296292011-04-08 18:41:53 +00007563 literalString = rex.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007564 literalStringStripped = RHSStripped;
7565 }
7566
7567 if (literalString) {
7568 std::string resultComparison;
7569 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007570 case BO_LT: resultComparison = ") < 0"; break;
7571 case BO_GT: resultComparison = ") > 0"; break;
7572 case BO_LE: resultComparison = ") <= 0"; break;
7573 case BO_GE: resultComparison = ") >= 0"; break;
7574 case BO_EQ: resultComparison = ") == 0"; break;
7575 case BO_NE: resultComparison = ") != 0"; break;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007576 default: assert(false && "Invalid comparison operator");
7577 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007578
Ted Kremenek3427fac2011-02-23 01:52:04 +00007579 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00007580 PDiag(diag::warn_stringcompare)
7581 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00007582 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00007583 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00007584 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007585
Douglas Gregorec170db2010-06-08 19:50:34 +00007586 // C99 6.5.8p3 / C99 6.5.9p4
John Wiegley01296292011-04-08 18:41:53 +00007587 if (lex.get()->getType()->isArithmeticType() && rex.get()->getType()->isArithmeticType()) {
Douglas Gregorec170db2010-06-08 19:50:34 +00007588 UsualArithmeticConversions(lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00007589 if (lex.isInvalid() || rex.isInvalid())
7590 return QualType();
7591 }
Douglas Gregorec170db2010-06-08 19:50:34 +00007592 else {
John Wiegley01296292011-04-08 18:41:53 +00007593 lex = UsualUnaryConversions(lex.take());
7594 if (lex.isInvalid())
7595 return QualType();
7596
7597 rex = UsualUnaryConversions(rex.take());
7598 if (rex.isInvalid())
7599 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007600 }
7601
John Wiegley01296292011-04-08 18:41:53 +00007602 lType = lex.get()->getType();
7603 rType = rex.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00007604
Douglas Gregorca63811b2008-11-19 03:25:36 +00007605 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00007606 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00007607
Chris Lattnerb620c342007-08-26 01:18:55 +00007608 if (isRelational) {
7609 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007610 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007611 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00007612 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007613 if (lType->hasFloatingRepresentation())
John Wiegley01296292011-04-08 18:41:53 +00007614 CheckFloatComparison(Loc, lex.get(), rex.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007615
Chris Lattnerb620c342007-08-26 01:18:55 +00007616 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00007617 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00007618 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007619
John Wiegley01296292011-04-08 18:41:53 +00007620 bool LHSIsNull = lex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007621 Expr::NPC_ValueDependentIsNull);
John Wiegley01296292011-04-08 18:41:53 +00007622 bool RHSIsNull = rex.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00007623 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007624
Douglas Gregorf267edd2010-06-15 21:38:40 +00007625 // All of the following pointer-related warnings are GCC extensions, except
7626 // when handling null pointer constants.
Steve Naroff808eb8f2007-08-27 04:08:11 +00007627 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00007628 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007629 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00007630 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007631 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00007632
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007633 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00007634 if (LCanPointeeTy == RCanPointeeTy)
7635 return ResultTy;
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007636 if (!isRelational &&
7637 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7638 // Valid unless comparison between non-null pointer and function pointer
7639 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00007640 // In a SFINAE context, we treat this as a hard error to maintain
7641 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007642 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7643 && !LHSIsNull && !RHSIsNull) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00007644 Diag(Loc,
7645 isSFINAEContext()?
7646 diag::err_typecheck_comparison_of_fptr_to_void
7647 : diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00007648 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007649
7650 if (isSFINAEContext())
7651 return QualType();
7652
John Wiegley01296292011-04-08 18:41:53 +00007653 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00007654 return ResultTy;
7655 }
7656 }
Anders Carlssona95069c2010-11-04 03:17:43 +00007657
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007658 // C++ [expr.rel]p2:
7659 // [...] Pointer conversions (4.10) and qualification
7660 // conversions (4.4) are performed on pointer operands (or on
7661 // a pointer operand and a null pointer constant) to bring
7662 // them to their composite pointer type. [...]
7663 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007664 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007665 // comparisons of pointers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007666 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007667 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007668 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007669 if (T.isNull()) {
7670 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007671 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007672 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007673 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007674 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007675 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007676 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00007677 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007678 }
7679
John Wiegley01296292011-04-08 18:41:53 +00007680 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7681 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00007682 return ResultTy;
7683 }
Eli Friedman16c209612009-08-23 00:27:47 +00007684 // C99 6.5.9p2 and C99 6.5.8p2
7685 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7686 RCanPointeeTy.getUnqualifiedType())) {
7687 // Valid unless a relational comparison of function pointers
7688 if (isRelational && LCanPointeeTy->isFunctionType()) {
7689 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007690 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007691 }
7692 } else if (!isRelational &&
7693 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7694 // Valid unless comparison between non-null pointer and function pointer
7695 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7696 && !LHSIsNull && !RHSIsNull) {
7697 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
John Wiegley01296292011-04-08 18:41:53 +00007698 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00007699 }
7700 } else {
7701 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00007702 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007703 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00007704 }
John McCall7684dde2011-03-11 04:25:25 +00007705 if (LCanPointeeTy != RCanPointeeTy) {
7706 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007707 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007708 else
John Wiegley01296292011-04-08 18:41:53 +00007709 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007710 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00007711 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00007712 }
Mike Stump11289f42009-09-09 15:08:12 +00007713
Sebastian Redl576fd422009-05-10 18:38:11 +00007714 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00007715 // Comparison of nullptr_t with itself.
7716 if (lType->isNullPtrType() && rType->isNullPtrType())
7717 return ResultTy;
7718
Mike Stump11289f42009-09-09 15:08:12 +00007719 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007720 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00007721 if (RHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00007722 ((lType->isAnyPointerType() || lType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007723 (!isRelational && lType->isMemberPointerType()))) {
John Wiegley01296292011-04-08 18:41:53 +00007724 rex = ImpCastExprToType(rex.take(), lType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00007725 lType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007726 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007727 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007728 return ResultTy;
7729 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007730 if (LHSIsNull &&
Douglas Gregor39e9fa92011-06-01 15:12:24 +00007731 ((rType->isAnyPointerType() || rType->isNullPtrType()) ||
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007732 (!isRelational && rType->isMemberPointerType()))) {
John Wiegley01296292011-04-08 18:41:53 +00007733 lex = ImpCastExprToType(lex.take(), rType,
Douglas Gregorf58ff322010-08-07 13:36:37 +00007734 rType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00007735 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00007736 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00007737 return ResultTy;
7738 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007739
7740 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00007741 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007742 lType->isMemberPointerType() && rType->isMemberPointerType()) {
7743 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00007744 // In addition, pointers to members can be compared, or a pointer to
7745 // member and a null pointer constant. Pointer to member conversions
7746 // (4.11) and qualification conversions (4.4) are performed to bring
7747 // them to a common type. If one operand is a null pointer constant,
7748 // the common type is the type of the other operand. Otherwise, the
7749 // common type is a pointer to member type similar (4.4) to the type
7750 // of one of the operands, with a cv-qualification signature (4.4)
7751 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007752 // types.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007753 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00007754 QualType T = FindCompositePointerType(Loc, lex, rex,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007755 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007756 if (T.isNull()) {
7757 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007758 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007759 return QualType();
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007760 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007761 Diag(Loc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00007762 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007763 << lType << rType << T
John Wiegley01296292011-04-08 18:41:53 +00007764 << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007765 }
Mike Stump11289f42009-09-09 15:08:12 +00007766
John Wiegley01296292011-04-08 18:41:53 +00007767 lex = ImpCastExprToType(lex.take(), T, CK_BitCast);
7768 rex = ImpCastExprToType(rex.take(), T, CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007769 return ResultTy;
7770 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007771
7772 // Handle scoped enumeration types specifically, since they don't promote
7773 // to integers.
John Wiegley01296292011-04-08 18:41:53 +00007774 if (lex.get()->getType()->isEnumeralType() &&
7775 Context.hasSameUnqualifiedType(lex.get()->getType(), rex.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007776 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00007777 }
Mike Stump11289f42009-09-09 15:08:12 +00007778
Steve Naroff081c7422008-09-04 15:10:53 +00007779 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00007780 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007781 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
7782 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007783
Steve Naroff081c7422008-09-04 15:10:53 +00007784 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007785 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007786 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00007787 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007788 }
John Wiegley01296292011-04-08 18:41:53 +00007789 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007790 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007791 }
John Wiegley01296292011-04-08 18:41:53 +00007792
Steve Naroffe18f94c2008-09-28 01:11:11 +00007793 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00007794 if (!isRelational
7795 && ((lType->isBlockPointerType() && rType->isPointerType())
7796 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007797 if (!LHSIsNull && !RHSIsNull) {
John McCall7684dde2011-03-11 04:25:25 +00007798 if (!((rType->isPointerType() && rType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007799 ->getPointeeType()->isVoidType())
John McCall7684dde2011-03-11 04:25:25 +00007800 || (lType->isPointerType() && lType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007801 ->getPointeeType()->isVoidType())))
7802 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
John Wiegley01296292011-04-08 18:41:53 +00007803 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007804 }
John McCall7684dde2011-03-11 04:25:25 +00007805 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007806 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007807 else
John Wiegley01296292011-04-08 18:41:53 +00007808 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007809 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007810 }
Steve Naroff081c7422008-09-04 15:10:53 +00007811
John McCall7684dde2011-03-11 04:25:25 +00007812 if (lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType()) {
7813 const PointerType *LPT = lType->getAs<PointerType>();
7814 const PointerType *RPT = rType->getAs<PointerType>();
7815 if (LPT || RPT) {
7816 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7817 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007818
Steve Naroff753567f2008-11-17 19:49:16 +00007819 if (!LPtrToVoid && !RPtrToVoid &&
7820 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007821 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007822 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007823 }
John McCall7684dde2011-03-11 04:25:25 +00007824 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007825 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007826 else
John Wiegley01296292011-04-08 18:41:53 +00007827 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007828 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007829 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007830 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007831 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007832 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
John Wiegley01296292011-04-08 18:41:53 +00007833 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
John McCall7684dde2011-03-11 04:25:25 +00007834 if (LHSIsNull && !RHSIsNull)
John Wiegley01296292011-04-08 18:41:53 +00007835 lex = ImpCastExprToType(lex.take(), rType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007836 else
John Wiegley01296292011-04-08 18:41:53 +00007837 rex = ImpCastExprToType(rex.take(), lType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007838 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007839 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007840 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007841 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
7842 (lType->isIntegerType() && rType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007843 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007844 bool isError = false;
7845 if ((LHSIsNull && lType->isIntegerType()) ||
7846 (RHSIsNull && rType->isIntegerType())) {
7847 if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007848 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007849 } else if (isRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007850 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007851 else if (getLangOptions().CPlusPlus) {
7852 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7853 isError = true;
7854 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007855 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007856
Chris Lattnerd99bd522009-08-23 00:03:44 +00007857 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007858 Diag(Loc, DiagID)
John Wiegley01296292011-04-08 18:41:53 +00007859 << lType << rType << lex.get()->getSourceRange() << rex.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007860 if (isError)
7861 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007862 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007863
7864 if (lType->isIntegerType())
John Wiegley01296292011-04-08 18:41:53 +00007865 lex = ImpCastExprToType(lex.take(), rType,
John McCalle84af4e2010-11-13 01:35:44 +00007866 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007867 else
John Wiegley01296292011-04-08 18:41:53 +00007868 rex = ImpCastExprToType(rex.take(), lType,
John McCalle84af4e2010-11-13 01:35:44 +00007869 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007870 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007871 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007872
Steve Naroff4b191572008-09-04 16:56:14 +00007873 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00007874 if (!isRelational && RHSIsNull
7875 && lType->isBlockPointerType() && rType->isIntegerType()) {
John Wiegley01296292011-04-08 18:41:53 +00007876 rex = ImpCastExprToType(rex.take(), lType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007877 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007878 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00007879 if (!isRelational && LHSIsNull
7880 && lType->isIntegerType() && rType->isBlockPointerType()) {
John Wiegley01296292011-04-08 18:41:53 +00007881 lex = ImpCastExprToType(lex.take(), rType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007882 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007883 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007884
Chris Lattner326f7572008-11-18 01:30:42 +00007885 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007886}
7887
Nate Begeman191a6b12008-07-14 18:02:46 +00007888/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007889/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007890/// like a scalar comparison, a vector comparison produces a vector of integer
7891/// types.
John Wiegley01296292011-04-08 18:41:53 +00007892QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex,
Chris Lattner326f7572008-11-18 01:30:42 +00007893 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00007894 bool isRelational) {
7895 // Check to make sure we're operating on vectors of the same type and width,
7896 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00007897 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00007898 if (vType.isNull())
7899 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007900
John Wiegley01296292011-04-08 18:41:53 +00007901 QualType lType = lex.get()->getType();
7902 QualType rType = rex.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007903
Anton Yartsev530deb92011-03-27 15:36:07 +00007904 // If AltiVec, the comparison results in a numeric type, i.e.
7905 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00007906 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00007907 return Context.getLogicalOperationType();
7908
Nate Begeman191a6b12008-07-14 18:02:46 +00007909 // For non-floating point types, check for self-comparisons of the form
7910 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7911 // often indicate logic errors in the program.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007912 if (!lType->hasFloatingRepresentation()) {
John Wiegley01296292011-04-08 18:41:53 +00007913 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens()))
7914 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens()))
Nate Begeman191a6b12008-07-14 18:02:46 +00007915 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007916 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007917 PDiag(diag::warn_comparison_always)
7918 << 0 // self-
7919 << 2 // "a constant"
7920 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007921 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007922
Nate Begeman191a6b12008-07-14 18:02:46 +00007923 // Check for comparisons of floating point operands using != and ==.
Douglas Gregor4ffbad12010-06-22 22:12:46 +00007924 if (!isRelational && lType->hasFloatingRepresentation()) {
7925 assert (rType->hasFloatingRepresentation());
John Wiegley01296292011-04-08 18:41:53 +00007926 CheckFloatComparison(Loc, lex.get(), rex.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00007927 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007928
Nate Begeman191a6b12008-07-14 18:02:46 +00007929 // Return the type for the comparison, which is the same as vector type for
7930 // integer vectors, or an integer type of identical size and number of
7931 // elements for floating point vectors.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007932 if (lType->hasIntegerRepresentation())
Nate Begeman191a6b12008-07-14 18:02:46 +00007933 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007934
John McCall9dd450b2009-09-21 23:43:11 +00007935 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00007936 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007937 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00007938 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00007939 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007940 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7941
Mike Stump4e1f26a2009-02-19 03:04:26 +00007942 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007943 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00007944 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7945}
7946
Steve Naroff218bc2b2007-05-04 21:54:46 +00007947inline QualType Sema::CheckBitwiseOperands(
John Wiegley01296292011-04-08 18:41:53 +00007948 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) {
7949 if (lex.get()->getType()->isVectorType() || rex.get()->getType()->isVectorType()) {
7950 if (lex.get()->getType()->hasIntegerRepresentation() &&
7951 rex.get()->getType()->hasIntegerRepresentation())
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007952 return CheckVectorOperands(Loc, lex, rex);
7953
7954 return InvalidOperands(Loc, lex, rex);
7955 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007956
John Wiegley01296292011-04-08 18:41:53 +00007957 ExprResult lexResult = Owned(lex), rexResult = Owned(rex);
7958 QualType compType = UsualArithmeticConversions(lexResult, rexResult, isCompAssign);
7959 if (lexResult.isInvalid() || rexResult.isInvalid())
7960 return QualType();
7961 lex = lexResult.take();
7962 rex = rexResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007963
John Wiegley01296292011-04-08 18:41:53 +00007964 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
7965 rex.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007966 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00007967 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007968}
7969
Steve Naroff218bc2b2007-05-04 21:54:46 +00007970inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
John Wiegley01296292011-04-08 18:41:53 +00007971 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00007972
7973 // Diagnose cases where the user write a logical and/or but probably meant a
7974 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7975 // is a constant.
John Wiegley01296292011-04-08 18:41:53 +00007976 if (lex.get()->getType()->isIntegerType() && !lex.get()->getType()->isBooleanType() &&
7977 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() &&
Chris Lattnerdeee7a32010-07-15 00:26:43 +00007978 // Don't warn in macros.
Chris Lattner938533d2010-07-24 01:10:11 +00007979 !Loc.isMacroID()) {
7980 // If the RHS can be constant folded, and if it constant folds to something
7981 // that isn't 0 or 1 (which indicate a potential logical operation that
7982 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007983 // Parens on the RHS are ignored.
Chris Lattner938533d2010-07-24 01:10:11 +00007984 Expr::EvalResult Result;
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007985 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
7986 if ((getLangOptions().Bool && !rex.get()->getType()->isBooleanType()) ||
7987 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
7988 Diag(Loc, diag::warn_logical_instead_of_bitwise)
7989 << rex.get()->getSourceRange()
7990 << (Opc == BO_LAnd ? "&&" : "||")
7991 << (Opc == BO_LAnd ? "&" : "|");
Chris Lattner938533d2010-07-24 01:10:11 +00007992 }
7993 }
Chris Lattner8406c512010-07-13 19:41:32 +00007994
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007995 if (!Context.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007996 lex = UsualUnaryConversions(lex.take());
7997 if (lex.isInvalid())
7998 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007999
John Wiegley01296292011-04-08 18:41:53 +00008000 rex = UsualUnaryConversions(rex.take());
8001 if (rex.isInvalid())
8002 return QualType();
8003
8004 if (!lex.get()->getType()->isScalarType() || !rex.get()->getType()->isScalarType())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00008005 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008006
Anders Carlsson2e7bc112009-11-23 21:47:44 +00008007 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00008008 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008009
John McCall4a2429a2010-06-04 00:29:51 +00008010 // The following is safe because we only use this method for
8011 // non-overloadable operands.
8012
Anders Carlsson2e7bc112009-11-23 21:47:44 +00008013 // C++ [expr.log.and]p1
8014 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00008015 // The operands are both contextually converted to type bool.
John Wiegley01296292011-04-08 18:41:53 +00008016 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get());
8017 if (lexRes.isInvalid())
Anders Carlsson2e7bc112009-11-23 21:47:44 +00008018 return InvalidOperands(Loc, lex, rex);
John Wiegley01296292011-04-08 18:41:53 +00008019 lex = move(lexRes);
8020
8021 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get());
8022 if (rexRes.isInvalid())
8023 return InvalidOperands(Loc, lex, rex);
8024 rex = move(rexRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008025
Anders Carlsson2e7bc112009-11-23 21:47:44 +00008026 // C++ [expr.log.and]p2
8027 // C++ [expr.log.or]p2
8028 // The result is a bool.
8029 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00008030}
8031
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00008032/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
8033/// is a read-only property; return true if so. A readonly property expression
8034/// depends on various declarations and thus must be treated specially.
8035///
Mike Stump11289f42009-09-09 15:08:12 +00008036static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00008037 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
8038 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
John McCallb7bd14f2010-12-02 01:19:52 +00008039 if (PropExpr->isImplicitProperty()) return false;
8040
8041 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
8042 QualType BaseType = PropExpr->isSuperReceiver() ?
8043 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00008044 PropExpr->getBase()->getType();
8045
John McCallb7bd14f2010-12-02 01:19:52 +00008046 if (const ObjCObjectPointerType *OPT =
8047 BaseType->getAsObjCInterfacePointerType())
8048 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
8049 if (S.isPropertyReadonly(PDecl, IFace))
8050 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00008051 }
8052 return false;
8053}
8054
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00008055static bool IsConstProperty(Expr *E, Sema &S) {
8056 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
8057 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
8058 if (PropExpr->isImplicitProperty()) return false;
8059
8060 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
8061 QualType T = PDecl->getType();
8062 if (T->isReferenceType())
Fariborz Jahanian20688cc2011-03-30 16:59:30 +00008063 T = T->getAs<ReferenceType>()->getPointeeType();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00008064 CanQualType CT = S.Context.getCanonicalType(T);
8065 return CT.isConstQualified();
8066 }
8067 return false;
8068}
8069
Fariborz Jahanian071caef2011-03-26 19:48:30 +00008070static bool IsReadonlyMessage(Expr *E, Sema &S) {
8071 if (E->getStmtClass() != Expr::MemberExprClass)
8072 return false;
8073 const MemberExpr *ME = cast<MemberExpr>(E);
8074 NamedDecl *Member = ME->getMemberDecl();
8075 if (isa<FieldDecl>(Member)) {
8076 Expr *Base = ME->getBase()->IgnoreParenImpCasts();
8077 if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
8078 return false;
8079 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
8080 }
8081 return false;
8082}
8083
Chris Lattner30bd3272008-11-18 01:22:49 +00008084/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
8085/// emit an error and return true. If so, return false.
8086static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00008087 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00008088 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00008089 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00008090 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
8091 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00008092 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
8093 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00008094 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
8095 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00008096 if (IsLV == Expr::MLV_Valid)
8097 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008098
Chris Lattner30bd3272008-11-18 01:22:49 +00008099 unsigned Diag = 0;
8100 bool NeedType = false;
8101 switch (IsLV) { // C99 6.5.16p2
Chris Lattner30bd3272008-11-18 01:22:49 +00008102 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008103 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00008104 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
8105 NeedType = true;
8106 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008107 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00008108 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
8109 NeedType = true;
8110 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00008111 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00008112 Diag = diag::err_typecheck_lvalue_casts_not_supported;
8113 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008114 case Expr::MLV_Valid:
8115 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00008116 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008117 case Expr::MLV_MemberFunction:
8118 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00008119 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
8120 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008121 case Expr::MLV_IncompleteType:
8122 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00008123 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00008124 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00008125 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00008126 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00008127 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
8128 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00008129 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00008130 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
8131 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00008132 case Expr::MLV_ReadonlyProperty:
8133 Diag = diag::error_readonly_property_assignment;
8134 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00008135 case Expr::MLV_NoSetterProperty:
8136 Diag = diag::error_nosetter_property_assignment;
8137 break;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00008138 case Expr::MLV_InvalidMessageExpression:
8139 Diag = diag::error_readonly_message_assignment;
8140 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00008141 case Expr::MLV_SubObjCPropertySetting:
8142 Diag = diag::error_no_subobject_property_setting;
8143 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008144 }
Steve Naroffad373bd2007-07-31 12:34:36 +00008145
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00008146 SourceRange Assign;
8147 if (Loc != OrigLoc)
8148 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00008149 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00008150 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00008151 else
Mike Stump11289f42009-09-09 15:08:12 +00008152 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00008153 return true;
8154}
8155
8156
8157
8158// C99 6.5.16.1
John Wiegley01296292011-04-08 18:41:53 +00008159QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00008160 SourceLocation Loc,
8161 QualType CompoundType) {
8162 // Verify that LHS is a modifiable lvalue, and emit error if not.
8163 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00008164 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00008165
8166 QualType LHSType = LHS->getType();
John Wiegley01296292011-04-08 18:41:53 +00008167 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00008168 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00008169 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00008170 QualType LHSTy(LHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00008171 // Simple assignment "x = y".
John Wiegley01296292011-04-08 18:41:53 +00008172 if (LHS->getObjectKind() == OK_ObjCProperty) {
8173 ExprResult LHSResult = Owned(LHS);
8174 ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
8175 if (LHSResult.isInvalid())
8176 return QualType();
8177 LHS = LHSResult.take();
8178 }
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00008179 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00008180 if (RHS.isInvalid())
8181 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00008182 // Special case of NSObject attributes on c-style pointer types.
8183 if (ConvTy == IncompatiblePointer &&
8184 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00008185 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00008186 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00008187 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00008188 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008189
John McCall7decc9e2010-11-18 06:31:45 +00008190 if (ConvTy == Compatible &&
8191 getLangOptions().ObjCNonFragileABI &&
8192 LHSType->isObjCObjectType())
8193 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
8194 << LHSType;
8195
Chris Lattnerea714382008-08-21 18:04:13 +00008196 // If the RHS is a unary plus or minus, check to see if they = and + are
8197 // right next to each other. If so, the user may have typo'd "x =+ 4"
8198 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00008199 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00008200 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8201 RHSCheck = ICE->getSubExpr();
8202 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00008203 if ((UO->getOpcode() == UO_Plus ||
8204 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00008205 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00008206 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00008207 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
8208 // And there is a space or other character before the subexpr of the
8209 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00008210 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
8211 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00008212 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00008213 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00008214 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00008215 }
Chris Lattnerea714382008-08-21 18:04:13 +00008216 }
8217 } else {
8218 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00008219 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00008220 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00008221
Chris Lattner326f7572008-11-18 01:30:42 +00008222 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00008223 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00008224 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00008225
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +00008226 CheckForNullPointerDereference(*this, LHS);
Ted Kremenek64699be2011-02-16 01:57:07 +00008227 // Check for trivial buffer overflows.
Ted Kremenekdf26df72011-03-01 18:41:00 +00008228 CheckArrayAccess(LHS->IgnoreParenCasts());
Ted Kremenek64699be2011-02-16 01:57:07 +00008229
Steve Naroff98cf3e92007-06-06 18:38:38 +00008230 // C99 6.5.16p3: The type of an assignment expression is the type of the
8231 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00008232 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00008233 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8234 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00008235 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00008236 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00008237 return (getLangOptions().CPlusPlus
8238 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00008239}
8240
Chris Lattner326f7572008-11-18 01:30:42 +00008241// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00008242static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00008243 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00008244 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00008245
John McCall3aef3d82011-04-10 19:13:55 +00008246 LHS = S.CheckPlaceholderExpr(LHS.take());
8247 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00008248 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00008249 return QualType();
8250
John McCall73d36182010-10-12 07:14:40 +00008251 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8252 // operands, but not unary promotions.
8253 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00008254
John McCall34376a62010-12-04 03:47:34 +00008255 // So we treat the LHS as a ignored value, and in C++ we allow the
8256 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00008257 LHS = S.IgnoredValueConversions(LHS.take());
8258 if (LHS.isInvalid())
8259 return QualType();
John McCall34376a62010-12-04 03:47:34 +00008260
8261 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00008262 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8263 if (RHS.isInvalid())
8264 return QualType();
8265 if (!RHS.get()->getType()->isVoidType())
8266 S.RequireCompleteType(Loc, RHS.get()->getType(), diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00008267 }
Eli Friedmanba961a92009-03-23 00:24:07 +00008268
John Wiegley01296292011-04-08 18:41:53 +00008269 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00008270}
8271
Steve Naroff7a5af782007-07-13 16:58:59 +00008272/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8273/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00008274static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8275 ExprValueKind &VK,
8276 SourceLocation OpLoc,
8277 bool isInc, bool isPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008278 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008279 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008280
Chris Lattner6b0cf142008-11-21 07:05:48 +00008281 QualType ResType = Op->getType();
8282 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00008283
John McCall4bc41ae2010-11-18 19:01:18 +00008284 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00008285 // Decrement of bool is not allowed.
8286 if (!isInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00008287 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00008288 return QualType();
8289 }
8290 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00008291 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00008292 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00008293 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00008294 } else if (ResType->isAnyPointerType()) {
8295 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00008296
Chris Lattner6b0cf142008-11-21 07:05:48 +00008297 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00008298 if (PointeeTy->isVoidType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008299 if (S.getLangOptions().CPlusPlus) {
8300 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00008301 << Op->getSourceRange();
8302 return QualType();
8303 }
8304
8305 // Pointer to void is a GNU extension in C.
John McCall4bc41ae2010-11-18 19:01:18 +00008306 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00008307 } else if (PointeeTy->isFunctionType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008308 if (S.getLangOptions().CPlusPlus) {
8309 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
Douglas Gregorf6cd9282009-01-23 00:36:41 +00008310 << Op->getType() << Op->getSourceRange();
8311 return QualType();
8312 }
8313
John McCall4bc41ae2010-11-18 19:01:18 +00008314 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008315 << ResType << Op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00008316 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
8317 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00008318 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00008319 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00008320 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00008321 // Diagnose bad cases where we step over interface counts.
John McCall4bc41ae2010-11-18 19:01:18 +00008322 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
8323 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
Fariborz Jahanianca75db72009-07-16 17:59:14 +00008324 << PointeeTy << Op->getSourceRange();
8325 return QualType();
8326 }
Eli Friedman090addd2010-01-03 00:20:48 +00008327 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00008328 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00008329 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008330 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008331 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00008332 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00008333 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008334 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8335 isInc, isPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00008336 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
8337 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00008338 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00008339 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor906db8a2009-12-15 16:44:32 +00008340 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00008341 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00008342 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008343 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00008344 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00008345 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00008346 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00008347 // In C++, a prefix increment is the same type as the operand. Otherwise
8348 // (in C or with postfix), the increment is the unqualified type of the
8349 // operand.
John McCall4bc41ae2010-11-18 19:01:18 +00008350 if (isPrefix && S.getLangOptions().CPlusPlus) {
8351 VK = VK_LValue;
8352 return ResType;
8353 } else {
8354 VK = VK_RValue;
8355 return ResType.getUnqualifiedType();
8356 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00008357}
8358
John Wiegley01296292011-04-08 18:41:53 +00008359ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
John McCall34376a62010-12-04 03:47:34 +00008360 assert(E->getValueKind() == VK_LValue &&
8361 E->getObjectKind() == OK_ObjCProperty);
8362 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
8363
Douglas Gregor33823722011-06-11 01:09:30 +00008364 QualType T = E->getType();
8365 QualType ReceiverType;
8366 if (PRE->isObjectReceiver())
8367 ReceiverType = PRE->getBase()->getType();
8368 else if (PRE->isSuperReceiver())
8369 ReceiverType = PRE->getSuperReceiverType();
8370 else
8371 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
8372
John McCall34376a62010-12-04 03:47:34 +00008373 ExprValueKind VK = VK_RValue;
8374 if (PRE->isImplicitProperty()) {
Douglas Gregor33823722011-06-11 01:09:30 +00008375 if (ObjCMethodDecl *GetterMethod =
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00008376 PRE->getImplicitPropertyGetter()) {
Douglas Gregor33823722011-06-11 01:09:30 +00008377 T = getMessageSendResultType(ReceiverType, GetterMethod,
8378 PRE->isClassReceiver(),
8379 PRE->isSuperReceiver());
8380 VK = Expr::getValueKindForType(GetterMethod->getResultType());
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00008381 }
8382 else {
8383 Diag(PRE->getLocation(), diag::err_getter_not_found)
8384 << PRE->getBase()->getType();
8385 }
John McCall34376a62010-12-04 03:47:34 +00008386 }
Douglas Gregor33823722011-06-11 01:09:30 +00008387
8388 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
John McCall34376a62010-12-04 03:47:34 +00008389 E, 0, VK);
John McCall4f26cd82010-12-10 01:49:45 +00008390
8391 ExprResult Result = MaybeBindToTemporary(E);
8392 if (!Result.isInvalid())
8393 E = Result.take();
John Wiegley01296292011-04-08 18:41:53 +00008394
8395 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00008396}
8397
John Wiegley01296292011-04-08 18:41:53 +00008398void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType &LHSTy) {
8399 assert(LHS.get()->getValueKind() == VK_LValue &&
8400 LHS.get()->getObjectKind() == OK_ObjCProperty);
8401 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
John McCall34376a62010-12-04 03:47:34 +00008402
John Wiegley01296292011-04-08 18:41:53 +00008403 if (PropRef->isImplicitProperty()) {
John McCall34376a62010-12-04 03:47:34 +00008404 // If using property-dot syntax notation for assignment, and there is a
8405 // setter, RHS expression is being passed to the setter argument. So,
8406 // type conversion (and comparison) is RHS to setter's argument type.
John Wiegley01296292011-04-08 18:41:53 +00008407 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
John McCall34376a62010-12-04 03:47:34 +00008408 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
8409 LHSTy = (*P)->getType();
8410
8411 // Otherwise, if the getter returns an l-value, just call that.
8412 } else {
John Wiegley01296292011-04-08 18:41:53 +00008413 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
John McCall34376a62010-12-04 03:47:34 +00008414 ExprValueKind VK = Expr::getValueKindForType(Result);
8415 if (VK == VK_LValue) {
John Wiegley01296292011-04-08 18:41:53 +00008416 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
8417 CK_GetObjCProperty, LHS.take(), 0, VK);
John McCall34376a62010-12-04 03:47:34 +00008418 return;
John McCallb7bd14f2010-12-02 01:19:52 +00008419 }
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008420 }
John McCall34376a62010-12-04 03:47:34 +00008421 }
8422
8423 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008424 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008425 InitializedEntity::InitializeParameter(Context, LHSTy);
John Wiegley01296292011-04-08 18:41:53 +00008426 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008427 if (!ArgE.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00008428 RHS = ArgE;
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00008429 }
8430}
8431
8432
Anders Carlsson806700f2008-02-01 07:15:58 +00008433/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00008434/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008435/// where the declaration is needed for type checking. We only need to
8436/// handle cases when the expression references a function designator
8437/// or is an lvalue. Here are some examples:
8438/// - &(x) => x
8439/// - &*****f => f for f a function designator.
8440/// - &s.xx => s
8441/// - &s.zz[1].yy -> s, if zz is an array
8442/// - *(x + 1) -> x, if x is an array
8443/// - &"123"[2] -> 0
8444/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00008445static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008446 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00008447 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008448 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00008449 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00008450 // If this is an arrow operator, the address is an offset from
8451 // the base's value, so the object the base refers to is
8452 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008453 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00008454 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00008455 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008456 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00008457 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00008458 // FIXME: This code shouldn't be necessary! We should catch the implicit
8459 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00008460 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8461 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8462 if (ICE->getSubExpr()->getType()->isArrayType())
8463 return getPrimaryDecl(ICE->getSubExpr());
8464 }
8465 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00008466 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008467 case Stmt::UnaryOperatorClass: {
8468 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008469
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008470 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008471 case UO_Real:
8472 case UO_Imag:
8473 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00008474 return getPrimaryDecl(UO->getSubExpr());
8475 default:
8476 return 0;
8477 }
8478 }
Steve Naroff47500512007-04-19 23:00:49 +00008479 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008480 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00008481 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00008482 // If the result of an implicit cast is an l-value, we care about
8483 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00008484 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00008485 default:
8486 return 0;
8487 }
8488}
8489
8490/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00008491/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00008492/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008493/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00008494/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008495/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00008496/// we allow the '&' but retain the overloaded-function type.
John McCall4bc41ae2010-11-18 19:01:18 +00008497static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
8498 SourceLocation OpLoc) {
John McCall8d08b9b2010-08-27 09:08:28 +00008499 if (OrigOp->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008500 return S.Context.DependentTy;
8501 if (OrigOp->getType() == S.Context.OverloadTy)
8502 return S.Context.OverloadTy;
John McCall2979fe02011-04-12 00:42:48 +00008503 if (OrigOp->getType() == S.Context.UnknownAnyTy)
8504 return S.Context.UnknownAnyTy;
John McCall0009fcc2011-04-26 20:42:42 +00008505 if (OrigOp->getType() == S.Context.BoundMemberTy) {
8506 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8507 << OrigOp->getSourceRange();
8508 return QualType();
8509 }
John McCall8d08b9b2010-08-27 09:08:28 +00008510
John McCall2979fe02011-04-12 00:42:48 +00008511 assert(!OrigOp->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00008512
John McCall8d08b9b2010-08-27 09:08:28 +00008513 // Make sure to ignore parentheses in subsequent checks
8514 Expr *op = OrigOp->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00008515
John McCall4bc41ae2010-11-18 19:01:18 +00008516 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00008517 // Implement C99-only parts of addressof rules.
8518 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00008519 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00008520 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8521 // (assuming the deref expression is valid).
8522 return uOp->getSubExpr()->getType();
8523 }
8524 // Technically, there should be a check for array subscript
8525 // expressions here, but the result of one is always an lvalue anyway.
8526 }
John McCallf3a88602011-02-03 08:15:49 +00008527 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00008528 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00008529
Fariborz Jahanian071caef2011-03-26 19:48:30 +00008530 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00008531 bool sfinae = S.isSFINAEContext();
8532 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8533 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008534 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00008535 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00008536 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00008537 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008538 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00008539 } else if (lval == Expr::LV_MemberFunction) {
8540 // If it's an instance method, make a member pointer.
8541 // The expression must have exactly the form &A::foo.
8542
8543 // If the underlying expression isn't a decl ref, give up.
8544 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008545 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008546 << OrigOp->getSourceRange();
8547 return QualType();
8548 }
8549 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8550 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8551
8552 // The id-expression was parenthesized.
8553 if (OrigOp != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00008554 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008555 << OrigOp->getSourceRange();
8556
8557 // The method was named without a qualifier.
8558 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008559 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00008560 << op->getSourceRange();
8561 }
8562
John McCall4bc41ae2010-11-18 19:01:18 +00008563 return S.Context.getMemberPointerType(op->getType(),
8564 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00008565 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00008566 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008567 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00008568 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00008569 // FIXME: emit more specific diag...
John McCall4bc41ae2010-11-18 19:01:18 +00008570 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
Chris Lattnerf490e152008-11-19 05:27:50 +00008571 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00008572 return QualType();
8573 }
John McCall086a4642010-11-24 05:12:34 +00008574 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00008575 // The operand cannot be a bit-field
John McCall4bc41ae2010-11-18 19:01:18 +00008576 S.Diag(OpLoc, diag::err_typecheck_address_of)
Eli Friedman3a1e6922009-04-20 08:23:18 +00008577 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00008578 return QualType();
John McCall086a4642010-11-24 05:12:34 +00008579 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00008580 // The operand cannot be an element of a vector
John McCall4bc41ae2010-11-18 19:01:18 +00008581 S.Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00008582 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008583 return QualType();
John McCall086a4642010-11-24 05:12:34 +00008584 } else if (op->getObjectKind() == OK_ObjCProperty) {
Fariborz Jahanian385db802009-07-07 18:50:52 +00008585 // cannot take address of a property expression.
John McCall4bc41ae2010-11-18 19:01:18 +00008586 S.Diag(OpLoc, diag::err_typecheck_address_of)
Fariborz Jahanian385db802009-07-07 18:50:52 +00008587 << "property expression" << op->getSourceRange();
8588 return QualType();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00008589 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00008590 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00008591 // with the register storage-class specifier.
8592 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00008593 // in C++ it is not error to take address of a register
8594 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00008595 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00008596 !S.getLangOptions().CPlusPlus) {
8597 S.Diag(OpLoc, diag::err_typecheck_address_of)
Chris Lattner29e812b2008-11-20 06:06:08 +00008598 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00008599 return QualType();
8600 }
John McCalld14a8642009-11-21 08:51:07 +00008601 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00008602 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00008603 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00008604 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008605 // Could be a pointer to member, though, if there is an explicit
8606 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00008607 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008608 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008609 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00008610 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008611 S.Diag(OpLoc,
8612 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00008613 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00008614 return QualType();
8615 }
Mike Stump11289f42009-09-09 15:08:12 +00008616
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00008617 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8618 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00008619 return S.Context.getMemberPointerType(op->getType(),
8620 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00008621 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00008622 }
Anders Carlsson5b535762009-05-16 21:43:42 +00008623 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00008624 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00008625 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008626
Eli Friedmance7f9002009-05-16 23:27:50 +00008627 if (lval == Expr::LV_IncompleteVoidType) {
8628 // Taking the address of a void variable is technically illegal, but we
8629 // allow it in cases which are otherwise valid.
8630 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00008631 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00008632 }
8633
Steve Naroff47500512007-04-19 23:00:49 +00008634 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00008635 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00008636 return S.Context.getObjCObjectPointerType(op->getType());
8637 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00008638}
8639
Chris Lattner9156f1b2010-07-05 19:17:26 +00008640/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00008641static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8642 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008643 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00008644 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008645
John Wiegley01296292011-04-08 18:41:53 +00008646 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8647 if (ConvResult.isInvalid())
8648 return QualType();
8649 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00008650 QualType OpTy = Op->getType();
8651 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00008652
8653 if (isa<CXXReinterpretCastExpr>(Op)) {
8654 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8655 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8656 Op->getSourceRange());
8657 }
8658
Chris Lattner9156f1b2010-07-05 19:17:26 +00008659 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8660 // is an incomplete type or void. It would be possible to warn about
8661 // dereferencing a void pointer, but it's completely well-defined, and such a
8662 // warning is unlikely to catch any mistakes.
8663 if (const PointerType *PT = OpTy->getAs<PointerType>())
8664 Result = PT->getPointeeType();
8665 else if (const ObjCObjectPointerType *OPT =
8666 OpTy->getAs<ObjCObjectPointerType>())
8667 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00008668 else {
John McCall3aef3d82011-04-10 19:13:55 +00008669 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00008670 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00008671 if (PR.take() != Op)
8672 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00008673 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008674
Chris Lattner9156f1b2010-07-05 19:17:26 +00008675 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00008676 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00008677 << OpTy << Op->getSourceRange();
8678 return QualType();
8679 }
John McCall4bc41ae2010-11-18 19:01:18 +00008680
8681 // Dereferences are usually l-values...
8682 VK = VK_LValue;
8683
8684 // ...except that certain expressions are never l-values in C.
8685 if (!S.getLangOptions().CPlusPlus &&
8686 IsCForbiddenLValueType(S.Context, Result))
8687 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00008688
8689 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00008690}
Steve Naroff218bc2b2007-05-04 21:54:46 +00008691
John McCalle3027922010-08-25 11:45:40 +00008692static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00008693 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008694 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008695 switch (Kind) {
8696 default: assert(0 && "Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00008697 case tok::periodstar: Opc = BO_PtrMemD; break;
8698 case tok::arrowstar: Opc = BO_PtrMemI; break;
8699 case tok::star: Opc = BO_Mul; break;
8700 case tok::slash: Opc = BO_Div; break;
8701 case tok::percent: Opc = BO_Rem; break;
8702 case tok::plus: Opc = BO_Add; break;
8703 case tok::minus: Opc = BO_Sub; break;
8704 case tok::lessless: Opc = BO_Shl; break;
8705 case tok::greatergreater: Opc = BO_Shr; break;
8706 case tok::lessequal: Opc = BO_LE; break;
8707 case tok::less: Opc = BO_LT; break;
8708 case tok::greaterequal: Opc = BO_GE; break;
8709 case tok::greater: Opc = BO_GT; break;
8710 case tok::exclaimequal: Opc = BO_NE; break;
8711 case tok::equalequal: Opc = BO_EQ; break;
8712 case tok::amp: Opc = BO_And; break;
8713 case tok::caret: Opc = BO_Xor; break;
8714 case tok::pipe: Opc = BO_Or; break;
8715 case tok::ampamp: Opc = BO_LAnd; break;
8716 case tok::pipepipe: Opc = BO_LOr; break;
8717 case tok::equal: Opc = BO_Assign; break;
8718 case tok::starequal: Opc = BO_MulAssign; break;
8719 case tok::slashequal: Opc = BO_DivAssign; break;
8720 case tok::percentequal: Opc = BO_RemAssign; break;
8721 case tok::plusequal: Opc = BO_AddAssign; break;
8722 case tok::minusequal: Opc = BO_SubAssign; break;
8723 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8724 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8725 case tok::ampequal: Opc = BO_AndAssign; break;
8726 case tok::caretequal: Opc = BO_XorAssign; break;
8727 case tok::pipeequal: Opc = BO_OrAssign; break;
8728 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008729 }
8730 return Opc;
8731}
8732
John McCalle3027922010-08-25 11:45:40 +00008733static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00008734 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008735 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00008736 switch (Kind) {
8737 default: assert(0 && "Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00008738 case tok::plusplus: Opc = UO_PreInc; break;
8739 case tok::minusminus: Opc = UO_PreDec; break;
8740 case tok::amp: Opc = UO_AddrOf; break;
8741 case tok::star: Opc = UO_Deref; break;
8742 case tok::plus: Opc = UO_Plus; break;
8743 case tok::minus: Opc = UO_Minus; break;
8744 case tok::tilde: Opc = UO_Not; break;
8745 case tok::exclaim: Opc = UO_LNot; break;
8746 case tok::kw___real: Opc = UO_Real; break;
8747 case tok::kw___imag: Opc = UO_Imag; break;
8748 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00008749 }
8750 return Opc;
8751}
8752
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008753/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8754/// This warning is only emitted for builtin assignment operations. It is also
8755/// suppressed in the event of macro expansions.
8756static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
8757 SourceLocation OpLoc) {
8758 if (!S.ActiveTemplateInstantiations.empty())
8759 return;
8760 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8761 return;
8762 lhs = lhs->IgnoreParenImpCasts();
8763 rhs = rhs->IgnoreParenImpCasts();
8764 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
8765 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
8766 if (!LeftDeclRef || !RightDeclRef ||
8767 LeftDeclRef->getLocation().isMacroID() ||
8768 RightDeclRef->getLocation().isMacroID())
8769 return;
8770 const ValueDecl *LeftDecl =
8771 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
8772 const ValueDecl *RightDecl =
8773 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
8774 if (LeftDecl != RightDecl)
8775 return;
8776 if (LeftDecl->getType().isVolatileQualified())
8777 return;
8778 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
8779 if (RefTy->getPointeeType().isVolatileQualified())
8780 return;
8781
8782 S.Diag(OpLoc, diag::warn_self_assignment)
8783 << LeftDeclRef->getType()
8784 << lhs->getSourceRange() << rhs->getSourceRange();
8785}
8786
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008787/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8788/// operator @p Opc at location @c TokLoc. This routine only supports
8789/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00008790ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008791 BinaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008792 Expr *lhsExpr, Expr *rhsExpr) {
8793 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008794 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008795 // The following two variables are used for compound assignment operators
8796 QualType CompLHSTy; // Type of LHS after promotions for computation
8797 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00008798 ExprValueKind VK = VK_RValue;
8799 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008800
Douglas Gregor1beec452011-03-12 01:48:56 +00008801 // Check if a 'foo<int>' involved in a binary op, identifies a single
8802 // function unambiguously (i.e. an lvalue ala 13.4)
8803 // But since an assignment can trigger target based overload, exclude it in
8804 // our blind search. i.e:
8805 // template<class T> void f(); template<class T, class U> void f(U);
8806 // f<int> == 0; // resolve f<int> blindly
8807 // void (*p)(int); p = f<int>; // resolve f<int> using target
8808 if (Opc != BO_Assign) {
John McCall3aef3d82011-04-10 19:13:55 +00008809 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get());
John McCall31996342011-04-07 08:22:57 +00008810 if (!resolvedLHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008811 lhs = move(resolvedLHS);
John McCall31996342011-04-07 08:22:57 +00008812
John McCall3aef3d82011-04-10 19:13:55 +00008813 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get());
John McCall31996342011-04-07 08:22:57 +00008814 if (!resolvedRHS.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008815 rhs = move(resolvedRHS);
Douglas Gregor1beec452011-03-12 01:48:56 +00008816 }
8817
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008818 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008819 case BO_Assign:
John Wiegley01296292011-04-08 18:41:53 +00008820 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00008821 if (getLangOptions().CPlusPlus &&
John Wiegley01296292011-04-08 18:41:53 +00008822 lhs.get()->getObjectKind() != OK_ObjCProperty) {
8823 VK = lhs.get()->getValueKind();
8824 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008825 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008826 if (!ResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00008827 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008828 break;
John McCalle3027922010-08-25 11:45:40 +00008829 case BO_PtrMemD:
8830 case BO_PtrMemI:
John McCall7decc9e2010-11-18 06:31:45 +00008831 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008832 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00008833 break;
John McCalle3027922010-08-25 11:45:40 +00008834 case BO_Mul:
8835 case BO_Div:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008836 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00008837 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008838 break;
John McCalle3027922010-08-25 11:45:40 +00008839 case BO_Rem:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008840 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
8841 break;
John McCalle3027922010-08-25 11:45:40 +00008842 case BO_Add:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008843 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
8844 break;
John McCalle3027922010-08-25 11:45:40 +00008845 case BO_Sub:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008846 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
8847 break;
John McCalle3027922010-08-25 11:45:40 +00008848 case BO_Shl:
8849 case BO_Shr:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008850 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008851 break;
John McCalle3027922010-08-25 11:45:40 +00008852 case BO_LE:
8853 case BO_LT:
8854 case BO_GE:
8855 case BO_GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008856 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008857 break;
John McCalle3027922010-08-25 11:45:40 +00008858 case BO_EQ:
8859 case BO_NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00008860 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008861 break;
John McCalle3027922010-08-25 11:45:40 +00008862 case BO_And:
8863 case BO_Xor:
8864 case BO_Or:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008865 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
8866 break;
John McCalle3027922010-08-25 11:45:40 +00008867 case BO_LAnd:
8868 case BO_LOr:
Chris Lattner8406c512010-07-13 19:41:32 +00008869 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008870 break;
John McCalle3027922010-08-25 11:45:40 +00008871 case BO_MulAssign:
8872 case BO_DivAssign:
Chris Lattnerfaa54172010-01-12 21:23:57 +00008873 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00008874 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008875 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008876 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8877 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008878 break;
John McCalle3027922010-08-25 11:45:40 +00008879 case BO_RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008880 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
8881 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008882 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8883 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008884 break;
John McCalle3027922010-08-25 11:45:40 +00008885 case BO_AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008886 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00008887 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8888 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008889 break;
John McCalle3027922010-08-25 11:45:40 +00008890 case BO_SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008891 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
John Wiegley01296292011-04-08 18:41:53 +00008892 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8893 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008894 break;
John McCalle3027922010-08-25 11:45:40 +00008895 case BO_ShlAssign:
8896 case BO_ShrAssign:
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00008897 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008898 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008899 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8900 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008901 break;
John McCalle3027922010-08-25 11:45:40 +00008902 case BO_AndAssign:
8903 case BO_XorAssign:
8904 case BO_OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008905 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
8906 CompLHSTy = CompResultTy;
John Wiegley01296292011-04-08 18:41:53 +00008907 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid())
8908 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008909 break;
John McCalle3027922010-08-25 11:45:40 +00008910 case BO_Comma:
John McCall4bc41ae2010-11-18 19:01:18 +00008911 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00008912 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) {
8913 VK = rhs.get()->getValueKind();
8914 OK = rhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008915 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008916 break;
8917 }
John Wiegley01296292011-04-08 18:41:53 +00008918 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008919 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008920 if (CompResultTy.isNull())
John Wiegley01296292011-04-08 18:41:53 +00008921 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc,
8922 ResultTy, VK, OK, OpLoc));
8923 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008924 VK = VK_LValue;
John Wiegley01296292011-04-08 18:41:53 +00008925 OK = lhs.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008926 }
John Wiegley01296292011-04-08 18:41:53 +00008927 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc,
8928 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00008929 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008930}
8931
Sebastian Redl44615072009-10-27 12:10:02 +00008932/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8933/// operators are mixed in a way that suggests that the programmer forgot that
8934/// comparison operators have higher precedence. The most typical example of
8935/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008936static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00008937 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00008938 typedef BinaryOperator BinOp;
8939 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
8940 rhsopc = static_cast<BinOp::Opcode>(-1);
8941 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008942 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00008943 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00008944 rhsopc = BO->getOpcode();
8945
8946 // Subs are not binary operators.
8947 if (lhsopc == -1 && rhsopc == -1)
8948 return;
8949
8950 // Bitwise operations are sometimes used as eager logical ops.
8951 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00008952 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
8953 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008954 return;
8955
Sebastian Redl44615072009-10-27 12:10:02 +00008956 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008957 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008958 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008959 << SourceRange(lhs->getLocStart(), OpLoc)
8960 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +00008961 Self.PDiag(diag::note_precedence_bitwise_silence)
8962 << BinOp::getOpcodeStr(lhsopc),
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00008963 lhs->getSourceRange(),
8964 Self.PDiag(diag::note_precedence_bitwise_first)
8965 << BinOp::getOpcodeStr(Opc),
8966 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
Sebastian Redl44615072009-10-27 12:10:02 +00008967 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00008968 SuggestParentheses(Self, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00008969 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00008970 << SourceRange(OpLoc, rhs->getLocEnd())
8971 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00008972 Self.PDiag(diag::note_precedence_bitwise_silence)
8973 << BinOp::getOpcodeStr(rhsopc),
8974 rhs->getSourceRange(),
Douglas Gregor89336232010-03-29 23:34:08 +00008975 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregorfa1e36d2010-01-08 00:20:23 +00008976 << BinOp::getOpcodeStr(Opc),
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +00008977 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl43028242009-10-26 15:24:15 +00008978}
8979
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008980/// \brief It accepts a '&&' expr that is inside a '||' one.
8981/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8982/// in parentheses.
8983static void
8984EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008985 BinaryOperator *Bop) {
8986 assert(Bop->getOpcode() == BO_LAnd);
8987 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008988 Self.PDiag(diag::warn_logical_and_in_logical_or)
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008989 << Bop->getSourceRange() << OpLoc,
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008990 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008991 Bop->getSourceRange(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008992 Self.PDiag(0), SourceRange());
8993}
8994
8995/// \brief Returns true if the given expression can be evaluated as a constant
8996/// 'true'.
8997static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8998 bool Res;
8999 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
9000}
9001
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00009002/// \brief Returns true if the given expression can be evaluated as a constant
9003/// 'false'.
9004static bool EvaluatesAsFalse(Sema &S, Expr *E) {
9005 bool Res;
9006 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
9007}
9008
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009009/// \brief Look for '&&' in the left hand of a '||' expr.
9010static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00009011 Expr *OrLHS, Expr *OrRHS) {
9012 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00009013 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00009014 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
9015 if (EvaluatesAsFalse(S, OrRHS))
9016 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009017 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
9018 if (!EvaluatesAsTrue(S, Bop->getLHS()))
9019 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9020 } else if (Bop->getOpcode() == BO_LOr) {
9021 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
9022 // If it's "a || b && 1 || c" we didn't warn earlier for
9023 // "a || b && 1", but warn now.
9024 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
9025 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
9026 }
9027 }
9028 }
9029}
9030
9031/// \brief Look for '&&' in the right hand of a '||' expr.
9032static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00009033 Expr *OrLHS, Expr *OrRHS) {
9034 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009035 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00009036 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
9037 if (EvaluatesAsFalse(S, OrLHS))
9038 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009039 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
9040 if (!EvaluatesAsTrue(S, Bop->getRHS()))
9041 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00009042 }
9043 }
9044}
9045
Sebastian Redl43028242009-10-26 15:24:15 +00009046/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00009047/// precedence.
John McCalle3027922010-08-25 11:45:40 +00009048static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Sebastian Redl43028242009-10-26 15:24:15 +00009049 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00009050 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00009051 if (BinaryOperator::isBitwiseOp(Opc))
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00009052 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
9053
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00009054 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9055 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00009056 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00009057 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
9058 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00009059 }
Sebastian Redl43028242009-10-26 15:24:15 +00009060}
9061
Steve Naroff218bc2b2007-05-04 21:54:46 +00009062// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00009063ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00009064 tok::TokenKind Kind,
9065 Expr *lhs, Expr *rhs) {
9066 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Steve Naroff83895f72007-09-16 03:34:24 +00009067 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
9068 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00009069
Sebastian Redl43028242009-10-26 15:24:15 +00009070 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
9071 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
9072
Douglas Gregor5287f092009-11-05 00:51:44 +00009073 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
9074}
9075
John McCalldadc5752010-08-24 06:29:42 +00009076ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00009077 BinaryOperatorKind Opc,
9078 Expr *lhs, Expr *rhs) {
John McCall622114c2010-12-06 05:26:58 +00009079 if (getLangOptions().CPlusPlus) {
9080 bool UseBuiltinOperator;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009081
John McCall622114c2010-12-06 05:26:58 +00009082 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
9083 UseBuiltinOperator = false;
9084 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
9085 UseBuiltinOperator = true;
9086 } else {
9087 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
9088 !rhs->getType()->isOverloadableType();
9089 }
9090
9091 if (!UseBuiltinOperator) {
9092 // Find all of the overloaded operators visible from this
9093 // point. We perform both an operator-name lookup from the local
9094 // scope and an argument-dependent lookup based on the types of
9095 // the arguments.
9096 UnresolvedSet<16> Functions;
9097 OverloadedOperatorKind OverOp
9098 = BinaryOperator::getOverloadedOperator(Opc);
9099 if (S && OverOp != OO_None)
9100 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
9101 Functions);
9102
9103 // Build the (potentially-overloaded, potentially-dependent)
9104 // binary operation.
9105 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
9106 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00009107 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009108
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00009109 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00009110 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00009111}
9112
John McCalldadc5752010-08-24 06:29:42 +00009113ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00009114 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00009115 Expr *InputExpr) {
9116 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00009117 ExprValueKind VK = VK_RValue;
9118 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00009119 QualType resultType;
9120 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00009121 case UO_PreInc:
9122 case UO_PreDec:
9123 case UO_PostInc:
9124 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00009125 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00009126 Opc == UO_PreInc ||
9127 Opc == UO_PostInc,
9128 Opc == UO_PreInc ||
9129 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00009130 break;
John McCalle3027922010-08-25 11:45:40 +00009131 case UO_AddrOf:
John Wiegley01296292011-04-08 18:41:53 +00009132 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00009133 break;
John McCall31996342011-04-07 08:22:57 +00009134 case UO_Deref: {
John McCall3aef3d82011-04-10 19:13:55 +00009135 ExprResult resolved = CheckPlaceholderExpr(Input.get());
John McCall31996342011-04-07 08:22:57 +00009136 if (!resolved.isUsable()) return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009137 Input = move(resolved);
9138 Input = DefaultFunctionArrayLvalueConversion(Input.take());
9139 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00009140 break;
John McCall31996342011-04-07 08:22:57 +00009141 }
John McCalle3027922010-08-25 11:45:40 +00009142 case UO_Plus:
9143 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00009144 Input = UsualUnaryConversions(Input.take());
9145 if (Input.isInvalid()) return ExprError();
9146 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009147 if (resultType->isDependentType())
9148 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00009149 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9150 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00009151 break;
9152 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
9153 resultType->isEnumeralType())
9154 break;
9155 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00009156 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00009157 resultType->isPointerType())
9158 break;
John McCall36226622010-10-12 02:09:17 +00009159 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00009160 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00009161 if (Input.isInvalid()) return ExprError();
9162 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00009163 }
Douglas Gregord08452f2008-11-19 15:42:04 +00009164
Sebastian Redlc215cfc2009-01-19 00:08:26 +00009165 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00009166 << resultType << Input.get()->getSourceRange());
9167
John McCalle3027922010-08-25 11:45:40 +00009168 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00009169 Input = UsualUnaryConversions(Input.take());
9170 if (Input.isInvalid()) return ExprError();
9171 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009172 if (resultType->isDependentType())
9173 break;
Chris Lattner0d707612008-07-25 23:52:49 +00009174 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9175 if (resultType->isComplexType() || resultType->isComplexIntegerType())
9176 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00009177 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00009178 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00009179 else if (resultType->hasIntegerRepresentation())
9180 break;
9181 else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00009182 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00009183 if (Input.isInvalid()) return ExprError();
9184 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00009185 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00009186 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00009187 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00009188 }
Steve Naroff35d85152007-05-07 00:24:15 +00009189 break;
John Wiegley01296292011-04-08 18:41:53 +00009190
John McCalle3027922010-08-25 11:45:40 +00009191 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00009192 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00009193 Input = DefaultFunctionArrayLvalueConversion(Input.take());
9194 if (Input.isInvalid()) return ExprError();
9195 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009196 if (resultType->isDependentType())
9197 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00009198 if (resultType->isScalarType()) {
9199 // C99 6.5.3.3p1: ok, fallthrough;
9200 if (Context.getLangOptions().CPlusPlus) {
9201 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9202 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00009203 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
9204 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00009205 }
John McCall36226622010-10-12 02:09:17 +00009206 } else if (resultType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00009207 Input = CheckPlaceholderExpr(Input.take());
John Wiegley01296292011-04-08 18:41:53 +00009208 if (Input.isInvalid()) return ExprError();
9209 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
John McCall36226622010-10-12 02:09:17 +00009210 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00009211 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00009212 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00009213 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00009214
Chris Lattnerbe31ed82007-06-02 19:11:33 +00009215 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00009216 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00009217 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00009218 break;
John McCalle3027922010-08-25 11:45:40 +00009219 case UO_Real:
9220 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00009221 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
John McCall7decc9e2010-11-18 06:31:45 +00009222 // _Real and _Imag map ordinary l-values into ordinary l-values.
John Wiegley01296292011-04-08 18:41:53 +00009223 if (Input.isInvalid()) return ExprError();
9224 if (Input.get()->getValueKind() != VK_RValue &&
9225 Input.get()->getObjectKind() == OK_Ordinary)
9226 VK = Input.get()->getValueKind();
Chris Lattner30b5dd02007-08-24 21:16:53 +00009227 break;
John McCalle3027922010-08-25 11:45:40 +00009228 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00009229 resultType = Input.get()->getType();
9230 VK = Input.get()->getValueKind();
9231 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00009232 break;
Steve Naroff35d85152007-05-07 00:24:15 +00009233 }
John Wiegley01296292011-04-08 18:41:53 +00009234 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00009235 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00009236
John Wiegley01296292011-04-08 18:41:53 +00009237 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00009238 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00009239}
Chris Lattnereefa10e2007-05-28 06:56:27 +00009240
John McCalldadc5752010-08-24 06:29:42 +00009241ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00009242 UnaryOperatorKind Opc,
9243 Expr *Input) {
Anders Carlsson461a2c02009-11-14 21:26:41 +00009244 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Eli Friedman8ed2bac2010-09-05 23:15:52 +00009245 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009246 // Find all of the overloaded operators visible from this
9247 // point. We perform both an operator-name lookup from the local
9248 // scope and an argument-dependent lookup based on the types of
9249 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00009250 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00009251 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00009252 if (S && OverOp != OO_None)
9253 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9254 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009255
John McCallb268a282010-08-23 23:25:46 +00009256 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009257 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009258
John McCallb268a282010-08-23 23:25:46 +00009259 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009260}
9261
Douglas Gregor5287f092009-11-05 00:51:44 +00009262// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00009263ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00009264 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00009265 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00009266}
9267
Steve Naroff66356bd2007-09-16 14:56:35 +00009268/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00009269ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00009270 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00009271 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00009272 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00009273 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009274 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00009275}
9276
John McCalldadc5752010-08-24 06:29:42 +00009277ExprResult
John McCallb268a282010-08-23 23:25:46 +00009278Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009279 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00009280 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9281 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9282
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00009283 bool isFileScope
9284 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00009285 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009286 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00009287
Chris Lattner366727f2007-07-24 16:58:17 +00009288 // FIXME: there are a variety of strange constraints to enforce here, for
9289 // example, it is not possible to goto into a stmt expression apparently.
9290 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00009291
Chris Lattner366727f2007-07-24 16:58:17 +00009292 // If there are sub stmts in the compound stmt, take the type of the last one
9293 // as the type of the stmtexpr.
9294 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009295 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00009296 if (!Compound->body_empty()) {
9297 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009298 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00009299 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009300 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9301 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00009302 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009303 }
John Wiegley01296292011-04-08 18:41:53 +00009304 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00009305 // Do function/array conversion on the last expression, but not
9306 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00009307 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9308 if (LastExpr.isInvalid())
9309 return ExprError();
9310 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00009311
John Wiegley01296292011-04-08 18:41:53 +00009312 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9313 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009314 InitializedEntity::InitializeResult(LPLoc,
9315 Ty,
9316 false),
9317 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00009318 LastExpr);
9319 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009320 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009321 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009322 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00009323 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009324 else
John Wiegley01296292011-04-08 18:41:53 +00009325 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009326 StmtExprMayBindToTemp = true;
9327 }
9328 }
9329 }
Chris Lattner944d3062008-07-26 19:51:01 +00009330 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009331
Eli Friedmanba961a92009-03-23 00:24:07 +00009332 // FIXME: Check that expression type is complete/non-abstract; statement
9333 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00009334 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9335 if (StmtExprMayBindToTemp)
9336 return MaybeBindToTemporary(ResStmtExpr);
9337 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00009338}
Steve Naroff78864672007-08-01 22:05:33 +00009339
John McCalldadc5752010-08-24 06:29:42 +00009340ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009341 TypeSourceInfo *TInfo,
9342 OffsetOfComponent *CompPtr,
9343 unsigned NumComponents,
9344 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00009345 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009346 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00009347 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00009348
Chris Lattnerf17bd422007-08-30 17:45:32 +00009349 // We must have at least one component that refers to the type, and the first
9350 // one is known to be a field designator. Verify that the ArgTy represents
9351 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009352 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00009353 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9354 << ArgTy << TypeRange);
9355
9356 // Type must be complete per C99 7.17p3 because a declaring a variable
9357 // with an incomplete type would be ill-formed.
9358 if (!Dependent
9359 && RequireCompleteType(BuiltinLoc, ArgTy,
9360 PDiag(diag::err_offsetof_incomplete_type)
9361 << TypeRange))
9362 return ExprError();
9363
Chris Lattner78502cf2007-08-31 21:49:13 +00009364 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9365 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00009366 // FIXME: This diagnostic isn't actually visible because the location is in
9367 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00009368 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00009369 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9370 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00009371
9372 bool DidWarnAboutNonPOD = false;
9373 QualType CurrentType = ArgTy;
9374 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9375 llvm::SmallVector<OffsetOfNode, 4> Comps;
9376 llvm::SmallVector<Expr*, 4> Exprs;
9377 for (unsigned i = 0; i != NumComponents; ++i) {
9378 const OffsetOfComponent &OC = CompPtr[i];
9379 if (OC.isBrackets) {
9380 // Offset of an array sub-field. TODO: Should we allow vector elements?
9381 if (!CurrentType->isDependentType()) {
9382 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9383 if(!AT)
9384 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9385 << CurrentType);
9386 CurrentType = AT->getElementType();
9387 } else
9388 CurrentType = Context.DependentTy;
9389
9390 // The expression must be an integral expression.
9391 // FIXME: An integral constant expression?
9392 Expr *Idx = static_cast<Expr*>(OC.U.E);
9393 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9394 !Idx->getType()->isIntegerType())
9395 return ExprError(Diag(Idx->getLocStart(),
9396 diag::err_typecheck_subscript_not_integer)
9397 << Idx->getSourceRange());
9398
9399 // Record this array index.
9400 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9401 Exprs.push_back(Idx);
9402 continue;
9403 }
9404
9405 // Offset of a field.
9406 if (CurrentType->isDependentType()) {
9407 // We have the offset of a field, but we can't look into the dependent
9408 // type. Just record the identifier of the field.
9409 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9410 CurrentType = Context.DependentTy;
9411 continue;
9412 }
9413
9414 // We need to have a complete type to look into.
9415 if (RequireCompleteType(OC.LocStart, CurrentType,
9416 diag::err_offsetof_incomplete_type))
9417 return ExprError();
9418
9419 // Look for the designated field.
9420 const RecordType *RC = CurrentType->getAs<RecordType>();
9421 if (!RC)
9422 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9423 << CurrentType);
9424 RecordDecl *RD = RC->getDecl();
9425
9426 // C++ [lib.support.types]p5:
9427 // The macro offsetof accepts a restricted set of type arguments in this
9428 // International Standard. type shall be a POD structure or a POD union
9429 // (clause 9).
9430 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9431 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00009432 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00009433 PDiag(diag::warn_offsetof_non_pod_type)
9434 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9435 << CurrentType))
9436 DidWarnAboutNonPOD = true;
9437 }
9438
9439 // Look for the field.
9440 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9441 LookupQualifiedName(R, RD);
9442 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009443 IndirectFieldDecl *IndirectMemberDecl = 0;
9444 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00009445 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00009446 MemberDecl = IndirectMemberDecl->getAnonField();
9447 }
9448
Douglas Gregor882211c2010-04-28 22:16:22 +00009449 if (!MemberDecl)
9450 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9451 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9452 OC.LocEnd));
9453
Douglas Gregor10982ea2010-04-28 22:36:06 +00009454 // C99 7.17p3:
9455 // (If the specified member is a bit-field, the behavior is undefined.)
9456 //
9457 // We diagnose this as an error.
9458 if (MemberDecl->getBitWidth()) {
9459 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9460 << MemberDecl->getDeclName()
9461 << SourceRange(BuiltinLoc, RParenLoc);
9462 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9463 return ExprError();
9464 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009465
9466 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00009467 if (IndirectMemberDecl)
9468 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009469
Douglas Gregord1702062010-04-29 00:18:15 +00009470 // If the member was found in a base class, introduce OffsetOfNodes for
9471 // the base class indirections.
9472 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9473 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009474 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00009475 CXXBasePath &Path = Paths.front();
9476 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9477 B != BEnd; ++B)
9478 Comps.push_back(OffsetOfNode(B->Base));
9479 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009480
Francois Pichet783dd6e2010-11-21 06:08:52 +00009481 if (IndirectMemberDecl) {
9482 for (IndirectFieldDecl::chain_iterator FI =
9483 IndirectMemberDecl->chain_begin(),
9484 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9485 assert(isa<FieldDecl>(*FI));
9486 Comps.push_back(OffsetOfNode(OC.LocStart,
9487 cast<FieldDecl>(*FI), OC.LocEnd));
9488 }
9489 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00009490 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00009491
Douglas Gregor882211c2010-04-28 22:16:22 +00009492 CurrentType = MemberDecl->getType().getNonReferenceType();
9493 }
9494
9495 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9496 TInfo, Comps.data(), Comps.size(),
9497 Exprs.data(), Exprs.size(), RParenLoc));
9498}
Mike Stump4e1f26a2009-02-19 03:04:26 +00009499
John McCalldadc5752010-08-24 06:29:42 +00009500ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00009501 SourceLocation BuiltinLoc,
9502 SourceLocation TypeLoc,
9503 ParsedType argty,
9504 OffsetOfComponent *CompPtr,
9505 unsigned NumComponents,
9506 SourceLocation RPLoc) {
9507
Douglas Gregor882211c2010-04-28 22:16:22 +00009508 TypeSourceInfo *ArgTInfo;
9509 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
9510 if (ArgTy.isNull())
9511 return ExprError();
9512
Eli Friedman06dcfd92010-08-05 10:15:45 +00009513 if (!ArgTInfo)
9514 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9515
9516 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9517 RPLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00009518}
9519
9520
John McCalldadc5752010-08-24 06:29:42 +00009521ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009522 Expr *CondExpr,
9523 Expr *LHSExpr, Expr *RHSExpr,
9524 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00009525 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9526
John McCall7decc9e2010-11-18 06:31:45 +00009527 ExprValueKind VK = VK_RValue;
9528 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009529 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00009530 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00009531 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009532 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00009533 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009534 } else {
9535 // The conditional expression is required to be a constant expression.
9536 llvm::APSInt condEval(32);
9537 SourceLocation ExpLoc;
9538 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009539 return ExprError(Diag(ExpLoc,
9540 diag::err_typecheck_choose_expr_requires_constant)
9541 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00009542
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009543 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00009544 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9545
9546 resType = ActiveExpr->getType();
9547 ValueDependent = ActiveExpr->isValueDependent();
9548 VK = ActiveExpr->getValueKind();
9549 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009550 }
9551
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009552 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00009553 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00009554 resType->isDependentType(),
9555 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00009556}
9557
Steve Naroffc540d662008-09-03 18:15:37 +00009558//===----------------------------------------------------------------------===//
9559// Clang Extensions.
9560//===----------------------------------------------------------------------===//
9561
9562/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009563void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009564 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9565 PushBlockScope(BlockScope, Block);
9566 CurContext->addDecl(Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009567 if (BlockScope)
9568 PushDeclContext(BlockScope, Block);
9569 else
9570 CurContext = Block;
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009571}
9572
Mike Stump82f071f2009-02-04 22:31:32 +00009573void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00009574 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00009575 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009576 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009577
John McCall8cb7bdf2010-06-04 23:28:52 +00009578 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00009579 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00009580
John McCall3882ace2011-01-05 12:14:39 +00009581 // GetTypeForDeclarator always produces a function type for a block
9582 // literal signature. Furthermore, it is always a FunctionProtoType
9583 // unless the function was written with a typedef.
9584 assert(T->isFunctionType() &&
9585 "GetTypeForDeclarator made a non-function block signature");
9586
9587 // Look for an explicit signature in that function type.
9588 FunctionProtoTypeLoc ExplicitSignature;
9589
9590 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9591 if (isa<FunctionProtoTypeLoc>(tmp)) {
9592 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9593
9594 // Check whether that explicit signature was synthesized by
9595 // GetTypeForDeclarator. If so, don't save that as part of the
9596 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00009597 if (ExplicitSignature.getLocalRangeBegin() ==
9598 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00009599 // This would be much cheaper if we stored TypeLocs instead of
9600 // TypeSourceInfos.
9601 TypeLoc Result = ExplicitSignature.getResultLoc();
9602 unsigned Size = Result.getFullDataSize();
9603 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9604 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9605
9606 ExplicitSignature = FunctionProtoTypeLoc();
9607 }
John McCalla3ccba02010-06-04 11:21:44 +00009608 }
Mike Stump11289f42009-09-09 15:08:12 +00009609
John McCall3882ace2011-01-05 12:14:39 +00009610 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9611 CurBlock->FunctionType = T;
9612
9613 const FunctionType *Fn = T->getAs<FunctionType>();
9614 QualType RetTy = Fn->getResultType();
9615 bool isVariadic =
9616 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9617
John McCall8e346702010-06-04 19:02:56 +00009618 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00009619
John McCalla3ccba02010-06-04 11:21:44 +00009620 // Don't allow returning a objc interface by value.
9621 if (RetTy->isObjCObjectType()) {
9622 Diag(ParamInfo.getSourceRange().getBegin(),
9623 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9624 return;
9625 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009626
John McCalla3ccba02010-06-04 11:21:44 +00009627 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00009628 // return type. TODO: what should we do with declarators like:
9629 // ^ * { ... }
9630 // If the answer is "apply template argument deduction"....
John McCalla3ccba02010-06-04 11:21:44 +00009631 if (RetTy != Context.DependentTy)
9632 CurBlock->ReturnType = RetTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009633
John McCalla3ccba02010-06-04 11:21:44 +00009634 // Push block parameters from the declarator if we had them.
John McCall8e346702010-06-04 19:02:56 +00009635 llvm::SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00009636 if (ExplicitSignature) {
9637 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9638 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009639 if (Param->getIdentifier() == 0 &&
9640 !Param->isImplicit() &&
9641 !Param->isInvalidDecl() &&
9642 !getLangOptions().CPlusPlus)
9643 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00009644 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009645 }
John McCalla3ccba02010-06-04 11:21:44 +00009646
9647 // Fake up parameter variables if we have a typedef, like
9648 // ^ fntype { ... }
9649 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9650 for (FunctionProtoType::arg_type_iterator
9651 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9652 ParmVarDecl *Param =
9653 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9654 ParamInfo.getSourceRange().getBegin(),
9655 *I);
John McCall8e346702010-06-04 19:02:56 +00009656 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00009657 }
Steve Naroffc540d662008-09-03 18:15:37 +00009658 }
John McCalla3ccba02010-06-04 11:21:44 +00009659
John McCall8e346702010-06-04 19:02:56 +00009660 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00009661 if (!Params.empty()) {
John McCall8e346702010-06-04 19:02:56 +00009662 CurBlock->TheDecl->setParams(Params.data(), Params.size());
Douglas Gregorb524d902010-11-01 18:37:59 +00009663 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9664 CurBlock->TheDecl->param_end(),
9665 /*CheckParameterNames=*/false);
9666 }
9667
John McCalla3ccba02010-06-04 11:21:44 +00009668 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00009669 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00009670
John McCall8e346702010-06-04 19:02:56 +00009671 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
John McCalla3ccba02010-06-04 11:21:44 +00009672 Diag(ParamInfo.getAttributes()->getLoc(),
9673 diag::warn_attribute_sentinel_not_variadic) << 1;
9674 // FIXME: remove the attribute.
9675 }
9676
9677 // Put the parameter variables in scope. We can bail out immediately
9678 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00009679 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00009680 return;
9681
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009682 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00009683 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9684 (*AI)->setOwningFunction(CurBlock->TheDecl);
9685
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009686 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009687 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009688 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00009689
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009690 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009691 }
John McCallf7b2fb52010-01-22 00:28:27 +00009692 }
Steve Naroffc540d662008-09-03 18:15:37 +00009693}
9694
9695/// ActOnBlockError - If there is an error parsing a block, this callback
9696/// is invoked to pop the information about the block from the action impl.
9697void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00009698 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00009699 PopDeclContext();
Douglas Gregor9a28e842010-03-01 23:15:13 +00009700 PopFunctionOrBlockScope();
Steve Naroffc540d662008-09-03 18:15:37 +00009701}
9702
9703/// ActOnBlockStmtExpr - This is called when the body of a block statement
9704/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00009705ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00009706 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00009707 // If blocks are disabled, emit an error.
9708 if (!LangOpts.Blocks)
9709 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00009710
Douglas Gregor9a28e842010-03-01 23:15:13 +00009711 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009712
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009713 PopDeclContext();
9714
Steve Naroffc540d662008-09-03 18:15:37 +00009715 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00009716 if (!BSI->ReturnType.isNull())
9717 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009718
Mike Stump3bf1ab42009-07-28 22:04:01 +00009719 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00009720 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00009721
John McCallc63de662011-02-02 13:00:07 +00009722 // Set the captured variables on the block.
John McCall351762c2011-02-07 10:33:21 +00009723 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
9724 BSI->CapturesCXXThis);
John McCallc63de662011-02-02 13:00:07 +00009725
John McCall8e346702010-06-04 19:02:56 +00009726 // If the user wrote a function type in some form, try to use that.
9727 if (!BSI->FunctionType.isNull()) {
9728 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9729
9730 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9731 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9732
9733 // Turn protoless block types into nullary block types.
9734 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009735 FunctionProtoType::ExtProtoInfo EPI;
9736 EPI.ExtInfo = Ext;
9737 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009738
9739 // Otherwise, if we don't need to change anything about the function type,
9740 // preserve its sugar structure.
9741 } else if (FTy->getResultType() == RetTy &&
9742 (!NoReturn || FTy->getNoReturnAttr())) {
9743 BlockTy = BSI->FunctionType;
9744
9745 // Otherwise, make the minimal modifications to the function type.
9746 } else {
9747 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009748 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9749 EPI.TypeQuals = 0; // FIXME: silently?
9750 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009751 BlockTy = Context.getFunctionType(RetTy,
9752 FPT->arg_type_begin(),
9753 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009754 EPI);
John McCall8e346702010-06-04 19:02:56 +00009755 }
9756
9757 // If we don't have a function type, just build one from nothing.
9758 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009759 FunctionProtoType::ExtProtoInfo EPI;
Eli Friedmanc5b20b52011-04-09 08:18:08 +00009760 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, false, 0, CC_Default);
John McCalldb40c7f2010-12-14 08:05:40 +00009761 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009762 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009763
John McCall8e346702010-06-04 19:02:56 +00009764 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9765 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009766 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009767
Chris Lattner45542ea2009-04-19 05:28:12 +00009768 // If needed, diagnose invalid gotos and switches in the block.
John McCallaab3e412010-08-25 08:40:02 +00009769 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00009770 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009771
Chris Lattner60f84492011-02-17 23:58:47 +00009772 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009773
John McCallc63de662011-02-02 13:00:07 +00009774 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
John McCall1d570a72010-08-25 05:56:39 +00009775
Ted Kremenek1767a272011-02-23 01:51:48 +00009776 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9777 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009778 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009779}
9780
John McCalldadc5752010-08-24 06:29:42 +00009781ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
John McCallba7bf592010-08-24 05:47:05 +00009782 Expr *expr, ParsedType type,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009783 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009784 TypeSourceInfo *TInfo;
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009785 GetTypeFromParser(type, &TInfo);
John McCallb268a282010-08-23 23:25:46 +00009786 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009787}
9788
John McCalldadc5752010-08-24 06:29:42 +00009789ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009790 Expr *E, TypeSourceInfo *TInfo,
9791 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009792 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009793
Eli Friedman121ba0c2008-08-09 23:32:40 +00009794 // Get the va_list type
9795 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009796 if (VaListType->isArrayType()) {
9797 // Deal with implicit array decay; for example, on x86-64,
9798 // va_list is an array, but it's supposed to decay to
9799 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009800 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009801 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00009802 ExprResult Result = UsualUnaryConversions(E);
9803 if (Result.isInvalid())
9804 return ExprError();
9805 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00009806 } else {
9807 // Otherwise, the va_list argument must be an l-value because
9808 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009809 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009810 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009811 return ExprError();
9812 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009813
Douglas Gregorad3150c2009-05-19 23:10:31 +00009814 if (!E->isTypeDependent() &&
9815 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009816 return ExprError(Diag(E->getLocStart(),
9817 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009818 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009819 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009820
Eli Friedmanba961a92009-03-23 00:24:07 +00009821 // FIXME: Check that type is complete/non-abstract
David Majnemer254a5c02011-06-13 06:37:03 +00009822
9823 if (!TInfo->getType()->isDependentType() && !TInfo->getType()->isPODType())
9824 return ExprError(Diag(TInfo->getTypeLoc().getBeginLoc(),
9825 diag::warn_second_parameter_to_va_arg_not_pod)
9826 << TInfo->getType() << TInfo->getTypeLoc().getSourceRange());
Mike Stump4e1f26a2009-02-19 03:04:26 +00009827
Abramo Bagnara27db2392010-08-10 10:06:15 +00009828 QualType T = TInfo->getType().getNonLValueExprType(Context);
9829 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009830}
9831
John McCalldadc5752010-08-24 06:29:42 +00009832ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009833 // The type of __null will be int or long, depending on the size of
9834 // pointers on the target.
9835 QualType Ty;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009836 unsigned pw = Context.Target.getPointerWidth(0);
9837 if (pw == Context.Target.getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009838 Ty = Context.IntTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009839 else if (pw == Context.Target.getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009840 Ty = Context.LongTy;
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009841 else if (pw == Context.Target.getLongLongWidth())
9842 Ty = Context.LongLongTy;
9843 else {
9844 assert(!"I don't know size of pointer!");
9845 Ty = Context.IntTy;
9846 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009847
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009848 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009849}
9850
Alexis Huntc46382e2010-04-28 23:02:27 +00009851static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009852 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00009853 if (!SemaRef.getLangOptions().ObjC1)
9854 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009855
Anders Carlssonace5d072009-11-10 04:46:30 +00009856 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9857 if (!PT)
9858 return;
9859
9860 // Check if the destination is of type 'id'.
9861 if (!PT->isObjCIdType()) {
9862 // Check if the destination is the 'NSString' interface.
9863 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9864 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9865 return;
9866 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009867
Anders Carlssonace5d072009-11-10 04:46:30 +00009868 // Strip off any parens and casts.
9869 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
9870 if (!SL || SL->isWide())
9871 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009872
Douglas Gregora771f462010-03-31 17:46:05 +00009873 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009874}
9875
Chris Lattner9bad62c2008-01-04 18:04:52 +00009876bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9877 SourceLocation Loc,
9878 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009879 Expr *SrcExpr, AssignmentAction Action,
9880 bool *Complained) {
9881 if (Complained)
9882 *Complained = false;
9883
Chris Lattner9bad62c2008-01-04 18:04:52 +00009884 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00009885 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009886 bool isInvalid = false;
9887 unsigned DiagKind;
Douglas Gregora771f462010-03-31 17:46:05 +00009888 FixItHint Hint;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009889
Chris Lattner9bad62c2008-01-04 18:04:52 +00009890 switch (ConvTy) {
9891 default: assert(0 && "Unknown conversion type");
9892 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009893 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009894 DiagKind = diag::ext_typecheck_convert_pointer_int;
9895 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009896 case IntToPointer:
9897 DiagKind = diag::ext_typecheck_convert_int_pointer;
9898 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009899 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009900 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009901 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00009902 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9903 SrcType->isObjCObjectPointerType();
Chris Lattner9bad62c2008-01-04 18:04:52 +00009904 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009905 case IncompatiblePointerSign:
9906 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9907 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009908 case FunctionVoidPointer:
9909 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9910 break;
John McCall4fff8f62011-02-01 00:10:29 +00009911 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009912 // Perform array-to-pointer decay if necessary.
9913 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9914
John McCall4fff8f62011-02-01 00:10:29 +00009915 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9916 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9917 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9918 DiagKind = diag::err_typecheck_incompatible_address_space;
9919 break;
9920 }
9921
9922 llvm_unreachable("unknown error case for discarding qualifiers!");
9923 // fallthrough
9924 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009925 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009926 // If the qualifiers lost were because we were applying the
9927 // (deprecated) C++ conversion from a string literal to a char*
9928 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9929 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009930 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009931 // bit of refactoring (so that the second argument is an
9932 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009933 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009934 // C++ semantics.
9935 if (getLangOptions().CPlusPlus &&
9936 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9937 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009938 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9939 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009940 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009941 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009942 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009943 case IntToBlockPointer:
9944 DiagKind = diag::err_int_to_block_pointer;
9945 break;
9946 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009947 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009948 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009949 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009950 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009951 // it can give a more specific diagnostic.
9952 DiagKind = diag::warn_incompatible_qualified_id;
9953 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009954 case IncompatibleVectors:
9955 DiagKind = diag::warn_incompatible_vectors;
9956 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009957 case Incompatible:
9958 DiagKind = diag::err_typecheck_convert_incompatible;
9959 isInvalid = true;
9960 break;
9961 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009962
Douglas Gregorc68e1402010-04-09 00:35:39 +00009963 QualType FirstType, SecondType;
9964 switch (Action) {
9965 case AA_Assigning:
9966 case AA_Initializing:
9967 // The destination type comes first.
9968 FirstType = DstType;
9969 SecondType = SrcType;
9970 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009971
Douglas Gregorc68e1402010-04-09 00:35:39 +00009972 case AA_Returning:
9973 case AA_Passing:
9974 case AA_Converting:
9975 case AA_Sending:
9976 case AA_Casting:
9977 // The source type comes first.
9978 FirstType = SrcType;
9979 SecondType = DstType;
9980 break;
9981 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009982
Douglas Gregorc68e1402010-04-09 00:35:39 +00009983 Diag(Loc, DiagKind) << FirstType << SecondType << Action
Anders Carlssonace5d072009-11-10 04:46:30 +00009984 << SrcExpr->getSourceRange() << Hint;
Douglas Gregor33823722011-06-11 01:09:30 +00009985 if (CheckInferredResultType)
9986 EmitRelatedResultTypeNote(SrcExpr);
9987
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009988 if (Complained)
9989 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009990 return isInvalid;
9991}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009992
Chris Lattnerc71d08b2009-04-25 21:59:05 +00009993bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009994 llvm::APSInt ICEResult;
9995 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9996 if (Result)
9997 *Result = ICEResult;
9998 return false;
9999 }
10000
Anders Carlssone54e8a12008-11-30 19:50:32 +000010001 Expr::EvalResult EvalResult;
10002
Mike Stump4e1f26a2009-02-19 03:04:26 +000010003 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +000010004 EvalResult.HasSideEffects) {
10005 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
10006
10007 if (EvalResult.Diag) {
10008 // We only show the note if it's not the usual "invalid subexpression"
10009 // or if it's actually in a subexpression.
10010 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
10011 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
10012 Diag(EvalResult.DiagLoc, EvalResult.Diag);
10013 }
Mike Stump4e1f26a2009-02-19 03:04:26 +000010014
Anders Carlssone54e8a12008-11-30 19:50:32 +000010015 return true;
10016 }
10017
Eli Friedmanbb967cc2009-04-25 22:26:58 +000010018 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
10019 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +000010020
Eli Friedmanbb967cc2009-04-25 22:26:58 +000010021 if (EvalResult.Diag &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +000010022 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
10023 != Diagnostic::Ignored)
Eli Friedmanbb967cc2009-04-25 22:26:58 +000010024 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +000010025
Anders Carlssone54e8a12008-11-30 19:50:32 +000010026 if (Result)
10027 *Result = EvalResult.Val.getInt();
10028 return false;
10029}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010030
Douglas Gregorff790f12009-11-26 00:44:06 +000010031void
Mike Stump11289f42009-09-09 15:08:12 +000010032Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +000010033 ExprEvalContexts.push_back(
10034 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010035}
10036
Mike Stump11289f42009-09-09 15:08:12 +000010037void
Douglas Gregorff790f12009-11-26 00:44:06 +000010038Sema::PopExpressionEvaluationContext() {
10039 // Pop the current expression evaluation context off the stack.
10040 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
10041 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010042
Douglas Gregorfab31f42009-12-12 07:57:52 +000010043 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
10044 if (Rec.PotentiallyReferenced) {
10045 // Mark any remaining declarations in the current position of the stack
10046 // as "referenced". If they were not meant to be referenced, semantic
10047 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010048 for (PotentiallyReferencedDecls::iterator
Douglas Gregorfab31f42009-12-12 07:57:52 +000010049 I = Rec.PotentiallyReferenced->begin(),
10050 IEnd = Rec.PotentiallyReferenced->end();
10051 I != IEnd; ++I)
10052 MarkDeclarationReferenced(I->first, I->second);
10053 }
10054
10055 if (Rec.PotentiallyDiagnosed) {
10056 // Emit any pending diagnostics.
10057 for (PotentiallyEmittedDiagnostics::iterator
10058 I = Rec.PotentiallyDiagnosed->begin(),
10059 IEnd = Rec.PotentiallyDiagnosed->end();
10060 I != IEnd; ++I)
10061 Diag(I->first, I->second);
10062 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010063 }
Douglas Gregorff790f12009-11-26 00:44:06 +000010064
10065 // When are coming out of an unevaluated context, clear out any
10066 // temporaries that we may have created as part of the evaluation of
10067 // the expression in that context: they aren't relevant because they
10068 // will never be constructed.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010069 if (Rec.Context == Unevaluated &&
Douglas Gregorff790f12009-11-26 00:44:06 +000010070 ExprTemporaries.size() > Rec.NumTemporaries)
10071 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
10072 ExprTemporaries.end());
10073
10074 // Destroy the popped expression evaluation record.
10075 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010076}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010077
10078/// \brief Note that the given declaration was referenced in the source code.
10079///
10080/// This routine should be invoke whenever a given declaration is referenced
10081/// in the source code, and where that reference occurred. If this declaration
10082/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
10083/// C99 6.9p3), then the declaration will be marked as used.
10084///
10085/// \param Loc the location where the declaration was referenced.
10086///
10087/// \param D the declaration that has been referenced by the source code.
10088void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
10089 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +000010090
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +000010091 D->setReferenced();
10092
Douglas Gregorebada0772010-06-17 23:14:26 +000010093 if (D->isUsed(false))
Douglas Gregor77b50e12009-06-22 23:06:13 +000010094 return;
Mike Stump11289f42009-09-09 15:08:12 +000010095
Douglas Gregor3beaf9b2009-10-08 21:35:42 +000010096 // Mark a parameter or variable declaration "used", regardless of whether we're in a
10097 // template or not. The reason for this is that unevaluated expressions
10098 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
10099 // -Wunused-parameters)
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010100 if (isa<ParmVarDecl>(D) ||
Douglas Gregorfd27fed2010-04-07 20:29:57 +000010101 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
Anders Carlsson73067a02010-10-22 23:37:08 +000010102 D->setUsed();
Douglas Gregorfd27fed2010-04-07 20:29:57 +000010103 return;
10104 }
Alexis Huntc46382e2010-04-28 23:02:27 +000010105
Douglas Gregorfd27fed2010-04-07 20:29:57 +000010106 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
10107 return;
Alexis Huntc46382e2010-04-28 23:02:27 +000010108
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010109 // Do not mark anything as "used" within a dependent context; wait for
10110 // an instantiation.
10111 if (CurContext->isDependentContext())
10112 return;
Mike Stump11289f42009-09-09 15:08:12 +000010113
Douglas Gregorff790f12009-11-26 00:44:06 +000010114 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010115 case Unevaluated:
10116 // We are in an expression that is not potentially evaluated; do nothing.
10117 return;
Mike Stump11289f42009-09-09 15:08:12 +000010118
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010119 case PotentiallyEvaluated:
10120 // We are in a potentially-evaluated expression, so this declaration is
10121 // "used"; handle this below.
10122 break;
Mike Stump11289f42009-09-09 15:08:12 +000010123
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010124 case PotentiallyPotentiallyEvaluated:
10125 // We are in an expression that may be potentially evaluated; queue this
10126 // declaration reference until we know whether the expression is
10127 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +000010128 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010129 return;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010130
10131 case PotentiallyEvaluatedIfUsed:
10132 // Referenced declarations will only be used if the construct in the
10133 // containing expression is used.
10134 return;
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010135 }
Mike Stump11289f42009-09-09 15:08:12 +000010136
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010137 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +000010138 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Alexis Huntf92197c2011-05-12 03:51:51 +000010139 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor()) {
10140 if (Constructor->isTrivial())
Chandler Carruthc9262402010-08-23 07:55:51 +000010141 return;
10142 if (!Constructor->isUsed(false))
10143 DefineImplicitDefaultConstructor(Loc, Constructor);
Alexis Hunt22b5b132011-05-14 18:20:50 +000010144 } else if (Constructor->isDefaulted() &&
Alexis Hunt913820d2011-05-13 06:10:58 +000010145 Constructor->isCopyConstructor()) {
Douglas Gregorebada0772010-06-17 23:14:26 +000010146 if (!Constructor->isUsed(false))
Alexis Hunt913820d2011-05-13 06:10:58 +000010147 DefineImplicitCopyConstructor(Loc, Constructor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010148 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010149
Douglas Gregor88d292c2010-05-13 16:44:06 +000010150 MarkVTableUsed(Loc, Constructor->getParent());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010151 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Alexis Huntf91729462011-05-12 22:46:25 +000010152 if (Destructor->isDefaulted() && !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010153 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010154 if (Destructor->isVirtual())
10155 MarkVTableUsed(Loc, Destructor->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010156 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
Alexis Huntc9a55732011-05-14 05:23:28 +000010157 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010158 MethodDecl->getOverloadedOperator() == OO_Equal) {
Douglas Gregorebada0772010-06-17 23:14:26 +000010159 if (!MethodDecl->isUsed(false))
Douglas Gregora57478e2010-05-01 15:04:51 +000010160 DefineImplicitCopyAssignment(Loc, MethodDecl);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010161 } else if (MethodDecl->isVirtual())
10162 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010163 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +000010164 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall83779672011-02-19 02:53:41 +000010165 // Recursive functions should be marked when used from another function.
10166 if (CurContext == Function) return;
10167
Mike Stump11289f42009-09-09 15:08:12 +000010168 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +000010169 // class templates.
Douglas Gregor69f6a362010-05-17 17:34:56 +000010170 if (Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +000010171 bool AlreadyInstantiated = false;
10172 if (FunctionTemplateSpecializationInfo *SpecInfo
10173 = Function->getTemplateSpecializationInfo()) {
10174 if (SpecInfo->getPointOfInstantiation().isInvalid())
10175 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010176 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +000010177 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +000010178 AlreadyInstantiated = true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010179 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregor06db9f52009-10-12 20:18:28 +000010180 = Function->getMemberSpecializationInfo()) {
10181 if (MSInfo->getPointOfInstantiation().isInvalid())
10182 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010183 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregorafca3b42009-10-27 20:53:28 +000010184 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +000010185 AlreadyInstantiated = true;
10186 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010187
Douglas Gregor7f792cf2010-01-16 22:29:39 +000010188 if (!AlreadyInstantiated) {
10189 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
10190 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
10191 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
10192 Loc));
10193 else
Chandler Carruth54080172010-08-25 08:44:16 +000010194 PendingInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregor7f792cf2010-01-16 22:29:39 +000010195 }
John McCall83779672011-02-19 02:53:41 +000010196 } else {
10197 // Walk redefinitions, as some of them may be instantiable.
Gabor Greifb6aba3e2010-08-28 00:16:06 +000010198 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
10199 e(Function->redecls_end()); i != e; ++i) {
Gabor Greif34ecff22010-08-28 01:58:12 +000010200 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
Gabor Greifb6aba3e2010-08-28 00:16:06 +000010201 MarkDeclarationReferenced(Loc, *i);
10202 }
John McCall83779672011-02-19 02:53:41 +000010203 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010204
John McCall83779672011-02-19 02:53:41 +000010205 // Keep track of used but undefined functions.
10206 if (!Function->isPure() && !Function->hasBody() &&
10207 Function->getLinkage() != ExternalLinkage) {
10208 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
10209 if (old.isInvalid()) old = Loc;
10210 }
Argyrios Kyrtzidisdfffabd2010-08-25 10:34:54 +000010211
John McCall83779672011-02-19 02:53:41 +000010212 Function->setUsed(true);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010213 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +000010214 }
Mike Stump11289f42009-09-09 15:08:12 +000010215
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010216 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +000010217 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +000010218 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +000010219 Var->getInstantiatedFromStaticDataMember()) {
10220 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10221 assert(MSInfo && "Missing member specialization information?");
10222 if (MSInfo->getPointOfInstantiation().isInvalid() &&
10223 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
10224 MSInfo->setPointOfInstantiation(Loc);
Sebastian Redl2ac2c722011-04-29 08:19:30 +000010225 // This is a modification of an existing AST node. Notify listeners.
10226 if (ASTMutationListener *L = getASTMutationListener())
10227 L->StaticDataMemberInstantiated(Var);
Chandler Carruth54080172010-08-25 08:44:16 +000010228 PendingInstantiations.push_back(std::make_pair(Var, Loc));
Douglas Gregor06db9f52009-10-12 20:18:28 +000010229 }
10230 }
Mike Stump11289f42009-09-09 15:08:12 +000010231
John McCall15dd4042011-02-21 19:25:48 +000010232 // Keep track of used but undefined variables. We make a hole in
10233 // the warning for static const data members with in-line
10234 // initializers.
John McCall83779672011-02-19 02:53:41 +000010235 if (Var->hasDefinition() == VarDecl::DeclarationOnly
John McCall15dd4042011-02-21 19:25:48 +000010236 && Var->getLinkage() != ExternalLinkage
10237 && !(Var->isStaticDataMember() && Var->hasInit())) {
John McCall83779672011-02-19 02:53:41 +000010238 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
10239 if (old.isInvalid()) old = Loc;
10240 }
Douglas Gregora6ef8f02009-07-24 20:34:43 +000010241
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010242 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +000010243 return;
Sam Weinigbae69142009-09-11 03:29:30 +000010244 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010245}
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010246
Douglas Gregor5597ab42010-05-07 23:12:07 +000010247namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +000010248 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +000010249 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +000010250 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +000010251 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10252 Sema &S;
10253 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010254
Douglas Gregor5597ab42010-05-07 23:12:07 +000010255 public:
10256 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010257
Douglas Gregor5597ab42010-05-07 23:12:07 +000010258 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010259
10260 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10261 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010262 };
10263}
10264
Chandler Carruthaf80f662010-06-09 08:17:30 +000010265bool MarkReferencedDecls::TraverseTemplateArgument(
10266 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010267 if (Arg.getKind() == TemplateArgument::Declaration) {
10268 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
10269 }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010270
10271 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010272}
10273
Chandler Carruthaf80f662010-06-09 08:17:30 +000010274bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010275 if (ClassTemplateSpecializationDecl *Spec
10276 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10277 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +000010278 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +000010279 }
10280
Chandler Carruthc65667c2010-06-10 10:31:57 +000010281 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +000010282}
10283
10284void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10285 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000010286 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000010287}
10288
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010289namespace {
10290 /// \brief Helper class that marks all of the declarations referenced by
10291 /// potentially-evaluated subexpressions as "referenced".
10292 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10293 Sema &S;
10294
10295 public:
10296 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10297
10298 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
10299
10300 void VisitDeclRefExpr(DeclRefExpr *E) {
10301 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10302 }
10303
10304 void VisitMemberExpr(MemberExpr *E) {
10305 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010306 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010307 }
10308
10309 void VisitCXXNewExpr(CXXNewExpr *E) {
10310 if (E->getConstructor())
10311 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
10312 if (E->getOperatorNew())
10313 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
10314 if (E->getOperatorDelete())
10315 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010316 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010317 }
10318
10319 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10320 if (E->getOperatorDelete())
10321 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000010322 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10323 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10324 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10325 S.MarkDeclarationReferenced(E->getLocStart(),
10326 S.LookupDestructor(Record));
10327 }
10328
Douglas Gregor32b3de52010-09-11 23:32:50 +000010329 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010330 }
10331
10332 void VisitCXXConstructExpr(CXXConstructExpr *E) {
10333 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010334 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010335 }
10336
10337 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
10338 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
10339 }
Douglas Gregorf0873f42010-10-19 17:17:35 +000010340
10341 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10342 Visit(E->getExpr());
10343 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010344 };
10345}
10346
10347/// \brief Mark any declarations that appear within this expression or any
10348/// potentially-evaluated subexpressions as "referenced".
10349void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
10350 EvaluatedExprMarker(*this).Visit(E);
10351}
10352
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010353/// \brief Emit a diagnostic that describes an effect on the run-time behavior
10354/// of the program being compiled.
10355///
10356/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010357/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010358/// possibility that the code will actually be executable. Code in sizeof()
10359/// expressions, code used only during overload resolution, etc., are not
10360/// potentially evaluated. This routine will suppress such diagnostics or,
10361/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010362/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010363/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010364///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010365/// This routine should be used for all diagnostics that describe the run-time
10366/// behavior of a program, such as passing a non-POD value through an ellipsis.
10367/// Failure to do so will likely result in spurious diagnostics or failures
10368/// during overload resolution or within sizeof/alignof/typeof/typeid.
Ted Kremenek55ae3192011-02-23 01:51:43 +000010369bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010370 const PartialDiagnostic &PD) {
10371 switch (ExprEvalContexts.back().Context ) {
10372 case Unevaluated:
10373 // The argument will never be evaluated, so don't complain.
10374 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010375
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010376 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010377 case PotentiallyEvaluatedIfUsed:
Ted Kremenek3427fac2011-02-23 01:52:04 +000010378 if (stmt && getCurFunctionOrMethodDecl()) {
10379 FunctionScopes.back()->PossiblyUnreachableDiags.
10380 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt));
10381 }
10382 else
10383 Diag(Loc, PD);
10384
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010385 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010386
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010387 case PotentiallyPotentiallyEvaluated:
10388 ExprEvalContexts.back().addDiagnostic(Loc, PD);
10389 break;
10390 }
10391
10392 return false;
10393}
10394
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010395bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
10396 CallExpr *CE, FunctionDecl *FD) {
10397 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
10398 return false;
10399
10400 PartialDiagnostic Note =
10401 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
10402 << FD->getDeclName() : PDiag();
10403 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010404
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010405 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010406 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010407 PDiag(diag::err_call_function_incomplete_return)
10408 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010409 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010410 << CE->getSourceRange(),
10411 std::make_pair(NoteLoc, Note)))
10412 return true;
10413
10414 return false;
10415}
10416
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010417// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000010418// will prevent this condition from triggering, which is what we want.
10419void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
10420 SourceLocation Loc;
10421
John McCall0506e4a2009-11-11 02:41:58 +000010422 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010423 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000010424
John McCalld5707ab2009-10-12 21:59:07 +000010425 if (isa<BinaryOperator>(E)) {
10426 BinaryOperator *Op = cast<BinaryOperator>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010427 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000010428 return;
10429
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010430 IsOrAssign = Op->getOpcode() == BO_OrAssign;
10431
John McCallb0e419e2009-11-12 00:06:05 +000010432 // Greylist some idioms by putting them into a warning subcategory.
10433 if (ObjCMessageExpr *ME
10434 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
10435 Selector Sel = ME->getSelector();
10436
John McCallb0e419e2009-11-12 00:06:05 +000010437 // self = [<foo> init...]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000010438 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +000010439 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10440
10441 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000010442 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000010443 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10444 }
John McCall0506e4a2009-11-11 02:41:58 +000010445
John McCalld5707ab2009-10-12 21:59:07 +000010446 Loc = Op->getOperatorLoc();
10447 } else if (isa<CXXOperatorCallExpr>(E)) {
10448 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010449 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000010450 return;
10451
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010452 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000010453 Loc = Op->getOperatorLoc();
10454 } else {
10455 // Not an assignment.
10456 return;
10457 }
10458
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000010459 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010460
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000010461 SourceLocation Open = E->getSourceRange().getBegin();
10462 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
10463 Diag(Loc, diag::note_condition_assign_silence)
10464 << FixItHint::CreateInsertion(Open, "(")
10465 << FixItHint::CreateInsertion(Close, ")");
10466
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010467 if (IsOrAssign)
10468 Diag(Loc, diag::note_condition_or_assign_to_comparison)
10469 << FixItHint::CreateReplacement(Loc, "!=");
10470 else
10471 Diag(Loc, diag::note_condition_assign_to_comparison)
10472 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +000010473}
10474
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010475/// \brief Redundant parentheses over an equality comparison can indicate
10476/// that the user intended an assignment used as condition.
10477void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010478 // Don't warn if the parens came from a macro.
10479 SourceLocation parenLoc = parenE->getLocStart();
10480 if (parenLoc.isInvalid() || parenLoc.isMacroID())
10481 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000010482 // Don't warn for dependent expressions.
10483 if (parenE->isTypeDependent())
10484 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010485
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010486 Expr *E = parenE->IgnoreParens();
10487
10488 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000010489 if (opE->getOpcode() == BO_EQ &&
10490 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
10491 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010492 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000010493
Ted Kremenekae022092011-02-02 02:20:30 +000010494 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +000010495 Diag(Loc, diag::note_equality_comparison_silence)
10496 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
10497 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000010498 Diag(Loc, diag::note_equality_comparison_to_assign)
10499 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010500 }
10501}
10502
John Wiegley01296292011-04-08 18:41:53 +000010503ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000010504 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010505 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
10506 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000010507
John McCall0009fcc2011-04-26 20:42:42 +000010508 ExprResult result = CheckPlaceholderExpr(E);
10509 if (result.isInvalid()) return ExprError();
10510 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000010511
John McCall0009fcc2011-04-26 20:42:42 +000010512 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +000010513 if (getLangOptions().CPlusPlus)
10514 return CheckCXXBooleanCondition(E); // C++ 6.4p4
10515
John Wiegley01296292011-04-08 18:41:53 +000010516 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
10517 if (ERes.isInvalid())
10518 return ExprError();
10519 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +000010520
10521 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000010522 if (!T->isScalarType()) { // C99 6.8.4.1p1
10523 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
10524 << T << E->getSourceRange();
10525 return ExprError();
10526 }
John McCalld5707ab2009-10-12 21:59:07 +000010527 }
10528
John Wiegley01296292011-04-08 18:41:53 +000010529 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +000010530}
Douglas Gregore60e41a2010-05-06 17:25:47 +000010531
John McCalldadc5752010-08-24 06:29:42 +000010532ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
10533 Expr *Sub) {
Douglas Gregor12cc7ee2010-05-06 21:39:56 +000010534 if (!Sub)
Douglas Gregore60e41a2010-05-06 17:25:47 +000010535 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010536
10537 return CheckBooleanCondition(Sub, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000010538}
John McCall36e7fe32010-10-12 00:20:44 +000010539
John McCall31996342011-04-07 08:22:57 +000010540namespace {
John McCall2979fe02011-04-12 00:42:48 +000010541 /// A visitor for rebuilding a call to an __unknown_any expression
10542 /// to have an appropriate type.
10543 struct RebuildUnknownAnyFunction
10544 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
10545
10546 Sema &S;
10547
10548 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
10549
10550 ExprResult VisitStmt(Stmt *S) {
10551 llvm_unreachable("unexpected statement!");
10552 return ExprError();
10553 }
10554
10555 ExprResult VisitExpr(Expr *expr) {
10556 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call)
10557 << expr->getSourceRange();
10558 return ExprError();
10559 }
10560
10561 /// Rebuild an expression which simply semantically wraps another
10562 /// expression which it shares the type and value kind of.
10563 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10564 ExprResult subResult = Visit(expr->getSubExpr());
10565 if (subResult.isInvalid()) return ExprError();
10566
10567 Expr *subExpr = subResult.take();
10568 expr->setSubExpr(subExpr);
10569 expr->setType(subExpr->getType());
10570 expr->setValueKind(subExpr->getValueKind());
10571 assert(expr->getObjectKind() == OK_Ordinary);
10572 return expr;
10573 }
10574
10575 ExprResult VisitParenExpr(ParenExpr *paren) {
10576 return rebuildSugarExpr(paren);
10577 }
10578
10579 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10580 return rebuildSugarExpr(op);
10581 }
10582
10583 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10584 ExprResult subResult = Visit(op->getSubExpr());
10585 if (subResult.isInvalid()) return ExprError();
10586
10587 Expr *subExpr = subResult.take();
10588 op->setSubExpr(subExpr);
10589 op->setType(S.Context.getPointerType(subExpr->getType()));
10590 assert(op->getValueKind() == VK_RValue);
10591 assert(op->getObjectKind() == OK_Ordinary);
10592 return op;
10593 }
10594
10595 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) {
10596 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr);
10597
10598 expr->setType(decl->getType());
10599
10600 assert(expr->getValueKind() == VK_RValue);
10601 if (S.getLangOptions().CPlusPlus &&
10602 !(isa<CXXMethodDecl>(decl) &&
10603 cast<CXXMethodDecl>(decl)->isInstance()))
10604 expr->setValueKind(VK_LValue);
10605
10606 return expr;
10607 }
10608
10609 ExprResult VisitMemberExpr(MemberExpr *mem) {
10610 return resolveDecl(mem, mem->getMemberDecl());
10611 }
10612
10613 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
10614 return resolveDecl(ref, ref->getDecl());
10615 }
10616 };
10617}
10618
10619/// Given a function expression of unknown-any type, try to rebuild it
10620/// to have a function type.
10621static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) {
10622 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn);
10623 if (result.isInvalid()) return ExprError();
10624 return S.DefaultFunctionArrayConversion(result.take());
10625}
10626
10627namespace {
John McCall2d2e8702011-04-11 07:02:50 +000010628 /// A visitor for rebuilding an expression of type __unknown_anytype
10629 /// into one which resolves the type directly on the referring
10630 /// expression. Strict preservation of the original source
10631 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000010632 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000010633 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000010634
10635 Sema &S;
10636
10637 /// The current destination type.
10638 QualType DestType;
10639
10640 RebuildUnknownAnyExpr(Sema &S, QualType castType)
10641 : S(S), DestType(castType) {}
10642
John McCall39439732011-04-09 22:50:59 +000010643 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000010644 llvm_unreachable("unexpected statement!");
John McCall39439732011-04-09 22:50:59 +000010645 return ExprError();
John McCall31996342011-04-07 08:22:57 +000010646 }
10647
John McCall2d2e8702011-04-11 07:02:50 +000010648 ExprResult VisitExpr(Expr *expr) {
10649 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10650 << expr->getSourceRange();
10651 return ExprError();
John McCall31996342011-04-07 08:22:57 +000010652 }
10653
John McCall2d2e8702011-04-11 07:02:50 +000010654 ExprResult VisitCallExpr(CallExpr *call);
10655 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message);
10656
John McCall39439732011-04-09 22:50:59 +000010657 /// Rebuild an expression which simply semantically wraps another
10658 /// expression which it shares the type and value kind of.
10659 template <class T> ExprResult rebuildSugarExpr(T *expr) {
10660 ExprResult subResult = Visit(expr->getSubExpr());
John McCall2979fe02011-04-12 00:42:48 +000010661 if (subResult.isInvalid()) return ExprError();
John McCall39439732011-04-09 22:50:59 +000010662 Expr *subExpr = subResult.take();
10663 expr->setSubExpr(subExpr);
10664 expr->setType(subExpr->getType());
10665 expr->setValueKind(subExpr->getValueKind());
10666 assert(expr->getObjectKind() == OK_Ordinary);
10667 return expr;
10668 }
John McCall31996342011-04-07 08:22:57 +000010669
John McCall39439732011-04-09 22:50:59 +000010670 ExprResult VisitParenExpr(ParenExpr *paren) {
10671 return rebuildSugarExpr(paren);
10672 }
10673
10674 ExprResult VisitUnaryExtension(UnaryOperator *op) {
10675 return rebuildSugarExpr(op);
10676 }
10677
John McCall2979fe02011-04-12 00:42:48 +000010678 ExprResult VisitUnaryAddrOf(UnaryOperator *op) {
10679 const PointerType *ptr = DestType->getAs<PointerType>();
10680 if (!ptr) {
10681 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof)
10682 << op->getSourceRange();
10683 return ExprError();
10684 }
10685 assert(op->getValueKind() == VK_RValue);
10686 assert(op->getObjectKind() == OK_Ordinary);
10687 op->setType(DestType);
10688
10689 // Build the sub-expression as if it were an object of the pointee type.
10690 DestType = ptr->getPointeeType();
10691 ExprResult subResult = Visit(op->getSubExpr());
10692 if (subResult.isInvalid()) return ExprError();
10693 op->setSubExpr(subResult.take());
10694 return op;
10695 }
10696
John McCall2d2e8702011-04-11 07:02:50 +000010697 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice);
John McCall39439732011-04-09 22:50:59 +000010698
John McCall2979fe02011-04-12 00:42:48 +000010699 ExprResult resolveDecl(Expr *expr, ValueDecl *decl);
John McCall39439732011-04-09 22:50:59 +000010700
John McCall2979fe02011-04-12 00:42:48 +000010701 ExprResult VisitMemberExpr(MemberExpr *mem) {
10702 return resolveDecl(mem, mem->getMemberDecl());
10703 }
John McCall39439732011-04-09 22:50:59 +000010704
10705 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) {
John McCall2d2e8702011-04-11 07:02:50 +000010706 return resolveDecl(ref, ref->getDecl());
John McCall31996342011-04-07 08:22:57 +000010707 }
10708 };
10709}
10710
John McCall2d2e8702011-04-11 07:02:50 +000010711/// Rebuilds a call expression which yielded __unknown_anytype.
10712ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) {
10713 Expr *callee = call->getCallee();
10714
10715 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +000010716 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +000010717 FK_FunctionPointer,
10718 FK_BlockPointer
10719 };
10720
10721 FnKind kind;
10722 QualType type = callee->getType();
John McCall4adb38c2011-04-27 00:36:17 +000010723 if (type == S.Context.BoundMemberTy) {
10724 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call));
10725 kind = FK_MemberFunction;
10726 type = Expr::findBoundMemberType(callee);
John McCall2d2e8702011-04-11 07:02:50 +000010727 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
10728 type = ptr->getPointeeType();
10729 kind = FK_FunctionPointer;
10730 } else {
10731 type = type->castAs<BlockPointerType>()->getPointeeType();
10732 kind = FK_BlockPointer;
10733 }
10734 const FunctionType *fnType = type->castAs<FunctionType>();
10735
10736 // Verify that this is a legal result type of a function.
10737 if (DestType->isArrayType() || DestType->isFunctionType()) {
10738 unsigned diagID = diag::err_func_returning_array_function;
10739 if (kind == FK_BlockPointer)
10740 diagID = diag::err_block_returning_array_function;
10741
10742 S.Diag(call->getExprLoc(), diagID)
10743 << DestType->isFunctionType() << DestType;
10744 return ExprError();
10745 }
10746
10747 // Otherwise, go ahead and set DestType as the call's result.
10748 call->setType(DestType.getNonLValueExprType(S.Context));
10749 call->setValueKind(Expr::getValueKindForType(DestType));
10750 assert(call->getObjectKind() == OK_Ordinary);
10751
10752 // Rebuild the function type, replacing the result type with DestType.
10753 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType))
10754 DestType = S.Context.getFunctionType(DestType,
10755 proto->arg_type_begin(),
10756 proto->getNumArgs(),
10757 proto->getExtProtoInfo());
10758 else
10759 DestType = S.Context.getFunctionNoProtoType(DestType,
10760 fnType->getExtInfo());
10761
10762 // Rebuild the appropriate pointer-to-function type.
10763 switch (kind) {
John McCall4adb38c2011-04-27 00:36:17 +000010764 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +000010765 // Nothing to do.
10766 break;
10767
10768 case FK_FunctionPointer:
10769 DestType = S.Context.getPointerType(DestType);
10770 break;
10771
10772 case FK_BlockPointer:
10773 DestType = S.Context.getBlockPointerType(DestType);
10774 break;
10775 }
10776
10777 // Finally, we can recurse.
10778 ExprResult calleeResult = Visit(callee);
10779 if (!calleeResult.isUsable()) return ExprError();
10780 call->setCallee(calleeResult.take());
10781
10782 // Bind a temporary if necessary.
10783 return S.MaybeBindToTemporary(call);
10784}
10785
10786ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) {
John McCall2979fe02011-04-12 00:42:48 +000010787 ObjCMethodDecl *method = msg->getMethodDecl();
10788 assert(method && "__unknown_anytype message without result type?");
John McCall2d2e8702011-04-11 07:02:50 +000010789
John McCall2979fe02011-04-12 00:42:48 +000010790 // Verify that this is a legal result type of a call.
10791 if (DestType->isArrayType() || DestType->isFunctionType()) {
10792 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function)
10793 << DestType->isFunctionType() << DestType;
10794 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010795 }
10796
John McCall2979fe02011-04-12 00:42:48 +000010797 assert(method->getResultType() == S.Context.UnknownAnyTy);
10798 method->setResultType(DestType);
10799
John McCall2d2e8702011-04-11 07:02:50 +000010800 // Change the type of the message.
John McCall2979fe02011-04-12 00:42:48 +000010801 msg->setType(DestType.getNonReferenceType());
10802 msg->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000010803
John McCall2979fe02011-04-12 00:42:48 +000010804 return S.MaybeBindToTemporary(msg);
John McCall2d2e8702011-04-11 07:02:50 +000010805}
10806
10807ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) {
John McCall2979fe02011-04-12 00:42:48 +000010808 // The only case we should ever see here is a function-to-pointer decay.
John McCall2d2e8702011-04-11 07:02:50 +000010809 assert(ice->getCastKind() == CK_FunctionToPointerDecay);
John McCall2d2e8702011-04-11 07:02:50 +000010810 assert(ice->getValueKind() == VK_RValue);
10811 assert(ice->getObjectKind() == OK_Ordinary);
10812
John McCall2979fe02011-04-12 00:42:48 +000010813 ice->setType(DestType);
10814
John McCall2d2e8702011-04-11 07:02:50 +000010815 // Rebuild the sub-expression as the pointee (function) type.
10816 DestType = DestType->castAs<PointerType>()->getPointeeType();
10817
10818 ExprResult result = Visit(ice->getSubExpr());
10819 if (!result.isUsable()) return ExprError();
10820
10821 ice->setSubExpr(result.take());
10822 return S.Owned(ice);
10823}
10824
John McCall2979fe02011-04-12 00:42:48 +000010825ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) {
John McCall2d2e8702011-04-11 07:02:50 +000010826 ExprValueKind valueKind = VK_LValue;
John McCall2d2e8702011-04-11 07:02:50 +000010827 QualType type = DestType;
10828
10829 // We know how to make this work for certain kinds of decls:
10830
10831 // - functions
John McCall2979fe02011-04-12 00:42:48 +000010832 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
John McCall2d2e8702011-04-11 07:02:50 +000010833 // This is true because FunctionDecls must always have function
10834 // type, so we can't be resolving the entire thing at once.
10835 assert(type->isFunctionType());
10836
John McCall4adb38c2011-04-27 00:36:17 +000010837 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn))
10838 if (method->isInstance()) {
10839 valueKind = VK_RValue;
10840 type = S.Context.BoundMemberTy;
10841 }
10842
John McCall2d2e8702011-04-11 07:02:50 +000010843 // Function references aren't l-values in C.
10844 if (!S.getLangOptions().CPlusPlus)
10845 valueKind = VK_RValue;
10846
10847 // - variables
10848 } else if (isa<VarDecl>(decl)) {
John McCall2979fe02011-04-12 00:42:48 +000010849 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) {
10850 type = refTy->getPointeeType();
John McCall2d2e8702011-04-11 07:02:50 +000010851 } else if (type->isFunctionType()) {
John McCall2979fe02011-04-12 00:42:48 +000010852 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type)
10853 << decl << expr->getSourceRange();
10854 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010855 }
10856
10857 // - nothing else
10858 } else {
10859 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10860 << decl << expr->getSourceRange();
10861 return ExprError();
10862 }
10863
John McCall2979fe02011-04-12 00:42:48 +000010864 decl->setType(DestType);
10865 expr->setType(type);
10866 expr->setValueKind(valueKind);
10867 return S.Owned(expr);
John McCall2d2e8702011-04-11 07:02:50 +000010868}
10869
John McCall31996342011-04-07 08:22:57 +000010870/// Check a cast of an unknown-any type. We intentionally only
10871/// trigger this for C-style casts.
John Wiegley01296292011-04-08 18:41:53 +000010872ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType,
10873 Expr *castExpr, CastKind &castKind,
10874 ExprValueKind &VK, CXXCastPath &path) {
John McCall31996342011-04-07 08:22:57 +000010875 // Rewrite the casted expression from scratch.
John McCall39439732011-04-09 22:50:59 +000010876 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr);
10877 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000010878
John McCall39439732011-04-09 22:50:59 +000010879 castExpr = result.take();
10880 VK = castExpr->getValueKind();
10881 castKind = CK_NoOp;
10882
10883 return castExpr;
John McCall31996342011-04-07 08:22:57 +000010884}
10885
10886static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) {
10887 Expr *orig = e;
John McCall2d2e8702011-04-11 07:02:50 +000010888 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000010889 while (true) {
10890 e = e->IgnoreParenImpCasts();
John McCall2d2e8702011-04-11 07:02:50 +000010891 if (CallExpr *call = dyn_cast<CallExpr>(e)) {
John McCall31996342011-04-07 08:22:57 +000010892 e = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000010893 diagID = diag::err_uncasted_call_of_unknown_any;
10894 } else {
John McCall31996342011-04-07 08:22:57 +000010895 break;
John McCall2d2e8702011-04-11 07:02:50 +000010896 }
John McCall31996342011-04-07 08:22:57 +000010897 }
10898
John McCall2d2e8702011-04-11 07:02:50 +000010899 SourceLocation loc;
10900 NamedDecl *d;
10901 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10902 loc = ref->getLocation();
10903 d = ref->getDecl();
10904 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) {
10905 loc = mem->getMemberLoc();
10906 d = mem->getMemberDecl();
10907 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) {
10908 diagID = diag::err_uncasted_call_of_unknown_any;
10909 loc = msg->getSelectorLoc();
10910 d = msg->getMethodDecl();
10911 assert(d && "unknown method returning __unknown_any?");
10912 } else {
10913 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10914 << e->getSourceRange();
10915 return ExprError();
10916 }
10917
10918 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000010919
10920 // Never recoverable.
10921 return ExprError();
10922}
10923
John McCall36e7fe32010-10-12 00:20:44 +000010924/// Check for operands with placeholder types and complain if found.
10925/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000010926ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall31996342011-04-07 08:22:57 +000010927 // Placeholder types are always *exactly* the appropriate builtin type.
10928 QualType type = E->getType();
John McCall36e7fe32010-10-12 00:20:44 +000010929
John McCall31996342011-04-07 08:22:57 +000010930 // Overloaded expressions.
10931 if (type == Context.OverloadTy)
10932 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true,
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010933 E->getSourceRange(),
John McCall31996342011-04-07 08:22:57 +000010934 QualType(),
10935 diag::err_ovl_unresolvable);
10936
John McCall0009fcc2011-04-26 20:42:42 +000010937 // Bound member functions.
10938 if (type == Context.BoundMemberTy) {
10939 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
10940 << E->getSourceRange();
10941 return ExprError();
10942 }
10943
John McCall31996342011-04-07 08:22:57 +000010944 // Expressions of unknown type.
10945 if (type == Context.UnknownAnyTy)
10946 return diagnoseUnknownAnyExpr(*this, E);
10947
10948 assert(!type->isPlaceholderType());
10949 return Owned(E);
John McCall36e7fe32010-10-12 00:20:44 +000010950}
Richard Trieu2c850c02011-04-21 21:44:26 +000010951
10952bool Sema::CheckCaseExpression(Expr *expr) {
10953 if (expr->isTypeDependent())
10954 return true;
10955 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context))
10956 return expr->getType()->isIntegralOrEnumerationType();
10957 return false;
10958}